three.webgpu.js 1.9 MB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946219472194821949219502195121952219532195421955219562195721958219592196021961219622196321964219652196621967219682196921970219712197221973219742197521976219772197821979219802198121982219832198421985219862198721988219892199021991219922199321994219952199621997219982199922000220012200222003220042200522006220072200822009220102201122012220132201422015220162201722018220192202022021220222202322024220252202622027220282202922030220312203222033220342203522036220372203822039220402204122042220432204422045220462204722048220492205022051220522205322054220552205622057220582205922060220612206222063220642206522066220672206822069220702207122072220732207422075220762207722078220792208022081220822208322084220852208622087220882208922090220912209222093220942209522096220972209822099221002210122102221032210422105221062210722108221092211022111221122211322114221152211622117221182211922120221212212222123221242212522126221272212822129221302213122132221332213422135221362213722138221392214022141221422214322144221452214622147221482214922150221512215222153221542215522156221572215822159221602216122162221632216422165221662216722168221692217022171221722217322174221752217622177221782217922180221812218222183221842218522186221872218822189221902219122192221932219422195221962219722198221992220022201222022220322204222052220622207222082220922210222112221222213222142221522216222172221822219222202222122222222232222422225222262222722228222292223022231222322223322234222352223622237222382223922240222412224222243222442224522246222472224822249222502225122252222532225422255222562225722258222592226022261222622226322264222652226622267222682226922270222712227222273222742227522276222772227822279222802228122282222832228422285222862228722288222892229022291222922229322294222952229622297222982229922300223012230222303223042230522306223072230822309223102231122312223132231422315223162231722318223192232022321223222232322324223252232622327223282232922330223312233222333223342233522336223372233822339223402234122342223432234422345223462234722348223492235022351223522235322354223552235622357223582235922360223612236222363223642236522366223672236822369223702237122372223732237422375223762237722378223792238022381223822238322384223852238622387223882238922390223912239222393223942239522396223972239822399224002240122402224032240422405224062240722408224092241022411224122241322414224152241622417224182241922420224212242222423224242242522426224272242822429224302243122432224332243422435224362243722438224392244022441224422244322444224452244622447224482244922450224512245222453224542245522456224572245822459224602246122462224632246422465224662246722468224692247022471224722247322474224752247622477224782247922480224812248222483224842248522486224872248822489224902249122492224932249422495224962249722498224992250022501225022250322504225052250622507225082250922510225112251222513225142251522516225172251822519225202252122522225232252422525225262252722528225292253022531225322253322534225352253622537225382253922540225412254222543225442254522546225472254822549225502255122552225532255422555225562255722558225592256022561225622256322564225652256622567225682256922570225712257222573225742257522576225772257822579225802258122582225832258422585225862258722588225892259022591225922259322594225952259622597225982259922600226012260222603226042260522606226072260822609226102261122612226132261422615226162261722618226192262022621226222262322624226252262622627226282262922630226312263222633226342263522636226372263822639226402264122642226432264422645226462264722648226492265022651226522265322654226552265622657226582265922660226612266222663226642266522666226672266822669226702267122672226732267422675226762267722678226792268022681226822268322684226852268622687226882268922690226912269222693226942269522696226972269822699227002270122702227032270422705227062270722708227092271022711227122271322714227152271622717227182271922720227212272222723227242272522726227272272822729227302273122732227332273422735227362273722738227392274022741227422274322744227452274622747227482274922750227512275222753227542275522756227572275822759227602276122762227632276422765227662276722768227692277022771227722277322774227752277622777227782277922780227812278222783227842278522786227872278822789227902279122792227932279422795227962279722798227992280022801228022280322804228052280622807228082280922810228112281222813228142281522816228172281822819228202282122822228232282422825228262282722828228292283022831228322283322834228352283622837228382283922840228412284222843228442284522846228472284822849228502285122852228532285422855228562285722858228592286022861228622286322864228652286622867228682286922870228712287222873228742287522876228772287822879228802288122882228832288422885228862288722888228892289022891228922289322894228952289622897228982289922900229012290222903229042290522906229072290822909229102291122912229132291422915229162291722918229192292022921229222292322924229252292622927229282292922930229312293222933229342293522936229372293822939229402294122942229432294422945229462294722948229492295022951229522295322954229552295622957229582295922960229612296222963229642296522966229672296822969229702297122972229732297422975229762297722978229792298022981229822298322984229852298622987229882298922990229912299222993229942299522996229972299822999230002300123002230032300423005230062300723008230092301023011230122301323014230152301623017230182301923020230212302223023230242302523026230272302823029230302303123032230332303423035230362303723038230392304023041230422304323044230452304623047230482304923050230512305223053230542305523056230572305823059230602306123062230632306423065230662306723068230692307023071230722307323074230752307623077230782307923080230812308223083230842308523086230872308823089230902309123092230932309423095230962309723098230992310023101231022310323104231052310623107231082310923110231112311223113231142311523116231172311823119231202312123122231232312423125231262312723128231292313023131231322313323134231352313623137231382313923140231412314223143231442314523146231472314823149231502315123152231532315423155231562315723158231592316023161231622316323164231652316623167231682316923170231712317223173231742317523176231772317823179231802318123182231832318423185231862318723188231892319023191231922319323194231952319623197231982319923200232012320223203232042320523206232072320823209232102321123212232132321423215232162321723218232192322023221232222322323224232252322623227232282322923230232312323223233232342323523236232372323823239232402324123242232432324423245232462324723248232492325023251232522325323254232552325623257232582325923260232612326223263232642326523266232672326823269232702327123272232732327423275232762327723278232792328023281232822328323284232852328623287232882328923290232912329223293232942329523296232972329823299233002330123302233032330423305233062330723308233092331023311233122331323314233152331623317233182331923320233212332223323233242332523326233272332823329233302333123332233332333423335233362333723338233392334023341233422334323344233452334623347233482334923350233512335223353233542335523356233572335823359233602336123362233632336423365233662336723368233692337023371233722337323374233752337623377233782337923380233812338223383233842338523386233872338823389233902339123392233932339423395233962339723398233992340023401234022340323404234052340623407234082340923410234112341223413234142341523416234172341823419234202342123422234232342423425234262342723428234292343023431234322343323434234352343623437234382343923440234412344223443234442344523446234472344823449234502345123452234532345423455234562345723458234592346023461234622346323464234652346623467234682346923470234712347223473234742347523476234772347823479234802348123482234832348423485234862348723488234892349023491234922349323494234952349623497234982349923500235012350223503235042350523506235072350823509235102351123512235132351423515235162351723518235192352023521235222352323524235252352623527235282352923530235312353223533235342353523536235372353823539235402354123542235432354423545235462354723548235492355023551235522355323554235552355623557235582355923560235612356223563235642356523566235672356823569235702357123572235732357423575235762357723578235792358023581235822358323584235852358623587235882358923590235912359223593235942359523596235972359823599236002360123602236032360423605236062360723608236092361023611236122361323614236152361623617236182361923620236212362223623236242362523626236272362823629236302363123632236332363423635236362363723638236392364023641236422364323644236452364623647236482364923650236512365223653236542365523656236572365823659236602366123662236632366423665236662366723668236692367023671236722367323674236752367623677236782367923680236812368223683236842368523686236872368823689236902369123692236932369423695236962369723698236992370023701237022370323704237052370623707237082370923710237112371223713237142371523716237172371823719237202372123722237232372423725237262372723728237292373023731237322373323734237352373623737237382373923740237412374223743237442374523746237472374823749237502375123752237532375423755237562375723758237592376023761237622376323764237652376623767237682376923770237712377223773237742377523776237772377823779237802378123782237832378423785237862378723788237892379023791237922379323794237952379623797237982379923800238012380223803238042380523806238072380823809238102381123812238132381423815238162381723818238192382023821238222382323824238252382623827238282382923830238312383223833238342383523836238372383823839238402384123842238432384423845238462384723848238492385023851238522385323854238552385623857238582385923860238612386223863238642386523866238672386823869238702387123872238732387423875238762387723878238792388023881238822388323884238852388623887238882388923890238912389223893238942389523896238972389823899239002390123902239032390423905239062390723908239092391023911239122391323914239152391623917239182391923920239212392223923239242392523926239272392823929239302393123932239332393423935239362393723938239392394023941239422394323944239452394623947239482394923950239512395223953239542395523956239572395823959239602396123962239632396423965239662396723968239692397023971239722397323974239752397623977239782397923980239812398223983239842398523986239872398823989239902399123992239932399423995239962399723998239992400024001240022400324004240052400624007240082400924010240112401224013240142401524016240172401824019240202402124022240232402424025240262402724028240292403024031240322403324034240352403624037240382403924040240412404224043240442404524046240472404824049240502405124052240532405424055240562405724058240592406024061240622406324064240652406624067240682406924070240712407224073240742407524076240772407824079240802408124082240832408424085240862408724088240892409024091240922409324094240952409624097240982409924100241012410224103241042410524106241072410824109241102411124112241132411424115241162411724118241192412024121241222412324124241252412624127241282412924130241312413224133241342413524136241372413824139241402414124142241432414424145241462414724148241492415024151241522415324154241552415624157241582415924160241612416224163241642416524166241672416824169241702417124172241732417424175241762417724178241792418024181241822418324184241852418624187241882418924190241912419224193241942419524196241972419824199242002420124202242032420424205242062420724208242092421024211242122421324214242152421624217242182421924220242212422224223242242422524226242272422824229242302423124232242332423424235242362423724238242392424024241242422424324244242452424624247242482424924250242512425224253242542425524256242572425824259242602426124262242632426424265242662426724268242692427024271242722427324274242752427624277242782427924280242812428224283242842428524286242872428824289242902429124292242932429424295242962429724298242992430024301243022430324304243052430624307243082430924310243112431224313243142431524316243172431824319243202432124322243232432424325243262432724328243292433024331243322433324334243352433624337243382433924340243412434224343243442434524346243472434824349243502435124352243532435424355243562435724358243592436024361243622436324364243652436624367243682436924370243712437224373243742437524376243772437824379243802438124382243832438424385243862438724388243892439024391243922439324394243952439624397243982439924400244012440224403244042440524406244072440824409244102441124412244132441424415244162441724418244192442024421244222442324424244252442624427244282442924430244312443224433244342443524436244372443824439244402444124442244432444424445244462444724448244492445024451244522445324454244552445624457244582445924460244612446224463244642446524466244672446824469244702447124472244732447424475244762447724478244792448024481244822448324484244852448624487244882448924490244912449224493244942449524496244972449824499245002450124502245032450424505245062450724508245092451024511245122451324514245152451624517245182451924520245212452224523245242452524526245272452824529245302453124532245332453424535245362453724538245392454024541245422454324544245452454624547245482454924550245512455224553245542455524556245572455824559245602456124562245632456424565245662456724568245692457024571245722457324574245752457624577245782457924580245812458224583245842458524586245872458824589245902459124592245932459424595245962459724598245992460024601246022460324604246052460624607246082460924610246112461224613246142461524616246172461824619246202462124622246232462424625246262462724628246292463024631246322463324634246352463624637246382463924640246412464224643246442464524646246472464824649246502465124652246532465424655246562465724658246592466024661246622466324664246652466624667246682466924670246712467224673246742467524676246772467824679246802468124682246832468424685246862468724688246892469024691246922469324694246952469624697246982469924700247012470224703247042470524706247072470824709247102471124712247132471424715247162471724718247192472024721247222472324724247252472624727247282472924730247312473224733247342473524736247372473824739247402474124742247432474424745247462474724748247492475024751247522475324754247552475624757247582475924760247612476224763247642476524766247672476824769247702477124772247732477424775247762477724778247792478024781247822478324784247852478624787247882478924790247912479224793247942479524796247972479824799248002480124802248032480424805248062480724808248092481024811248122481324814248152481624817248182481924820248212482224823248242482524826248272482824829248302483124832248332483424835248362483724838248392484024841248422484324844248452484624847248482484924850248512485224853248542485524856248572485824859248602486124862248632486424865248662486724868248692487024871248722487324874248752487624877248782487924880248812488224883248842488524886248872488824889248902489124892248932489424895248962489724898248992490024901249022490324904249052490624907249082490924910249112491224913249142491524916249172491824919249202492124922249232492424925249262492724928249292493024931249322493324934249352493624937249382493924940249412494224943249442494524946249472494824949249502495124952249532495424955249562495724958249592496024961249622496324964249652496624967249682496924970249712497224973249742497524976249772497824979249802498124982249832498424985249862498724988249892499024991249922499324994249952499624997249982499925000250012500225003250042500525006250072500825009250102501125012250132501425015250162501725018250192502025021250222502325024250252502625027250282502925030250312503225033250342503525036250372503825039250402504125042250432504425045250462504725048250492505025051250522505325054250552505625057250582505925060250612506225063250642506525066250672506825069250702507125072250732507425075250762507725078250792508025081250822508325084250852508625087250882508925090250912509225093250942509525096250972509825099251002510125102251032510425105251062510725108251092511025111251122511325114251152511625117251182511925120251212512225123251242512525126251272512825129251302513125132251332513425135251362513725138251392514025141251422514325144251452514625147251482514925150251512515225153251542515525156251572515825159251602516125162251632516425165251662516725168251692517025171251722517325174251752517625177251782517925180251812518225183251842518525186251872518825189251902519125192251932519425195251962519725198251992520025201252022520325204252052520625207252082520925210252112521225213252142521525216252172521825219252202522125222252232522425225252262522725228252292523025231252322523325234252352523625237252382523925240252412524225243252442524525246252472524825249252502525125252252532525425255252562525725258252592526025261252622526325264252652526625267252682526925270252712527225273252742527525276252772527825279252802528125282252832528425285252862528725288252892529025291252922529325294252952529625297252982529925300253012530225303253042530525306253072530825309253102531125312253132531425315253162531725318253192532025321253222532325324253252532625327253282532925330253312533225333253342533525336253372533825339253402534125342253432534425345253462534725348253492535025351253522535325354253552535625357253582535925360253612536225363253642536525366253672536825369253702537125372253732537425375253762537725378253792538025381253822538325384253852538625387253882538925390253912539225393253942539525396253972539825399254002540125402254032540425405254062540725408254092541025411254122541325414254152541625417254182541925420254212542225423254242542525426254272542825429254302543125432254332543425435254362543725438254392544025441254422544325444254452544625447254482544925450254512545225453254542545525456254572545825459254602546125462254632546425465254662546725468254692547025471254722547325474254752547625477254782547925480254812548225483254842548525486254872548825489254902549125492254932549425495254962549725498254992550025501255022550325504255052550625507255082550925510255112551225513255142551525516255172551825519255202552125522255232552425525255262552725528255292553025531255322553325534255352553625537255382553925540255412554225543255442554525546255472554825549255502555125552255532555425555255562555725558255592556025561255622556325564255652556625567255682556925570255712557225573255742557525576255772557825579255802558125582255832558425585255862558725588255892559025591255922559325594255952559625597255982559925600256012560225603256042560525606256072560825609256102561125612256132561425615256162561725618256192562025621256222562325624256252562625627256282562925630256312563225633256342563525636256372563825639256402564125642256432564425645256462564725648256492565025651256522565325654256552565625657256582565925660256612566225663256642566525666256672566825669256702567125672256732567425675256762567725678256792568025681256822568325684256852568625687256882568925690256912569225693256942569525696256972569825699257002570125702257032570425705257062570725708257092571025711257122571325714257152571625717257182571925720257212572225723257242572525726257272572825729257302573125732257332573425735257362573725738257392574025741257422574325744257452574625747257482574925750257512575225753257542575525756257572575825759257602576125762257632576425765257662576725768257692577025771257722577325774257752577625777257782577925780257812578225783257842578525786257872578825789257902579125792257932579425795257962579725798257992580025801258022580325804258052580625807258082580925810258112581225813258142581525816258172581825819258202582125822258232582425825258262582725828258292583025831258322583325834258352583625837258382583925840258412584225843258442584525846258472584825849258502585125852258532585425855258562585725858258592586025861258622586325864258652586625867258682586925870258712587225873258742587525876258772587825879258802588125882258832588425885258862588725888258892589025891258922589325894258952589625897258982589925900259012590225903259042590525906259072590825909259102591125912259132591425915259162591725918259192592025921259222592325924259252592625927259282592925930259312593225933259342593525936259372593825939259402594125942259432594425945259462594725948259492595025951259522595325954259552595625957259582595925960259612596225963259642596525966259672596825969259702597125972259732597425975259762597725978259792598025981259822598325984259852598625987259882598925990259912599225993259942599525996259972599825999260002600126002260032600426005260062600726008260092601026011260122601326014260152601626017260182601926020260212602226023260242602526026260272602826029260302603126032260332603426035260362603726038260392604026041260422604326044260452604626047260482604926050260512605226053260542605526056260572605826059260602606126062260632606426065260662606726068260692607026071260722607326074260752607626077260782607926080260812608226083260842608526086260872608826089260902609126092260932609426095260962609726098260992610026101261022610326104261052610626107261082610926110261112611226113261142611526116261172611826119261202612126122261232612426125261262612726128261292613026131261322613326134261352613626137261382613926140261412614226143261442614526146261472614826149261502615126152261532615426155261562615726158261592616026161261622616326164261652616626167261682616926170261712617226173261742617526176261772617826179261802618126182261832618426185261862618726188261892619026191261922619326194261952619626197261982619926200262012620226203262042620526206262072620826209262102621126212262132621426215262162621726218262192622026221262222622326224262252622626227262282622926230262312623226233262342623526236262372623826239262402624126242262432624426245262462624726248262492625026251262522625326254262552625626257262582625926260262612626226263262642626526266262672626826269262702627126272262732627426275262762627726278262792628026281262822628326284262852628626287262882628926290262912629226293262942629526296262972629826299263002630126302263032630426305263062630726308263092631026311263122631326314263152631626317263182631926320263212632226323263242632526326263272632826329263302633126332263332633426335263362633726338263392634026341263422634326344263452634626347263482634926350263512635226353263542635526356263572635826359263602636126362263632636426365263662636726368263692637026371263722637326374263752637626377263782637926380263812638226383263842638526386263872638826389263902639126392263932639426395263962639726398263992640026401264022640326404264052640626407264082640926410264112641226413264142641526416264172641826419264202642126422264232642426425264262642726428264292643026431264322643326434264352643626437264382643926440264412644226443264442644526446264472644826449264502645126452264532645426455264562645726458264592646026461264622646326464264652646626467264682646926470264712647226473264742647526476264772647826479264802648126482264832648426485264862648726488264892649026491264922649326494264952649626497264982649926500265012650226503265042650526506265072650826509265102651126512265132651426515265162651726518265192652026521265222652326524265252652626527265282652926530265312653226533265342653526536265372653826539265402654126542265432654426545265462654726548265492655026551265522655326554265552655626557265582655926560265612656226563265642656526566265672656826569265702657126572265732657426575265762657726578265792658026581265822658326584265852658626587265882658926590265912659226593265942659526596265972659826599266002660126602266032660426605266062660726608266092661026611266122661326614266152661626617266182661926620266212662226623266242662526626266272662826629266302663126632266332663426635266362663726638266392664026641266422664326644266452664626647266482664926650266512665226653266542665526656266572665826659266602666126662266632666426665266662666726668266692667026671266722667326674266752667626677266782667926680266812668226683266842668526686266872668826689266902669126692266932669426695266962669726698266992670026701267022670326704267052670626707267082670926710267112671226713267142671526716267172671826719267202672126722267232672426725267262672726728267292673026731267322673326734267352673626737267382673926740267412674226743267442674526746267472674826749267502675126752267532675426755267562675726758267592676026761267622676326764267652676626767267682676926770267712677226773267742677526776267772677826779267802678126782267832678426785267862678726788267892679026791267922679326794267952679626797267982679926800268012680226803268042680526806268072680826809268102681126812268132681426815268162681726818268192682026821268222682326824268252682626827268282682926830268312683226833268342683526836268372683826839268402684126842268432684426845268462684726848268492685026851268522685326854268552685626857268582685926860268612686226863268642686526866268672686826869268702687126872268732687426875268762687726878268792688026881268822688326884268852688626887268882688926890268912689226893268942689526896268972689826899269002690126902269032690426905269062690726908269092691026911269122691326914269152691626917269182691926920269212692226923269242692526926269272692826929269302693126932269332693426935269362693726938269392694026941269422694326944269452694626947269482694926950269512695226953269542695526956269572695826959269602696126962269632696426965269662696726968269692697026971269722697326974269752697626977269782697926980269812698226983269842698526986269872698826989269902699126992269932699426995269962699726998269992700027001270022700327004270052700627007270082700927010270112701227013270142701527016270172701827019270202702127022270232702427025270262702727028270292703027031270322703327034270352703627037270382703927040270412704227043270442704527046270472704827049270502705127052270532705427055270562705727058270592706027061270622706327064270652706627067270682706927070270712707227073270742707527076270772707827079270802708127082270832708427085270862708727088270892709027091270922709327094270952709627097270982709927100271012710227103271042710527106271072710827109271102711127112271132711427115271162711727118271192712027121271222712327124271252712627127271282712927130271312713227133271342713527136271372713827139271402714127142271432714427145271462714727148271492715027151271522715327154271552715627157271582715927160271612716227163271642716527166271672716827169271702717127172271732717427175271762717727178271792718027181271822718327184271852718627187271882718927190271912719227193271942719527196271972719827199272002720127202272032720427205272062720727208272092721027211272122721327214272152721627217272182721927220272212722227223272242722527226272272722827229272302723127232272332723427235272362723727238272392724027241272422724327244272452724627247272482724927250272512725227253272542725527256272572725827259272602726127262272632726427265272662726727268272692727027271272722727327274272752727627277272782727927280272812728227283272842728527286272872728827289272902729127292272932729427295272962729727298272992730027301273022730327304273052730627307273082730927310273112731227313273142731527316273172731827319273202732127322273232732427325273262732727328273292733027331273322733327334273352733627337273382733927340273412734227343273442734527346273472734827349273502735127352273532735427355273562735727358273592736027361273622736327364273652736627367273682736927370273712737227373273742737527376273772737827379273802738127382273832738427385273862738727388273892739027391273922739327394273952739627397273982739927400274012740227403274042740527406274072740827409274102741127412274132741427415274162741727418274192742027421274222742327424274252742627427274282742927430274312743227433274342743527436274372743827439274402744127442274432744427445274462744727448274492745027451274522745327454274552745627457274582745927460274612746227463274642746527466274672746827469274702747127472274732747427475274762747727478274792748027481274822748327484274852748627487274882748927490274912749227493274942749527496274972749827499275002750127502275032750427505275062750727508275092751027511275122751327514275152751627517275182751927520275212752227523275242752527526275272752827529275302753127532275332753427535275362753727538275392754027541275422754327544275452754627547275482754927550275512755227553275542755527556275572755827559275602756127562275632756427565275662756727568275692757027571275722757327574275752757627577275782757927580275812758227583275842758527586275872758827589275902759127592275932759427595275962759727598275992760027601276022760327604276052760627607276082760927610276112761227613276142761527616276172761827619276202762127622276232762427625276262762727628276292763027631276322763327634276352763627637276382763927640276412764227643276442764527646276472764827649276502765127652276532765427655276562765727658276592766027661276622766327664276652766627667276682766927670276712767227673276742767527676276772767827679276802768127682276832768427685276862768727688276892769027691276922769327694276952769627697276982769927700277012770227703277042770527706277072770827709277102771127712277132771427715277162771727718277192772027721277222772327724277252772627727277282772927730277312773227733277342773527736277372773827739277402774127742277432774427745277462774727748277492775027751277522775327754277552775627757277582775927760277612776227763277642776527766277672776827769277702777127772277732777427775277762777727778277792778027781277822778327784277852778627787277882778927790277912779227793277942779527796277972779827799278002780127802278032780427805278062780727808278092781027811278122781327814278152781627817278182781927820278212782227823278242782527826278272782827829278302783127832278332783427835278362783727838278392784027841278422784327844278452784627847278482784927850278512785227853278542785527856278572785827859278602786127862278632786427865278662786727868278692787027871278722787327874278752787627877278782787927880278812788227883278842788527886278872788827889278902789127892278932789427895278962789727898278992790027901279022790327904279052790627907279082790927910279112791227913279142791527916279172791827919279202792127922279232792427925279262792727928279292793027931279322793327934279352793627937279382793927940279412794227943279442794527946279472794827949279502795127952279532795427955279562795727958279592796027961279622796327964279652796627967279682796927970279712797227973279742797527976279772797827979279802798127982279832798427985279862798727988279892799027991279922799327994279952799627997279982799928000280012800228003280042800528006280072800828009280102801128012280132801428015280162801728018280192802028021280222802328024280252802628027280282802928030280312803228033280342803528036280372803828039280402804128042280432804428045280462804728048280492805028051280522805328054280552805628057280582805928060280612806228063280642806528066280672806828069280702807128072280732807428075280762807728078280792808028081280822808328084280852808628087280882808928090280912809228093280942809528096280972809828099281002810128102281032810428105281062810728108281092811028111281122811328114281152811628117281182811928120281212812228123281242812528126281272812828129281302813128132281332813428135281362813728138281392814028141281422814328144281452814628147281482814928150281512815228153281542815528156281572815828159281602816128162281632816428165281662816728168281692817028171281722817328174281752817628177281782817928180281812818228183281842818528186281872818828189281902819128192281932819428195281962819728198281992820028201282022820328204282052820628207282082820928210282112821228213282142821528216282172821828219282202822128222282232822428225282262822728228282292823028231282322823328234282352823628237282382823928240282412824228243282442824528246282472824828249282502825128252282532825428255282562825728258282592826028261282622826328264282652826628267282682826928270282712827228273282742827528276282772827828279282802828128282282832828428285282862828728288282892829028291282922829328294282952829628297282982829928300283012830228303283042830528306283072830828309283102831128312283132831428315283162831728318283192832028321283222832328324283252832628327283282832928330283312833228333283342833528336283372833828339283402834128342283432834428345283462834728348283492835028351283522835328354283552835628357283582835928360283612836228363283642836528366283672836828369283702837128372283732837428375283762837728378283792838028381283822838328384283852838628387283882838928390283912839228393283942839528396283972839828399284002840128402284032840428405284062840728408284092841028411284122841328414284152841628417284182841928420284212842228423284242842528426284272842828429284302843128432284332843428435284362843728438284392844028441284422844328444284452844628447284482844928450284512845228453284542845528456284572845828459284602846128462284632846428465284662846728468284692847028471284722847328474284752847628477284782847928480284812848228483284842848528486284872848828489284902849128492284932849428495284962849728498284992850028501285022850328504285052850628507285082850928510285112851228513285142851528516285172851828519285202852128522285232852428525285262852728528285292853028531285322853328534285352853628537285382853928540285412854228543285442854528546285472854828549285502855128552285532855428555285562855728558285592856028561285622856328564285652856628567285682856928570285712857228573285742857528576285772857828579285802858128582285832858428585285862858728588285892859028591285922859328594285952859628597285982859928600286012860228603286042860528606286072860828609286102861128612286132861428615286162861728618286192862028621286222862328624286252862628627286282862928630286312863228633286342863528636286372863828639286402864128642286432864428645286462864728648286492865028651286522865328654286552865628657286582865928660286612866228663286642866528666286672866828669286702867128672286732867428675286762867728678286792868028681286822868328684286852868628687286882868928690286912869228693286942869528696286972869828699287002870128702287032870428705287062870728708287092871028711287122871328714287152871628717287182871928720287212872228723287242872528726287272872828729287302873128732287332873428735287362873728738287392874028741287422874328744287452874628747287482874928750287512875228753287542875528756287572875828759287602876128762287632876428765287662876728768287692877028771287722877328774287752877628777287782877928780287812878228783287842878528786287872878828789287902879128792287932879428795287962879728798287992880028801288022880328804288052880628807288082880928810288112881228813288142881528816288172881828819288202882128822288232882428825288262882728828288292883028831288322883328834288352883628837288382883928840288412884228843288442884528846288472884828849288502885128852288532885428855288562885728858288592886028861288622886328864288652886628867288682886928870288712887228873288742887528876288772887828879288802888128882288832888428885288862888728888288892889028891288922889328894288952889628897288982889928900289012890228903289042890528906289072890828909289102891128912289132891428915289162891728918289192892028921289222892328924289252892628927289282892928930289312893228933289342893528936289372893828939289402894128942289432894428945289462894728948289492895028951289522895328954289552895628957289582895928960289612896228963289642896528966289672896828969289702897128972289732897428975289762897728978289792898028981289822898328984289852898628987289882898928990289912899228993289942899528996289972899828999290002900129002290032900429005290062900729008290092901029011290122901329014290152901629017290182901929020290212902229023290242902529026290272902829029290302903129032290332903429035290362903729038290392904029041290422904329044290452904629047290482904929050290512905229053290542905529056290572905829059290602906129062290632906429065290662906729068290692907029071290722907329074290752907629077290782907929080290812908229083290842908529086290872908829089290902909129092290932909429095290962909729098290992910029101291022910329104291052910629107291082910929110291112911229113291142911529116291172911829119291202912129122291232912429125291262912729128291292913029131291322913329134291352913629137291382913929140291412914229143291442914529146291472914829149291502915129152291532915429155291562915729158291592916029161291622916329164291652916629167291682916929170291712917229173291742917529176291772917829179291802918129182291832918429185291862918729188291892919029191291922919329194291952919629197291982919929200292012920229203292042920529206292072920829209292102921129212292132921429215292162921729218292192922029221292222922329224292252922629227292282922929230292312923229233292342923529236292372923829239292402924129242292432924429245292462924729248292492925029251292522925329254292552925629257292582925929260292612926229263292642926529266292672926829269292702927129272292732927429275292762927729278292792928029281292822928329284292852928629287292882928929290292912929229293292942929529296292972929829299293002930129302293032930429305293062930729308293092931029311293122931329314293152931629317293182931929320293212932229323293242932529326293272932829329293302933129332293332933429335293362933729338293392934029341293422934329344293452934629347293482934929350293512935229353293542935529356293572935829359293602936129362293632936429365293662936729368293692937029371293722937329374293752937629377293782937929380293812938229383293842938529386293872938829389293902939129392293932939429395293962939729398293992940029401294022940329404294052940629407294082940929410294112941229413294142941529416294172941829419294202942129422294232942429425294262942729428294292943029431294322943329434294352943629437294382943929440294412944229443294442944529446294472944829449294502945129452294532945429455294562945729458294592946029461294622946329464294652946629467294682946929470294712947229473294742947529476294772947829479294802948129482294832948429485294862948729488294892949029491294922949329494294952949629497294982949929500295012950229503295042950529506295072950829509295102951129512295132951429515295162951729518295192952029521295222952329524295252952629527295282952929530295312953229533295342953529536295372953829539295402954129542295432954429545295462954729548295492955029551295522955329554295552955629557295582955929560295612956229563295642956529566295672956829569295702957129572295732957429575295762957729578295792958029581295822958329584295852958629587295882958929590295912959229593295942959529596295972959829599296002960129602296032960429605296062960729608296092961029611296122961329614296152961629617296182961929620296212962229623296242962529626296272962829629296302963129632296332963429635296362963729638296392964029641296422964329644296452964629647296482964929650296512965229653296542965529656296572965829659296602966129662296632966429665296662966729668296692967029671296722967329674296752967629677296782967929680296812968229683296842968529686296872968829689296902969129692296932969429695296962969729698296992970029701297022970329704297052970629707297082970929710297112971229713297142971529716297172971829719297202972129722297232972429725297262972729728297292973029731297322973329734297352973629737297382973929740297412974229743297442974529746297472974829749297502975129752297532975429755297562975729758297592976029761297622976329764297652976629767297682976929770297712977229773297742977529776297772977829779297802978129782297832978429785297862978729788297892979029791297922979329794297952979629797297982979929800298012980229803298042980529806298072980829809298102981129812298132981429815298162981729818298192982029821298222982329824298252982629827298282982929830298312983229833298342983529836298372983829839298402984129842298432984429845298462984729848298492985029851298522985329854298552985629857298582985929860298612986229863298642986529866298672986829869298702987129872298732987429875298762987729878298792988029881298822988329884298852988629887298882988929890298912989229893298942989529896298972989829899299002990129902299032990429905299062990729908299092991029911299122991329914299152991629917299182991929920299212992229923299242992529926299272992829929299302993129932299332993429935299362993729938299392994029941299422994329944299452994629947299482994929950299512995229953299542995529956299572995829959299602996129962299632996429965299662996729968299692997029971299722997329974299752997629977299782997929980299812998229983299842998529986299872998829989299902999129992299932999429995299962999729998299993000030001300023000330004300053000630007300083000930010300113001230013300143001530016300173001830019300203002130022300233002430025300263002730028300293003030031300323003330034300353003630037300383003930040300413004230043300443004530046300473004830049300503005130052300533005430055300563005730058300593006030061300623006330064300653006630067300683006930070300713007230073300743007530076300773007830079300803008130082300833008430085300863008730088300893009030091300923009330094300953009630097300983009930100301013010230103301043010530106301073010830109301103011130112301133011430115301163011730118301193012030121301223012330124301253012630127301283012930130301313013230133301343013530136301373013830139301403014130142301433014430145301463014730148301493015030151301523015330154301553015630157301583015930160301613016230163301643016530166301673016830169301703017130172301733017430175301763017730178301793018030181301823018330184301853018630187301883018930190301913019230193301943019530196301973019830199302003020130202302033020430205302063020730208302093021030211302123021330214302153021630217302183021930220302213022230223302243022530226302273022830229302303023130232302333023430235302363023730238302393024030241302423024330244302453024630247302483024930250302513025230253302543025530256302573025830259302603026130262302633026430265302663026730268302693027030271302723027330274302753027630277302783027930280302813028230283302843028530286302873028830289302903029130292302933029430295302963029730298302993030030301303023030330304303053030630307303083030930310303113031230313303143031530316303173031830319303203032130322303233032430325303263032730328303293033030331303323033330334303353033630337303383033930340303413034230343303443034530346303473034830349303503035130352303533035430355303563035730358303593036030361303623036330364303653036630367303683036930370303713037230373303743037530376303773037830379303803038130382303833038430385303863038730388303893039030391303923039330394303953039630397303983039930400304013040230403304043040530406304073040830409304103041130412304133041430415304163041730418304193042030421304223042330424304253042630427304283042930430304313043230433304343043530436304373043830439304403044130442304433044430445304463044730448304493045030451304523045330454304553045630457304583045930460304613046230463304643046530466304673046830469304703047130472304733047430475304763047730478304793048030481304823048330484304853048630487304883048930490304913049230493304943049530496304973049830499305003050130502305033050430505305063050730508305093051030511305123051330514305153051630517305183051930520305213052230523305243052530526305273052830529305303053130532305333053430535305363053730538305393054030541305423054330544305453054630547305483054930550305513055230553305543055530556305573055830559305603056130562305633056430565305663056730568305693057030571305723057330574305753057630577305783057930580305813058230583305843058530586305873058830589305903059130592305933059430595305963059730598305993060030601306023060330604306053060630607306083060930610306113061230613306143061530616306173061830619306203062130622306233062430625306263062730628306293063030631306323063330634306353063630637306383063930640306413064230643306443064530646306473064830649306503065130652306533065430655306563065730658306593066030661306623066330664306653066630667306683066930670306713067230673306743067530676306773067830679306803068130682306833068430685306863068730688306893069030691306923069330694306953069630697306983069930700307013070230703307043070530706307073070830709307103071130712307133071430715307163071730718307193072030721307223072330724307253072630727307283072930730307313073230733307343073530736307373073830739307403074130742307433074430745307463074730748307493075030751307523075330754307553075630757307583075930760307613076230763307643076530766307673076830769307703077130772307733077430775307763077730778307793078030781307823078330784307853078630787307883078930790307913079230793307943079530796307973079830799308003080130802308033080430805308063080730808308093081030811308123081330814308153081630817308183081930820308213082230823308243082530826308273082830829308303083130832308333083430835308363083730838308393084030841308423084330844308453084630847308483084930850308513085230853308543085530856308573085830859308603086130862308633086430865308663086730868308693087030871308723087330874308753087630877308783087930880308813088230883308843088530886308873088830889308903089130892308933089430895308963089730898308993090030901309023090330904309053090630907309083090930910309113091230913309143091530916309173091830919309203092130922309233092430925309263092730928309293093030931309323093330934309353093630937309383093930940309413094230943309443094530946309473094830949309503095130952309533095430955309563095730958309593096030961309623096330964309653096630967309683096930970309713097230973309743097530976309773097830979309803098130982309833098430985309863098730988309893099030991309923099330994309953099630997309983099931000310013100231003310043100531006310073100831009310103101131012310133101431015310163101731018310193102031021310223102331024310253102631027310283102931030310313103231033310343103531036310373103831039310403104131042310433104431045310463104731048310493105031051310523105331054310553105631057310583105931060310613106231063310643106531066310673106831069310703107131072310733107431075310763107731078310793108031081310823108331084310853108631087310883108931090310913109231093310943109531096310973109831099311003110131102311033110431105311063110731108311093111031111311123111331114311153111631117311183111931120311213112231123311243112531126311273112831129311303113131132311333113431135311363113731138311393114031141311423114331144311453114631147311483114931150311513115231153311543115531156311573115831159311603116131162311633116431165311663116731168311693117031171311723117331174311753117631177311783117931180311813118231183311843118531186311873118831189311903119131192311933119431195311963119731198311993120031201312023120331204312053120631207312083120931210312113121231213312143121531216312173121831219312203122131222312233122431225312263122731228312293123031231312323123331234312353123631237312383123931240312413124231243312443124531246312473124831249312503125131252312533125431255312563125731258312593126031261312623126331264312653126631267312683126931270312713127231273312743127531276312773127831279312803128131282312833128431285312863128731288312893129031291312923129331294312953129631297312983129931300313013130231303313043130531306313073130831309313103131131312313133131431315313163131731318313193132031321313223132331324313253132631327313283132931330313313133231333313343133531336313373133831339313403134131342313433134431345313463134731348313493135031351313523135331354313553135631357313583135931360313613136231363313643136531366313673136831369313703137131372313733137431375313763137731378313793138031381313823138331384313853138631387313883138931390313913139231393313943139531396313973139831399314003140131402314033140431405314063140731408314093141031411314123141331414314153141631417314183141931420314213142231423314243142531426314273142831429314303143131432314333143431435314363143731438314393144031441314423144331444314453144631447314483144931450314513145231453314543145531456314573145831459314603146131462314633146431465314663146731468314693147031471314723147331474314753147631477314783147931480314813148231483314843148531486314873148831489314903149131492314933149431495314963149731498314993150031501315023150331504315053150631507315083150931510315113151231513315143151531516315173151831519315203152131522315233152431525315263152731528315293153031531315323153331534315353153631537315383153931540315413154231543315443154531546315473154831549315503155131552315533155431555315563155731558315593156031561315623156331564315653156631567315683156931570315713157231573315743157531576315773157831579315803158131582315833158431585315863158731588315893159031591315923159331594315953159631597315983159931600316013160231603316043160531606316073160831609316103161131612316133161431615316163161731618316193162031621316223162331624316253162631627316283162931630316313163231633316343163531636316373163831639316403164131642316433164431645316463164731648316493165031651316523165331654316553165631657316583165931660316613166231663316643166531666316673166831669316703167131672316733167431675316763167731678316793168031681316823168331684316853168631687316883168931690316913169231693316943169531696316973169831699317003170131702317033170431705317063170731708317093171031711317123171331714317153171631717317183171931720317213172231723317243172531726317273172831729317303173131732317333173431735317363173731738317393174031741317423174331744317453174631747317483174931750317513175231753317543175531756317573175831759317603176131762317633176431765317663176731768317693177031771317723177331774317753177631777317783177931780317813178231783317843178531786317873178831789317903179131792317933179431795317963179731798317993180031801318023180331804318053180631807318083180931810318113181231813318143181531816318173181831819318203182131822318233182431825318263182731828318293183031831318323183331834318353183631837318383183931840318413184231843318443184531846318473184831849318503185131852318533185431855318563185731858318593186031861318623186331864318653186631867318683186931870318713187231873318743187531876318773187831879318803188131882318833188431885318863188731888318893189031891318923189331894318953189631897318983189931900319013190231903319043190531906319073190831909319103191131912319133191431915319163191731918319193192031921319223192331924319253192631927319283192931930319313193231933319343193531936319373193831939319403194131942319433194431945319463194731948319493195031951319523195331954319553195631957319583195931960319613196231963319643196531966319673196831969319703197131972319733197431975319763197731978319793198031981319823198331984319853198631987319883198931990319913199231993319943199531996319973199831999320003200132002320033200432005320063200732008320093201032011320123201332014320153201632017320183201932020320213202232023320243202532026320273202832029320303203132032320333203432035320363203732038320393204032041320423204332044320453204632047320483204932050320513205232053320543205532056320573205832059320603206132062320633206432065320663206732068320693207032071320723207332074320753207632077320783207932080320813208232083320843208532086320873208832089320903209132092320933209432095320963209732098320993210032101321023210332104321053210632107321083210932110321113211232113321143211532116321173211832119321203212132122321233212432125321263212732128321293213032131321323213332134321353213632137321383213932140321413214232143321443214532146321473214832149321503215132152321533215432155321563215732158321593216032161321623216332164321653216632167321683216932170321713217232173321743217532176321773217832179321803218132182321833218432185321863218732188321893219032191321923219332194321953219632197321983219932200322013220232203322043220532206322073220832209322103221132212322133221432215322163221732218322193222032221322223222332224322253222632227322283222932230322313223232233322343223532236322373223832239322403224132242322433224432245322463224732248322493225032251322523225332254322553225632257322583225932260322613226232263322643226532266322673226832269322703227132272322733227432275322763227732278322793228032281322823228332284322853228632287322883228932290322913229232293322943229532296322973229832299323003230132302323033230432305323063230732308323093231032311323123231332314323153231632317323183231932320323213232232323323243232532326323273232832329323303233132332323333233432335323363233732338323393234032341323423234332344323453234632347323483234932350323513235232353323543235532356323573235832359323603236132362323633236432365323663236732368323693237032371323723237332374323753237632377323783237932380323813238232383323843238532386323873238832389323903239132392323933239432395323963239732398323993240032401324023240332404324053240632407324083240932410324113241232413324143241532416324173241832419324203242132422324233242432425324263242732428324293243032431324323243332434324353243632437324383243932440324413244232443324443244532446324473244832449324503245132452324533245432455324563245732458324593246032461324623246332464324653246632467324683246932470324713247232473324743247532476324773247832479324803248132482324833248432485324863248732488324893249032491324923249332494324953249632497324983249932500325013250232503325043250532506325073250832509325103251132512325133251432515325163251732518325193252032521325223252332524325253252632527325283252932530325313253232533325343253532536325373253832539325403254132542325433254432545325463254732548325493255032551325523255332554325553255632557325583255932560325613256232563325643256532566325673256832569325703257132572325733257432575325763257732578325793258032581325823258332584325853258632587325883258932590325913259232593325943259532596325973259832599326003260132602326033260432605326063260732608326093261032611326123261332614326153261632617326183261932620326213262232623326243262532626326273262832629326303263132632326333263432635326363263732638326393264032641326423264332644326453264632647326483264932650326513265232653326543265532656326573265832659326603266132662326633266432665326663266732668326693267032671326723267332674326753267632677326783267932680326813268232683326843268532686326873268832689326903269132692326933269432695326963269732698326993270032701327023270332704327053270632707327083270932710327113271232713327143271532716327173271832719327203272132722327233272432725327263272732728327293273032731327323273332734327353273632737327383273932740327413274232743327443274532746327473274832749327503275132752327533275432755327563275732758327593276032761327623276332764327653276632767327683276932770327713277232773327743277532776327773277832779327803278132782327833278432785327863278732788327893279032791327923279332794327953279632797327983279932800328013280232803328043280532806328073280832809328103281132812328133281432815328163281732818328193282032821328223282332824328253282632827328283282932830328313283232833328343283532836328373283832839328403284132842328433284432845328463284732848328493285032851328523285332854328553285632857328583285932860328613286232863328643286532866328673286832869328703287132872328733287432875328763287732878328793288032881328823288332884328853288632887328883288932890328913289232893328943289532896328973289832899329003290132902329033290432905329063290732908329093291032911329123291332914329153291632917329183291932920329213292232923329243292532926329273292832929329303293132932329333293432935329363293732938329393294032941329423294332944329453294632947329483294932950329513295232953329543295532956329573295832959329603296132962329633296432965329663296732968329693297032971329723297332974329753297632977329783297932980329813298232983329843298532986329873298832989329903299132992329933299432995329963299732998329993300033001330023300333004330053300633007330083300933010330113301233013330143301533016330173301833019330203302133022330233302433025330263302733028330293303033031330323303333034330353303633037330383303933040330413304233043330443304533046330473304833049330503305133052330533305433055330563305733058330593306033061330623306333064330653306633067330683306933070330713307233073330743307533076330773307833079330803308133082330833308433085330863308733088330893309033091330923309333094330953309633097330983309933100331013310233103331043310533106331073310833109331103311133112331133311433115331163311733118331193312033121331223312333124331253312633127331283312933130331313313233133331343313533136331373313833139331403314133142331433314433145331463314733148331493315033151331523315333154331553315633157331583315933160331613316233163331643316533166331673316833169331703317133172331733317433175331763317733178331793318033181331823318333184331853318633187331883318933190331913319233193331943319533196331973319833199332003320133202332033320433205332063320733208332093321033211332123321333214332153321633217332183321933220332213322233223332243322533226332273322833229332303323133232332333323433235332363323733238332393324033241332423324333244332453324633247332483324933250332513325233253332543325533256332573325833259332603326133262332633326433265332663326733268332693327033271332723327333274332753327633277332783327933280332813328233283332843328533286332873328833289332903329133292332933329433295332963329733298332993330033301333023330333304333053330633307333083330933310333113331233313333143331533316333173331833319333203332133322333233332433325333263332733328333293333033331333323333333334333353333633337333383333933340333413334233343333443334533346333473334833349333503335133352333533335433355333563335733358333593336033361333623336333364333653336633367333683336933370333713337233373333743337533376333773337833379333803338133382333833338433385333863338733388333893339033391333923339333394333953339633397333983339933400334013340233403334043340533406334073340833409334103341133412334133341433415334163341733418334193342033421334223342333424334253342633427334283342933430334313343233433334343343533436334373343833439334403344133442334433344433445334463344733448334493345033451334523345333454334553345633457334583345933460334613346233463334643346533466334673346833469334703347133472334733347433475334763347733478334793348033481334823348333484334853348633487334883348933490334913349233493334943349533496334973349833499335003350133502335033350433505335063350733508335093351033511335123351333514335153351633517335183351933520335213352233523335243352533526335273352833529335303353133532335333353433535335363353733538335393354033541335423354333544335453354633547335483354933550335513355233553335543355533556335573355833559335603356133562335633356433565335663356733568335693357033571335723357333574335753357633577335783357933580335813358233583335843358533586335873358833589335903359133592335933359433595335963359733598335993360033601336023360333604336053360633607336083360933610336113361233613336143361533616336173361833619336203362133622336233362433625336263362733628336293363033631336323363333634336353363633637336383363933640336413364233643336443364533646336473364833649336503365133652336533365433655336563365733658336593366033661336623366333664336653366633667336683366933670336713367233673336743367533676336773367833679336803368133682336833368433685336863368733688336893369033691336923369333694336953369633697336983369933700337013370233703337043370533706337073370833709337103371133712337133371433715337163371733718337193372033721337223372333724337253372633727337283372933730337313373233733337343373533736337373373833739337403374133742337433374433745337463374733748337493375033751337523375333754337553375633757337583375933760337613376233763337643376533766337673376833769337703377133772337733377433775337763377733778337793378033781337823378333784337853378633787337883378933790337913379233793337943379533796337973379833799338003380133802338033380433805338063380733808338093381033811338123381333814338153381633817338183381933820338213382233823338243382533826338273382833829338303383133832338333383433835338363383733838338393384033841338423384333844338453384633847338483384933850338513385233853338543385533856338573385833859338603386133862338633386433865338663386733868338693387033871338723387333874338753387633877338783387933880338813388233883338843388533886338873388833889338903389133892338933389433895338963389733898338993390033901339023390333904339053390633907339083390933910339113391233913339143391533916339173391833919339203392133922339233392433925339263392733928339293393033931339323393333934339353393633937339383393933940339413394233943339443394533946339473394833949339503395133952339533395433955339563395733958339593396033961339623396333964339653396633967339683396933970339713397233973339743397533976339773397833979339803398133982339833398433985339863398733988339893399033991339923399333994339953399633997339983399934000340013400234003340043400534006340073400834009340103401134012340133401434015340163401734018340193402034021340223402334024340253402634027340283402934030340313403234033340343403534036340373403834039340403404134042340433404434045340463404734048340493405034051340523405334054340553405634057340583405934060340613406234063340643406534066340673406834069340703407134072340733407434075340763407734078340793408034081340823408334084340853408634087340883408934090340913409234093340943409534096340973409834099341003410134102341033410434105341063410734108341093411034111341123411334114341153411634117341183411934120341213412234123341243412534126341273412834129341303413134132341333413434135341363413734138341393414034141341423414334144341453414634147341483414934150341513415234153341543415534156341573415834159341603416134162341633416434165341663416734168341693417034171341723417334174341753417634177341783417934180341813418234183341843418534186341873418834189341903419134192341933419434195341963419734198341993420034201342023420334204342053420634207342083420934210342113421234213342143421534216342173421834219342203422134222342233422434225342263422734228342293423034231342323423334234342353423634237342383423934240342413424234243342443424534246342473424834249342503425134252342533425434255342563425734258342593426034261342623426334264342653426634267342683426934270342713427234273342743427534276342773427834279342803428134282342833428434285342863428734288342893429034291342923429334294342953429634297342983429934300343013430234303343043430534306343073430834309343103431134312343133431434315343163431734318343193432034321343223432334324343253432634327343283432934330343313433234333343343433534336343373433834339343403434134342343433434434345343463434734348343493435034351343523435334354343553435634357343583435934360343613436234363343643436534366343673436834369343703437134372343733437434375343763437734378343793438034381343823438334384343853438634387343883438934390343913439234393343943439534396343973439834399344003440134402344033440434405344063440734408344093441034411344123441334414344153441634417344183441934420344213442234423344243442534426344273442834429344303443134432344333443434435344363443734438344393444034441344423444334444344453444634447344483444934450344513445234453344543445534456344573445834459344603446134462344633446434465344663446734468344693447034471344723447334474344753447634477344783447934480344813448234483344843448534486344873448834489344903449134492344933449434495344963449734498344993450034501345023450334504345053450634507345083450934510345113451234513345143451534516345173451834519345203452134522345233452434525345263452734528345293453034531345323453334534345353453634537345383453934540345413454234543345443454534546345473454834549345503455134552345533455434555345563455734558345593456034561345623456334564345653456634567345683456934570345713457234573345743457534576345773457834579345803458134582345833458434585345863458734588345893459034591345923459334594345953459634597345983459934600346013460234603346043460534606346073460834609346103461134612346133461434615346163461734618346193462034621346223462334624346253462634627346283462934630346313463234633346343463534636346373463834639346403464134642346433464434645346463464734648346493465034651346523465334654346553465634657346583465934660346613466234663346643466534666346673466834669346703467134672346733467434675346763467734678346793468034681346823468334684346853468634687346883468934690346913469234693346943469534696346973469834699347003470134702347033470434705347063470734708347093471034711347123471334714347153471634717347183471934720347213472234723347243472534726347273472834729347303473134732347333473434735347363473734738347393474034741347423474334744347453474634747347483474934750347513475234753347543475534756347573475834759347603476134762347633476434765347663476734768347693477034771347723477334774347753477634777347783477934780347813478234783347843478534786347873478834789347903479134792347933479434795347963479734798347993480034801348023480334804348053480634807348083480934810348113481234813348143481534816348173481834819348203482134822348233482434825348263482734828348293483034831348323483334834348353483634837348383483934840348413484234843348443484534846348473484834849348503485134852348533485434855348563485734858348593486034861348623486334864348653486634867348683486934870348713487234873348743487534876348773487834879348803488134882348833488434885348863488734888348893489034891348923489334894348953489634897348983489934900349013490234903349043490534906349073490834909349103491134912349133491434915349163491734918349193492034921349223492334924349253492634927349283492934930349313493234933349343493534936349373493834939349403494134942349433494434945349463494734948349493495034951349523495334954349553495634957349583495934960349613496234963349643496534966349673496834969349703497134972349733497434975349763497734978349793498034981349823498334984349853498634987349883498934990349913499234993349943499534996349973499834999350003500135002350033500435005350063500735008350093501035011350123501335014350153501635017350183501935020350213502235023350243502535026350273502835029350303503135032350333503435035350363503735038350393504035041350423504335044350453504635047350483504935050350513505235053350543505535056350573505835059350603506135062350633506435065350663506735068350693507035071350723507335074350753507635077350783507935080350813508235083350843508535086350873508835089350903509135092350933509435095350963509735098350993510035101351023510335104351053510635107351083510935110351113511235113351143511535116351173511835119351203512135122351233512435125351263512735128351293513035131351323513335134351353513635137351383513935140351413514235143351443514535146351473514835149351503515135152351533515435155351563515735158351593516035161351623516335164351653516635167351683516935170351713517235173351743517535176351773517835179351803518135182351833518435185351863518735188351893519035191351923519335194351953519635197351983519935200352013520235203352043520535206352073520835209352103521135212352133521435215352163521735218352193522035221352223522335224352253522635227352283522935230352313523235233352343523535236352373523835239352403524135242352433524435245352463524735248352493525035251352523525335254352553525635257352583525935260352613526235263352643526535266352673526835269352703527135272352733527435275352763527735278352793528035281352823528335284352853528635287352883528935290352913529235293352943529535296352973529835299353003530135302353033530435305353063530735308353093531035311353123531335314353153531635317353183531935320353213532235323353243532535326353273532835329353303533135332353333533435335353363533735338353393534035341353423534335344353453534635347353483534935350353513535235353353543535535356353573535835359353603536135362353633536435365353663536735368353693537035371353723537335374353753537635377353783537935380353813538235383353843538535386353873538835389353903539135392353933539435395353963539735398353993540035401354023540335404354053540635407354083540935410354113541235413354143541535416354173541835419354203542135422354233542435425354263542735428354293543035431354323543335434354353543635437354383543935440354413544235443354443544535446354473544835449354503545135452354533545435455354563545735458354593546035461354623546335464354653546635467354683546935470354713547235473354743547535476354773547835479354803548135482354833548435485354863548735488354893549035491354923549335494354953549635497354983549935500355013550235503355043550535506355073550835509355103551135512355133551435515355163551735518355193552035521355223552335524355253552635527355283552935530355313553235533355343553535536355373553835539355403554135542355433554435545355463554735548355493555035551355523555335554355553555635557355583555935560355613556235563355643556535566355673556835569355703557135572355733557435575355763557735578355793558035581355823558335584355853558635587355883558935590355913559235593355943559535596355973559835599356003560135602356033560435605356063560735608356093561035611356123561335614356153561635617356183561935620356213562235623356243562535626356273562835629356303563135632356333563435635356363563735638356393564035641356423564335644356453564635647356483564935650356513565235653356543565535656356573565835659356603566135662356633566435665356663566735668356693567035671356723567335674356753567635677356783567935680356813568235683356843568535686356873568835689356903569135692356933569435695356963569735698356993570035701357023570335704357053570635707357083570935710357113571235713357143571535716357173571835719357203572135722357233572435725357263572735728357293573035731357323573335734357353573635737357383573935740357413574235743357443574535746357473574835749357503575135752357533575435755357563575735758357593576035761357623576335764357653576635767357683576935770357713577235773357743577535776357773577835779357803578135782357833578435785357863578735788357893579035791357923579335794357953579635797357983579935800358013580235803358043580535806358073580835809358103581135812358133581435815358163581735818358193582035821358223582335824358253582635827358283582935830358313583235833358343583535836358373583835839358403584135842358433584435845358463584735848358493585035851358523585335854358553585635857358583585935860358613586235863358643586535866358673586835869358703587135872358733587435875358763587735878358793588035881358823588335884358853588635887358883588935890358913589235893358943589535896358973589835899359003590135902359033590435905359063590735908359093591035911359123591335914359153591635917359183591935920359213592235923359243592535926359273592835929359303593135932359333593435935359363593735938359393594035941359423594335944359453594635947359483594935950359513595235953359543595535956359573595835959359603596135962359633596435965359663596735968359693597035971359723597335974359753597635977359783597935980359813598235983359843598535986359873598835989359903599135992359933599435995359963599735998359993600036001360023600336004360053600636007360083600936010360113601236013360143601536016360173601836019360203602136022360233602436025360263602736028360293603036031360323603336034360353603636037360383603936040360413604236043360443604536046360473604836049360503605136052360533605436055360563605736058360593606036061360623606336064360653606636067360683606936070360713607236073360743607536076360773607836079360803608136082360833608436085360863608736088360893609036091360923609336094360953609636097360983609936100361013610236103361043610536106361073610836109361103611136112361133611436115361163611736118361193612036121361223612336124361253612636127361283612936130361313613236133361343613536136361373613836139361403614136142361433614436145361463614736148361493615036151361523615336154361553615636157361583615936160361613616236163361643616536166361673616836169361703617136172361733617436175361763617736178361793618036181361823618336184361853618636187361883618936190361913619236193361943619536196361973619836199362003620136202362033620436205362063620736208362093621036211362123621336214362153621636217362183621936220362213622236223362243622536226362273622836229362303623136232362333623436235362363623736238362393624036241362423624336244362453624636247362483624936250362513625236253362543625536256362573625836259362603626136262362633626436265362663626736268362693627036271362723627336274362753627636277362783627936280362813628236283362843628536286362873628836289362903629136292362933629436295362963629736298362993630036301363023630336304363053630636307363083630936310363113631236313363143631536316363173631836319363203632136322363233632436325363263632736328363293633036331363323633336334363353633636337363383633936340363413634236343363443634536346363473634836349363503635136352363533635436355363563635736358363593636036361363623636336364363653636636367363683636936370363713637236373363743637536376363773637836379363803638136382363833638436385363863638736388363893639036391363923639336394363953639636397363983639936400364013640236403364043640536406364073640836409364103641136412364133641436415364163641736418364193642036421364223642336424364253642636427364283642936430364313643236433364343643536436364373643836439364403644136442364433644436445364463644736448364493645036451364523645336454364553645636457364583645936460364613646236463364643646536466364673646836469364703647136472364733647436475364763647736478364793648036481364823648336484364853648636487364883648936490364913649236493364943649536496364973649836499365003650136502365033650436505365063650736508365093651036511365123651336514365153651636517365183651936520365213652236523365243652536526365273652836529365303653136532365333653436535365363653736538365393654036541365423654336544365453654636547365483654936550365513655236553365543655536556365573655836559365603656136562365633656436565365663656736568365693657036571365723657336574365753657636577365783657936580365813658236583365843658536586365873658836589365903659136592365933659436595365963659736598365993660036601366023660336604366053660636607366083660936610366113661236613366143661536616366173661836619366203662136622366233662436625366263662736628366293663036631366323663336634366353663636637366383663936640366413664236643366443664536646366473664836649366503665136652366533665436655366563665736658366593666036661366623666336664366653666636667366683666936670366713667236673366743667536676366773667836679366803668136682366833668436685366863668736688366893669036691366923669336694366953669636697366983669936700367013670236703367043670536706367073670836709367103671136712367133671436715367163671736718367193672036721367223672336724367253672636727367283672936730367313673236733367343673536736367373673836739367403674136742367433674436745367463674736748367493675036751367523675336754367553675636757367583675936760367613676236763367643676536766367673676836769367703677136772367733677436775367763677736778367793678036781367823678336784367853678636787367883678936790367913679236793367943679536796367973679836799368003680136802368033680436805368063680736808368093681036811368123681336814368153681636817368183681936820368213682236823368243682536826368273682836829368303683136832368333683436835368363683736838368393684036841368423684336844368453684636847368483684936850368513685236853368543685536856368573685836859368603686136862368633686436865368663686736868368693687036871368723687336874368753687636877368783687936880368813688236883368843688536886368873688836889368903689136892368933689436895368963689736898368993690036901369023690336904369053690636907369083690936910369113691236913369143691536916369173691836919369203692136922369233692436925369263692736928369293693036931369323693336934369353693636937369383693936940369413694236943369443694536946369473694836949369503695136952369533695436955369563695736958369593696036961369623696336964369653696636967369683696936970369713697236973369743697536976369773697836979369803698136982369833698436985369863698736988369893699036991369923699336994369953699636997369983699937000370013700237003370043700537006370073700837009370103701137012370133701437015370163701737018370193702037021370223702337024370253702637027370283702937030370313703237033370343703537036370373703837039370403704137042370433704437045370463704737048370493705037051370523705337054370553705637057370583705937060370613706237063370643706537066370673706837069370703707137072370733707437075370763707737078370793708037081370823708337084370853708637087370883708937090370913709237093370943709537096370973709837099371003710137102371033710437105371063710737108371093711037111371123711337114371153711637117371183711937120371213712237123371243712537126371273712837129371303713137132371333713437135371363713737138371393714037141371423714337144371453714637147371483714937150371513715237153371543715537156371573715837159371603716137162371633716437165371663716737168371693717037171371723717337174371753717637177371783717937180371813718237183371843718537186371873718837189371903719137192371933719437195371963719737198371993720037201372023720337204372053720637207372083720937210372113721237213372143721537216372173721837219372203722137222372233722437225372263722737228372293723037231372323723337234372353723637237372383723937240372413724237243372443724537246372473724837249372503725137252372533725437255372563725737258372593726037261372623726337264372653726637267372683726937270372713727237273372743727537276372773727837279372803728137282372833728437285372863728737288372893729037291372923729337294372953729637297372983729937300373013730237303373043730537306373073730837309373103731137312373133731437315373163731737318373193732037321373223732337324373253732637327373283732937330373313733237333373343733537336373373733837339373403734137342373433734437345373463734737348373493735037351373523735337354373553735637357373583735937360373613736237363373643736537366373673736837369373703737137372373733737437375373763737737378373793738037381373823738337384373853738637387373883738937390373913739237393373943739537396373973739837399374003740137402374033740437405374063740737408374093741037411374123741337414374153741637417374183741937420374213742237423374243742537426374273742837429374303743137432374333743437435374363743737438374393744037441374423744337444374453744637447374483744937450374513745237453374543745537456374573745837459374603746137462374633746437465374663746737468374693747037471374723747337474374753747637477374783747937480374813748237483374843748537486374873748837489374903749137492374933749437495374963749737498374993750037501375023750337504375053750637507375083750937510375113751237513375143751537516375173751837519375203752137522375233752437525375263752737528375293753037531375323753337534375353753637537375383753937540375413754237543375443754537546375473754837549375503755137552375533755437555375563755737558375593756037561375623756337564375653756637567375683756937570375713757237573375743757537576375773757837579375803758137582375833758437585375863758737588375893759037591375923759337594375953759637597375983759937600376013760237603376043760537606376073760837609376103761137612376133761437615376163761737618376193762037621376223762337624376253762637627376283762937630376313763237633376343763537636376373763837639376403764137642376433764437645376463764737648376493765037651376523765337654376553765637657376583765937660376613766237663376643766537666376673766837669376703767137672376733767437675376763767737678376793768037681376823768337684376853768637687376883768937690376913769237693376943769537696376973769837699377003770137702377033770437705377063770737708377093771037711377123771337714377153771637717377183771937720377213772237723377243772537726377273772837729377303773137732377333773437735377363773737738377393774037741377423774337744377453774637747377483774937750377513775237753377543775537756377573775837759377603776137762377633776437765377663776737768377693777037771377723777337774377753777637777377783777937780377813778237783377843778537786377873778837789377903779137792377933779437795377963779737798377993780037801378023780337804378053780637807378083780937810378113781237813378143781537816378173781837819378203782137822378233782437825378263782737828378293783037831378323783337834378353783637837378383783937840378413784237843378443784537846378473784837849378503785137852378533785437855378563785737858378593786037861378623786337864378653786637867378683786937870378713787237873378743787537876378773787837879378803788137882378833788437885378863788737888378893789037891378923789337894378953789637897378983789937900379013790237903379043790537906379073790837909379103791137912379133791437915379163791737918379193792037921379223792337924379253792637927379283792937930379313793237933379343793537936379373793837939379403794137942379433794437945379463794737948379493795037951379523795337954379553795637957379583795937960379613796237963379643796537966379673796837969379703797137972379733797437975379763797737978379793798037981379823798337984379853798637987379883798937990379913799237993379943799537996379973799837999380003800138002380033800438005380063800738008380093801038011380123801338014380153801638017380183801938020380213802238023380243802538026380273802838029380303803138032380333803438035380363803738038380393804038041380423804338044380453804638047380483804938050380513805238053380543805538056380573805838059380603806138062380633806438065380663806738068380693807038071380723807338074380753807638077380783807938080380813808238083380843808538086380873808838089380903809138092380933809438095380963809738098380993810038101381023810338104381053810638107381083810938110381113811238113381143811538116381173811838119381203812138122381233812438125381263812738128381293813038131381323813338134381353813638137381383813938140381413814238143381443814538146381473814838149381503815138152381533815438155381563815738158381593816038161381623816338164381653816638167381683816938170381713817238173381743817538176381773817838179381803818138182381833818438185381863818738188381893819038191381923819338194381953819638197381983819938200382013820238203382043820538206382073820838209382103821138212382133821438215382163821738218382193822038221382223822338224382253822638227382283822938230382313823238233382343823538236382373823838239382403824138242382433824438245382463824738248382493825038251382523825338254382553825638257382583825938260382613826238263382643826538266382673826838269382703827138272382733827438275382763827738278382793828038281382823828338284382853828638287382883828938290382913829238293382943829538296382973829838299383003830138302383033830438305383063830738308383093831038311383123831338314383153831638317383183831938320383213832238323383243832538326383273832838329383303833138332383333833438335383363833738338383393834038341383423834338344383453834638347383483834938350383513835238353383543835538356383573835838359383603836138362383633836438365383663836738368383693837038371383723837338374383753837638377383783837938380383813838238383383843838538386383873838838389383903839138392383933839438395383963839738398383993840038401384023840338404384053840638407384083840938410384113841238413384143841538416384173841838419384203842138422384233842438425384263842738428384293843038431384323843338434384353843638437384383843938440384413844238443384443844538446384473844838449384503845138452384533845438455384563845738458384593846038461384623846338464384653846638467384683846938470384713847238473384743847538476384773847838479384803848138482384833848438485384863848738488384893849038491384923849338494384953849638497384983849938500385013850238503385043850538506385073850838509385103851138512385133851438515385163851738518385193852038521385223852338524385253852638527385283852938530385313853238533385343853538536385373853838539385403854138542385433854438545385463854738548385493855038551385523855338554385553855638557385583855938560385613856238563385643856538566385673856838569385703857138572385733857438575385763857738578385793858038581385823858338584385853858638587385883858938590385913859238593385943859538596385973859838599386003860138602386033860438605386063860738608386093861038611386123861338614386153861638617386183861938620386213862238623386243862538626386273862838629386303863138632386333863438635386363863738638386393864038641386423864338644386453864638647386483864938650386513865238653386543865538656386573865838659386603866138662386633866438665386663866738668386693867038671386723867338674386753867638677386783867938680386813868238683386843868538686386873868838689386903869138692386933869438695386963869738698386993870038701387023870338704387053870638707387083870938710387113871238713387143871538716387173871838719387203872138722387233872438725387263872738728387293873038731387323873338734387353873638737387383873938740387413874238743387443874538746387473874838749387503875138752387533875438755387563875738758387593876038761387623876338764387653876638767387683876938770387713877238773387743877538776387773877838779387803878138782387833878438785387863878738788387893879038791387923879338794387953879638797387983879938800388013880238803388043880538806388073880838809388103881138812388133881438815388163881738818388193882038821388223882338824388253882638827388283882938830388313883238833388343883538836388373883838839388403884138842388433884438845388463884738848388493885038851388523885338854388553885638857388583885938860388613886238863388643886538866388673886838869388703887138872388733887438875388763887738878388793888038881388823888338884388853888638887388883888938890388913889238893388943889538896388973889838899389003890138902389033890438905389063890738908389093891038911389123891338914389153891638917389183891938920389213892238923389243892538926389273892838929389303893138932389333893438935389363893738938389393894038941389423894338944389453894638947389483894938950389513895238953389543895538956389573895838959389603896138962389633896438965389663896738968389693897038971389723897338974389753897638977389783897938980389813898238983389843898538986389873898838989389903899138992389933899438995389963899738998389993900039001390023900339004390053900639007390083900939010390113901239013390143901539016390173901839019390203902139022390233902439025390263902739028390293903039031390323903339034390353903639037390383903939040390413904239043390443904539046390473904839049390503905139052390533905439055390563905739058390593906039061390623906339064390653906639067390683906939070390713907239073390743907539076390773907839079390803908139082390833908439085390863908739088390893909039091390923909339094390953909639097390983909939100391013910239103391043910539106391073910839109391103911139112391133911439115391163911739118391193912039121391223912339124391253912639127391283912939130391313913239133391343913539136391373913839139391403914139142391433914439145391463914739148391493915039151391523915339154391553915639157391583915939160391613916239163391643916539166391673916839169391703917139172391733917439175391763917739178391793918039181391823918339184391853918639187391883918939190391913919239193391943919539196391973919839199392003920139202392033920439205392063920739208392093921039211392123921339214392153921639217392183921939220392213922239223392243922539226392273922839229392303923139232392333923439235392363923739238392393924039241392423924339244392453924639247392483924939250392513925239253392543925539256392573925839259392603926139262392633926439265392663926739268392693927039271392723927339274392753927639277392783927939280392813928239283392843928539286392873928839289392903929139292392933929439295392963929739298392993930039301393023930339304393053930639307393083930939310393113931239313393143931539316393173931839319393203932139322393233932439325393263932739328393293933039331393323933339334393353933639337393383933939340393413934239343393443934539346393473934839349393503935139352393533935439355393563935739358393593936039361393623936339364393653936639367393683936939370393713937239373393743937539376393773937839379393803938139382393833938439385393863938739388393893939039391393923939339394393953939639397393983939939400394013940239403394043940539406394073940839409394103941139412394133941439415394163941739418394193942039421394223942339424394253942639427394283942939430394313943239433394343943539436394373943839439394403944139442394433944439445394463944739448394493945039451394523945339454394553945639457394583945939460394613946239463394643946539466394673946839469394703947139472394733947439475394763947739478394793948039481394823948339484394853948639487394883948939490394913949239493394943949539496394973949839499395003950139502395033950439505395063950739508395093951039511395123951339514395153951639517395183951939520395213952239523395243952539526395273952839529395303953139532395333953439535395363953739538395393954039541395423954339544395453954639547395483954939550395513955239553395543955539556395573955839559395603956139562395633956439565395663956739568395693957039571395723957339574395753957639577395783957939580395813958239583395843958539586395873958839589395903959139592395933959439595395963959739598395993960039601396023960339604396053960639607396083960939610396113961239613396143961539616396173961839619396203962139622396233962439625396263962739628396293963039631396323963339634396353963639637396383963939640396413964239643396443964539646396473964839649396503965139652396533965439655396563965739658396593966039661396623966339664396653966639667396683966939670396713967239673396743967539676396773967839679396803968139682396833968439685396863968739688396893969039691396923969339694396953969639697396983969939700397013970239703397043970539706397073970839709397103971139712397133971439715397163971739718397193972039721397223972339724397253972639727397283972939730397313973239733397343973539736397373973839739397403974139742397433974439745397463974739748397493975039751397523975339754397553975639757397583975939760397613976239763397643976539766397673976839769397703977139772397733977439775397763977739778397793978039781397823978339784397853978639787397883978939790397913979239793397943979539796397973979839799398003980139802398033980439805398063980739808398093981039811398123981339814398153981639817398183981939820398213982239823398243982539826398273982839829398303983139832398333983439835398363983739838398393984039841398423984339844398453984639847398483984939850398513985239853398543985539856398573985839859398603986139862398633986439865398663986739868398693987039871398723987339874398753987639877398783987939880398813988239883398843988539886398873988839889398903989139892398933989439895398963989739898398993990039901399023990339904399053990639907399083990939910399113991239913399143991539916399173991839919399203992139922399233992439925399263992739928399293993039931399323993339934399353993639937399383993939940399413994239943399443994539946399473994839949399503995139952399533995439955399563995739958399593996039961399623996339964399653996639967399683996939970399713997239973399743997539976399773997839979399803998139982399833998439985399863998739988399893999039991399923999339994399953999639997399983999940000400014000240003400044000540006400074000840009400104001140012400134001440015400164001740018400194002040021400224002340024400254002640027400284002940030400314003240033400344003540036400374003840039400404004140042400434004440045400464004740048400494005040051400524005340054400554005640057400584005940060400614006240063400644006540066400674006840069400704007140072400734007440075400764007740078400794008040081400824008340084400854008640087400884008940090400914009240093400944009540096400974009840099401004010140102401034010440105401064010740108401094011040111401124011340114401154011640117401184011940120401214012240123401244012540126401274012840129401304013140132401334013440135401364013740138401394014040141401424014340144401454014640147401484014940150401514015240153401544015540156401574015840159401604016140162401634016440165401664016740168401694017040171401724017340174401754017640177401784017940180401814018240183401844018540186401874018840189401904019140192401934019440195401964019740198401994020040201402024020340204402054020640207402084020940210402114021240213402144021540216402174021840219402204022140222402234022440225402264022740228402294023040231402324023340234402354023640237402384023940240402414024240243402444024540246402474024840249402504025140252402534025440255402564025740258402594026040261402624026340264402654026640267402684026940270402714027240273402744027540276402774027840279402804028140282402834028440285402864028740288402894029040291402924029340294402954029640297402984029940300403014030240303403044030540306403074030840309403104031140312403134031440315403164031740318403194032040321403224032340324403254032640327403284032940330403314033240333403344033540336403374033840339403404034140342403434034440345403464034740348403494035040351403524035340354403554035640357403584035940360403614036240363403644036540366403674036840369403704037140372403734037440375403764037740378403794038040381403824038340384403854038640387403884038940390403914039240393403944039540396403974039840399404004040140402404034040440405404064040740408404094041040411404124041340414404154041640417404184041940420404214042240423404244042540426404274042840429404304043140432404334043440435404364043740438404394044040441404424044340444404454044640447404484044940450404514045240453404544045540456404574045840459404604046140462404634046440465404664046740468404694047040471404724047340474404754047640477404784047940480404814048240483404844048540486404874048840489404904049140492404934049440495404964049740498404994050040501405024050340504405054050640507405084050940510405114051240513405144051540516405174051840519405204052140522405234052440525405264052740528405294053040531405324053340534405354053640537405384053940540405414054240543405444054540546405474054840549405504055140552405534055440555405564055740558405594056040561405624056340564405654056640567405684056940570405714057240573405744057540576405774057840579405804058140582405834058440585405864058740588405894059040591405924059340594405954059640597405984059940600406014060240603406044060540606406074060840609406104061140612406134061440615406164061740618406194062040621406224062340624406254062640627406284062940630406314063240633406344063540636406374063840639406404064140642406434064440645406464064740648406494065040651406524065340654406554065640657406584065940660406614066240663406644066540666406674066840669406704067140672406734067440675406764067740678406794068040681406824068340684406854068640687406884068940690406914069240693406944069540696406974069840699407004070140702407034070440705407064070740708407094071040711407124071340714407154071640717407184071940720407214072240723407244072540726407274072840729407304073140732407334073440735407364073740738407394074040741407424074340744407454074640747407484074940750407514075240753407544075540756407574075840759407604076140762407634076440765407664076740768407694077040771407724077340774407754077640777407784077940780407814078240783407844078540786407874078840789407904079140792407934079440795407964079740798407994080040801408024080340804408054080640807408084080940810408114081240813408144081540816408174081840819408204082140822408234082440825408264082740828408294083040831408324083340834408354083640837408384083940840408414084240843408444084540846408474084840849408504085140852408534085440855408564085740858408594086040861408624086340864408654086640867408684086940870408714087240873408744087540876408774087840879408804088140882408834088440885408864088740888408894089040891408924089340894408954089640897408984089940900409014090240903409044090540906409074090840909409104091140912409134091440915409164091740918409194092040921409224092340924409254092640927409284092940930409314093240933409344093540936409374093840939409404094140942409434094440945409464094740948409494095040951409524095340954409554095640957409584095940960409614096240963409644096540966409674096840969409704097140972409734097440975409764097740978409794098040981409824098340984409854098640987409884098940990409914099240993409944099540996409974099840999410004100141002410034100441005410064100741008410094101041011410124101341014410154101641017410184101941020410214102241023410244102541026410274102841029410304103141032410334103441035410364103741038410394104041041410424104341044410454104641047410484104941050410514105241053410544105541056410574105841059410604106141062410634106441065410664106741068410694107041071410724107341074410754107641077410784107941080410814108241083410844108541086410874108841089410904109141092410934109441095410964109741098410994110041101411024110341104411054110641107411084110941110411114111241113411144111541116411174111841119411204112141122411234112441125411264112741128411294113041131411324113341134411354113641137411384113941140411414114241143411444114541146411474114841149411504115141152411534115441155411564115741158411594116041161411624116341164411654116641167411684116941170411714117241173411744117541176411774117841179411804118141182411834118441185411864118741188411894119041191411924119341194411954119641197411984119941200412014120241203412044120541206412074120841209412104121141212412134121441215412164121741218412194122041221412224122341224412254122641227412284122941230412314123241233412344123541236412374123841239412404124141242412434124441245412464124741248412494125041251412524125341254412554125641257412584125941260412614126241263412644126541266412674126841269412704127141272412734127441275412764127741278412794128041281412824128341284412854128641287412884128941290412914129241293412944129541296412974129841299413004130141302413034130441305413064130741308413094131041311413124131341314413154131641317413184131941320413214132241323413244132541326413274132841329413304133141332413334133441335413364133741338413394134041341413424134341344413454134641347413484134941350413514135241353413544135541356413574135841359413604136141362413634136441365413664136741368413694137041371413724137341374413754137641377413784137941380413814138241383413844138541386413874138841389413904139141392413934139441395413964139741398413994140041401414024140341404414054140641407414084140941410414114141241413414144141541416414174141841419414204142141422414234142441425414264142741428414294143041431414324143341434414354143641437414384143941440414414144241443414444144541446414474144841449414504145141452414534145441455414564145741458414594146041461414624146341464414654146641467414684146941470414714147241473414744147541476414774147841479414804148141482414834148441485414864148741488414894149041491414924149341494414954149641497414984149941500415014150241503415044150541506415074150841509415104151141512415134151441515415164151741518415194152041521415224152341524415254152641527415284152941530415314153241533415344153541536415374153841539415404154141542415434154441545415464154741548415494155041551415524155341554415554155641557415584155941560415614156241563415644156541566415674156841569415704157141572415734157441575415764157741578415794158041581415824158341584415854158641587415884158941590415914159241593415944159541596415974159841599416004160141602416034160441605416064160741608416094161041611416124161341614416154161641617416184161941620416214162241623416244162541626416274162841629416304163141632416334163441635416364163741638416394164041641416424164341644416454164641647416484164941650416514165241653416544165541656416574165841659416604166141662416634166441665416664166741668416694167041671416724167341674416754167641677416784167941680416814168241683416844168541686416874168841689416904169141692416934169441695416964169741698416994170041701417024170341704417054170641707417084170941710417114171241713417144171541716417174171841719417204172141722417234172441725417264172741728417294173041731417324173341734417354173641737417384173941740417414174241743417444174541746417474174841749417504175141752417534175441755417564175741758417594176041761417624176341764417654176641767417684176941770417714177241773417744177541776417774177841779417804178141782417834178441785417864178741788417894179041791417924179341794417954179641797417984179941800418014180241803418044180541806418074180841809418104181141812418134181441815418164181741818418194182041821418224182341824418254182641827418284182941830418314183241833418344183541836418374183841839418404184141842418434184441845418464184741848418494185041851418524185341854418554185641857418584185941860418614186241863418644186541866418674186841869418704187141872418734187441875418764187741878418794188041881418824188341884418854188641887418884188941890418914189241893418944189541896418974189841899419004190141902419034190441905419064190741908419094191041911419124191341914419154191641917419184191941920419214192241923419244192541926419274192841929419304193141932419334193441935419364193741938419394194041941419424194341944419454194641947419484194941950419514195241953419544195541956419574195841959419604196141962419634196441965419664196741968419694197041971419724197341974419754197641977419784197941980419814198241983419844198541986419874198841989419904199141992419934199441995419964199741998419994200042001420024200342004420054200642007420084200942010420114201242013420144201542016420174201842019420204202142022420234202442025420264202742028420294203042031420324203342034420354203642037420384203942040420414204242043420444204542046420474204842049420504205142052420534205442055420564205742058420594206042061420624206342064420654206642067420684206942070420714207242073420744207542076420774207842079420804208142082420834208442085420864208742088420894209042091420924209342094420954209642097420984209942100421014210242103421044210542106421074210842109421104211142112421134211442115421164211742118421194212042121421224212342124421254212642127421284212942130421314213242133421344213542136421374213842139421404214142142421434214442145421464214742148421494215042151421524215342154421554215642157421584215942160421614216242163421644216542166421674216842169421704217142172421734217442175421764217742178421794218042181421824218342184421854218642187421884218942190421914219242193421944219542196421974219842199422004220142202422034220442205422064220742208422094221042211422124221342214422154221642217422184221942220422214222242223422244222542226422274222842229422304223142232422334223442235422364223742238422394224042241422424224342244422454224642247422484224942250422514225242253422544225542256422574225842259422604226142262422634226442265422664226742268422694227042271422724227342274422754227642277422784227942280422814228242283422844228542286422874228842289422904229142292422934229442295422964229742298422994230042301423024230342304423054230642307423084230942310423114231242313423144231542316423174231842319423204232142322423234232442325423264232742328423294233042331423324233342334423354233642337423384233942340423414234242343423444234542346423474234842349423504235142352423534235442355423564235742358423594236042361423624236342364423654236642367423684236942370423714237242373423744237542376423774237842379423804238142382423834238442385423864238742388423894239042391423924239342394423954239642397423984239942400424014240242403424044240542406424074240842409424104241142412424134241442415424164241742418424194242042421424224242342424424254242642427424284242942430424314243242433424344243542436424374243842439424404244142442424434244442445424464244742448424494245042451424524245342454424554245642457424584245942460424614246242463424644246542466424674246842469424704247142472424734247442475424764247742478424794248042481424824248342484424854248642487424884248942490424914249242493424944249542496424974249842499425004250142502425034250442505425064250742508425094251042511425124251342514425154251642517425184251942520425214252242523425244252542526425274252842529425304253142532425334253442535425364253742538425394254042541425424254342544425454254642547425484254942550425514255242553425544255542556425574255842559425604256142562425634256442565425664256742568425694257042571425724257342574425754257642577425784257942580425814258242583425844258542586425874258842589425904259142592425934259442595425964259742598425994260042601426024260342604426054260642607426084260942610426114261242613426144261542616426174261842619426204262142622426234262442625426264262742628426294263042631426324263342634426354263642637426384263942640426414264242643426444264542646426474264842649426504265142652426534265442655426564265742658426594266042661426624266342664426654266642667426684266942670426714267242673426744267542676426774267842679426804268142682426834268442685426864268742688426894269042691426924269342694426954269642697426984269942700427014270242703427044270542706427074270842709427104271142712427134271442715427164271742718427194272042721427224272342724427254272642727427284272942730427314273242733427344273542736427374273842739427404274142742427434274442745427464274742748427494275042751427524275342754427554275642757427584275942760427614276242763427644276542766427674276842769427704277142772427734277442775427764277742778427794278042781427824278342784427854278642787427884278942790427914279242793427944279542796427974279842799428004280142802428034280442805428064280742808428094281042811428124281342814428154281642817428184281942820428214282242823428244282542826428274282842829428304283142832428334283442835428364283742838428394284042841428424284342844428454284642847428484284942850428514285242853428544285542856428574285842859428604286142862428634286442865428664286742868428694287042871428724287342874428754287642877428784287942880428814288242883428844288542886428874288842889428904289142892428934289442895428964289742898428994290042901429024290342904429054290642907429084290942910429114291242913429144291542916429174291842919429204292142922429234292442925429264292742928429294293042931429324293342934429354293642937429384293942940429414294242943429444294542946429474294842949429504295142952429534295442955429564295742958429594296042961429624296342964429654296642967429684296942970429714297242973429744297542976429774297842979429804298142982429834298442985429864298742988429894299042991429924299342994429954299642997429984299943000430014300243003430044300543006430074300843009430104301143012430134301443015430164301743018430194302043021430224302343024430254302643027430284302943030430314303243033430344303543036430374303843039430404304143042430434304443045430464304743048430494305043051430524305343054430554305643057430584305943060430614306243063430644306543066430674306843069430704307143072430734307443075430764307743078430794308043081430824308343084430854308643087430884308943090430914309243093430944309543096430974309843099431004310143102431034310443105431064310743108431094311043111431124311343114431154311643117431184311943120431214312243123431244312543126431274312843129431304313143132431334313443135431364313743138431394314043141431424314343144431454314643147431484314943150431514315243153431544315543156431574315843159431604316143162431634316443165431664316743168431694317043171431724317343174431754317643177431784317943180431814318243183431844318543186431874318843189431904319143192431934319443195431964319743198431994320043201432024320343204432054320643207432084320943210432114321243213432144321543216432174321843219432204322143222432234322443225432264322743228432294323043231432324323343234432354323643237432384323943240432414324243243432444324543246432474324843249432504325143252432534325443255432564325743258432594326043261432624326343264432654326643267432684326943270432714327243273432744327543276432774327843279432804328143282432834328443285432864328743288432894329043291432924329343294432954329643297432984329943300433014330243303433044330543306433074330843309433104331143312433134331443315433164331743318433194332043321433224332343324433254332643327433284332943330433314333243333433344333543336433374333843339433404334143342433434334443345433464334743348433494335043351433524335343354433554335643357433584335943360433614336243363433644336543366433674336843369433704337143372433734337443375433764337743378433794338043381433824338343384433854338643387433884338943390433914339243393433944339543396433974339843399434004340143402434034340443405434064340743408434094341043411434124341343414434154341643417434184341943420434214342243423434244342543426434274342843429434304343143432434334343443435434364343743438434394344043441434424344343444434454344643447434484344943450434514345243453434544345543456434574345843459434604346143462434634346443465434664346743468434694347043471434724347343474434754347643477434784347943480434814348243483434844348543486434874348843489434904349143492434934349443495434964349743498434994350043501435024350343504435054350643507435084350943510435114351243513435144351543516435174351843519435204352143522435234352443525435264352743528435294353043531435324353343534435354353643537435384353943540435414354243543435444354543546435474354843549435504355143552435534355443555435564355743558435594356043561435624356343564435654356643567435684356943570435714357243573435744357543576435774357843579435804358143582435834358443585435864358743588435894359043591435924359343594435954359643597435984359943600436014360243603436044360543606436074360843609436104361143612436134361443615436164361743618436194362043621436224362343624436254362643627436284362943630436314363243633436344363543636436374363843639436404364143642436434364443645436464364743648436494365043651436524365343654436554365643657436584365943660436614366243663436644366543666436674366843669436704367143672436734367443675436764367743678436794368043681436824368343684436854368643687436884368943690436914369243693436944369543696436974369843699437004370143702437034370443705437064370743708437094371043711437124371343714437154371643717437184371943720437214372243723437244372543726437274372843729437304373143732437334373443735437364373743738437394374043741437424374343744437454374643747437484374943750437514375243753437544375543756437574375843759437604376143762437634376443765437664376743768437694377043771437724377343774437754377643777437784377943780437814378243783437844378543786437874378843789437904379143792437934379443795437964379743798437994380043801438024380343804438054380643807438084380943810438114381243813438144381543816438174381843819438204382143822438234382443825438264382743828438294383043831438324383343834438354383643837438384383943840438414384243843438444384543846438474384843849438504385143852438534385443855438564385743858438594386043861438624386343864438654386643867438684386943870438714387243873438744387543876438774387843879438804388143882438834388443885438864388743888438894389043891438924389343894438954389643897438984389943900439014390243903439044390543906439074390843909439104391143912439134391443915439164391743918439194392043921439224392343924439254392643927439284392943930439314393243933439344393543936439374393843939439404394143942439434394443945439464394743948439494395043951439524395343954439554395643957439584395943960439614396243963439644396543966439674396843969439704397143972439734397443975439764397743978439794398043981439824398343984439854398643987439884398943990439914399243993439944399543996439974399843999440004400144002440034400444005440064400744008440094401044011440124401344014440154401644017440184401944020440214402244023440244402544026440274402844029440304403144032440334403444035440364403744038440394404044041440424404344044440454404644047440484404944050440514405244053440544405544056440574405844059440604406144062440634406444065440664406744068440694407044071440724407344074440754407644077440784407944080440814408244083440844408544086440874408844089440904409144092440934409444095440964409744098440994410044101441024410344104441054410644107441084410944110441114411244113441144411544116441174411844119441204412144122441234412444125441264412744128441294413044131441324413344134441354413644137441384413944140441414414244143441444414544146441474414844149441504415144152441534415444155441564415744158441594416044161441624416344164441654416644167441684416944170441714417244173441744417544176441774417844179441804418144182441834418444185441864418744188441894419044191441924419344194441954419644197441984419944200442014420244203442044420544206442074420844209442104421144212442134421444215442164421744218442194422044221442224422344224442254422644227442284422944230442314423244233442344423544236442374423844239442404424144242442434424444245442464424744248442494425044251442524425344254442554425644257442584425944260442614426244263442644426544266442674426844269442704427144272442734427444275442764427744278442794428044281442824428344284442854428644287442884428944290442914429244293442944429544296442974429844299443004430144302443034430444305443064430744308443094431044311443124431344314443154431644317443184431944320443214432244323443244432544326443274432844329443304433144332443334433444335443364433744338443394434044341443424434344344443454434644347443484434944350443514435244353443544435544356443574435844359443604436144362443634436444365443664436744368443694437044371443724437344374443754437644377443784437944380443814438244383443844438544386443874438844389443904439144392443934439444395443964439744398443994440044401444024440344404444054440644407444084440944410444114441244413444144441544416444174441844419444204442144422444234442444425444264442744428444294443044431444324443344434444354443644437444384443944440444414444244443444444444544446444474444844449444504445144452444534445444455444564445744458444594446044461444624446344464444654446644467444684446944470444714447244473444744447544476444774447844479444804448144482444834448444485444864448744488444894449044491444924449344494444954449644497444984449944500445014450244503445044450544506445074450844509445104451144512445134451444515445164451744518445194452044521445224452344524445254452644527445284452944530445314453244533445344453544536445374453844539445404454144542445434454444545445464454744548445494455044551445524455344554445554455644557445584455944560445614456244563445644456544566445674456844569445704457144572445734457444575445764457744578445794458044581445824458344584445854458644587445884458944590445914459244593445944459544596445974459844599446004460144602446034460444605446064460744608446094461044611446124461344614446154461644617446184461944620446214462244623446244462544626446274462844629446304463144632446334463444635446364463744638446394464044641446424464344644446454464644647446484464944650446514465244653446544465544656446574465844659446604466144662446634466444665446664466744668446694467044671446724467344674446754467644677446784467944680446814468244683446844468544686446874468844689446904469144692446934469444695446964469744698446994470044701447024470344704447054470644707447084470944710447114471244713447144471544716447174471844719447204472144722447234472444725447264472744728447294473044731447324473344734447354473644737447384473944740447414474244743447444474544746447474474844749447504475144752447534475444755447564475744758447594476044761447624476344764447654476644767447684476944770447714477244773447744477544776447774477844779447804478144782447834478444785447864478744788447894479044791447924479344794447954479644797447984479944800448014480244803448044480544806448074480844809448104481144812448134481444815448164481744818448194482044821448224482344824448254482644827448284482944830448314483244833448344483544836448374483844839448404484144842448434484444845448464484744848448494485044851448524485344854448554485644857448584485944860448614486244863448644486544866448674486844869448704487144872448734487444875448764487744878448794488044881448824488344884448854488644887448884488944890448914489244893448944489544896448974489844899449004490144902449034490444905449064490744908449094491044911449124491344914449154491644917449184491944920449214492244923449244492544926449274492844929449304493144932449334493444935449364493744938449394494044941449424494344944449454494644947449484494944950449514495244953449544495544956449574495844959449604496144962449634496444965449664496744968449694497044971449724497344974449754497644977449784497944980449814498244983449844498544986449874498844989449904499144992449934499444995449964499744998449994500045001450024500345004450054500645007450084500945010450114501245013450144501545016450174501845019450204502145022450234502445025450264502745028450294503045031450324503345034450354503645037450384503945040450414504245043450444504545046450474504845049450504505145052450534505445055450564505745058450594506045061450624506345064450654506645067450684506945070450714507245073450744507545076450774507845079450804508145082450834508445085450864508745088450894509045091450924509345094450954509645097450984509945100451014510245103451044510545106451074510845109451104511145112451134511445115451164511745118451194512045121451224512345124451254512645127451284512945130451314513245133451344513545136451374513845139451404514145142451434514445145451464514745148451494515045151451524515345154451554515645157451584515945160451614516245163451644516545166451674516845169451704517145172451734517445175451764517745178451794518045181451824518345184451854518645187451884518945190451914519245193451944519545196451974519845199452004520145202452034520445205452064520745208452094521045211452124521345214452154521645217452184521945220452214522245223452244522545226452274522845229452304523145232452334523445235452364523745238452394524045241452424524345244452454524645247452484524945250452514525245253452544525545256452574525845259452604526145262452634526445265452664526745268452694527045271452724527345274452754527645277452784527945280452814528245283452844528545286452874528845289452904529145292452934529445295452964529745298452994530045301453024530345304453054530645307453084530945310453114531245313453144531545316453174531845319453204532145322453234532445325453264532745328453294533045331453324533345334453354533645337453384533945340453414534245343453444534545346453474534845349453504535145352453534535445355453564535745358453594536045361453624536345364453654536645367453684536945370453714537245373453744537545376453774537845379453804538145382453834538445385453864538745388453894539045391453924539345394453954539645397453984539945400454014540245403454044540545406454074540845409454104541145412454134541445415454164541745418454194542045421454224542345424454254542645427454284542945430454314543245433454344543545436454374543845439454404544145442454434544445445454464544745448454494545045451454524545345454454554545645457454584545945460454614546245463454644546545466454674546845469454704547145472454734547445475454764547745478454794548045481454824548345484454854548645487454884548945490454914549245493454944549545496454974549845499455004550145502455034550445505455064550745508455094551045511455124551345514455154551645517455184551945520455214552245523455244552545526455274552845529455304553145532455334553445535455364553745538455394554045541455424554345544455454554645547455484554945550455514555245553455544555545556455574555845559455604556145562455634556445565455664556745568455694557045571455724557345574455754557645577455784557945580455814558245583455844558545586455874558845589455904559145592455934559445595455964559745598455994560045601456024560345604456054560645607456084560945610456114561245613456144561545616456174561845619456204562145622456234562445625456264562745628456294563045631456324563345634456354563645637456384563945640456414564245643456444564545646456474564845649456504565145652456534565445655456564565745658456594566045661456624566345664456654566645667456684566945670456714567245673456744567545676456774567845679456804568145682456834568445685456864568745688456894569045691456924569345694456954569645697456984569945700457014570245703457044570545706457074570845709457104571145712457134571445715457164571745718457194572045721457224572345724457254572645727457284572945730457314573245733457344573545736457374573845739457404574145742457434574445745457464574745748457494575045751457524575345754457554575645757457584575945760457614576245763457644576545766457674576845769457704577145772457734577445775457764577745778457794578045781457824578345784457854578645787457884578945790457914579245793457944579545796457974579845799458004580145802458034580445805458064580745808458094581045811458124581345814458154581645817458184581945820458214582245823458244582545826458274582845829458304583145832458334583445835458364583745838458394584045841458424584345844458454584645847458484584945850458514585245853458544585545856458574585845859458604586145862458634586445865458664586745868458694587045871458724587345874458754587645877458784587945880458814588245883458844588545886458874588845889458904589145892458934589445895458964589745898458994590045901459024590345904459054590645907459084590945910459114591245913459144591545916459174591845919459204592145922459234592445925459264592745928459294593045931459324593345934459354593645937459384593945940459414594245943459444594545946459474594845949459504595145952459534595445955459564595745958459594596045961459624596345964459654596645967459684596945970459714597245973459744597545976459774597845979459804598145982459834598445985459864598745988459894599045991459924599345994459954599645997459984599946000460014600246003460044600546006460074600846009460104601146012460134601446015460164601746018460194602046021460224602346024460254602646027460284602946030460314603246033460344603546036460374603846039460404604146042460434604446045460464604746048460494605046051460524605346054460554605646057460584605946060460614606246063460644606546066460674606846069460704607146072460734607446075460764607746078460794608046081460824608346084460854608646087460884608946090460914609246093460944609546096460974609846099461004610146102461034610446105461064610746108461094611046111461124611346114461154611646117461184611946120461214612246123461244612546126461274612846129461304613146132461334613446135461364613746138461394614046141461424614346144461454614646147461484614946150461514615246153461544615546156461574615846159461604616146162461634616446165461664616746168461694617046171461724617346174461754617646177461784617946180461814618246183461844618546186461874618846189461904619146192461934619446195461964619746198461994620046201462024620346204462054620646207462084620946210462114621246213462144621546216462174621846219462204622146222462234622446225462264622746228462294623046231462324623346234462354623646237462384623946240462414624246243462444624546246462474624846249462504625146252462534625446255462564625746258462594626046261462624626346264462654626646267462684626946270462714627246273462744627546276462774627846279462804628146282462834628446285462864628746288462894629046291462924629346294462954629646297462984629946300463014630246303463044630546306463074630846309463104631146312463134631446315463164631746318463194632046321463224632346324463254632646327463284632946330463314633246333463344633546336463374633846339463404634146342463434634446345463464634746348463494635046351463524635346354463554635646357463584635946360463614636246363463644636546366463674636846369463704637146372463734637446375463764637746378463794638046381463824638346384463854638646387463884638946390463914639246393463944639546396463974639846399464004640146402464034640446405464064640746408464094641046411464124641346414464154641646417464184641946420464214642246423464244642546426464274642846429464304643146432464334643446435464364643746438464394644046441464424644346444464454644646447464484644946450464514645246453464544645546456464574645846459464604646146462464634646446465464664646746468464694647046471464724647346474464754647646477464784647946480464814648246483464844648546486464874648846489464904649146492464934649446495464964649746498464994650046501465024650346504465054650646507465084650946510465114651246513465144651546516465174651846519465204652146522465234652446525465264652746528465294653046531465324653346534465354653646537465384653946540465414654246543465444654546546465474654846549465504655146552465534655446555465564655746558465594656046561465624656346564465654656646567465684656946570465714657246573465744657546576465774657846579465804658146582465834658446585465864658746588465894659046591465924659346594465954659646597465984659946600466014660246603466044660546606466074660846609466104661146612466134661446615466164661746618466194662046621466224662346624466254662646627466284662946630466314663246633466344663546636466374663846639466404664146642466434664446645466464664746648466494665046651466524665346654466554665646657466584665946660466614666246663466644666546666466674666846669466704667146672466734667446675466764667746678466794668046681466824668346684466854668646687466884668946690466914669246693466944669546696466974669846699467004670146702467034670446705467064670746708467094671046711467124671346714467154671646717467184671946720467214672246723467244672546726467274672846729467304673146732467334673446735467364673746738467394674046741467424674346744467454674646747467484674946750467514675246753467544675546756467574675846759467604676146762467634676446765467664676746768467694677046771467724677346774467754677646777467784677946780467814678246783467844678546786467874678846789467904679146792467934679446795467964679746798467994680046801468024680346804468054680646807468084680946810468114681246813468144681546816468174681846819468204682146822468234682446825468264682746828468294683046831468324683346834468354683646837468384683946840468414684246843468444684546846468474684846849468504685146852468534685446855468564685746858468594686046861468624686346864468654686646867468684686946870468714687246873468744687546876468774687846879468804688146882468834688446885468864688746888468894689046891468924689346894468954689646897468984689946900469014690246903469044690546906469074690846909469104691146912469134691446915469164691746918469194692046921469224692346924469254692646927469284692946930469314693246933469344693546936469374693846939469404694146942469434694446945469464694746948469494695046951469524695346954469554695646957469584695946960469614696246963469644696546966469674696846969469704697146972469734697446975469764697746978469794698046981469824698346984469854698646987469884698946990469914699246993469944699546996469974699846999470004700147002470034700447005470064700747008470094701047011470124701347014470154701647017470184701947020470214702247023470244702547026470274702847029470304703147032470334703447035470364703747038470394704047041470424704347044470454704647047470484704947050470514705247053470544705547056470574705847059470604706147062470634706447065470664706747068470694707047071470724707347074470754707647077470784707947080470814708247083470844708547086470874708847089470904709147092470934709447095470964709747098470994710047101471024710347104471054710647107471084710947110471114711247113471144711547116471174711847119471204712147122471234712447125471264712747128471294713047131471324713347134471354713647137471384713947140471414714247143471444714547146471474714847149471504715147152471534715447155471564715747158471594716047161471624716347164471654716647167471684716947170471714717247173471744717547176471774717847179471804718147182471834718447185471864718747188471894719047191471924719347194471954719647197471984719947200472014720247203472044720547206472074720847209472104721147212472134721447215472164721747218472194722047221472224722347224472254722647227472284722947230472314723247233472344723547236472374723847239472404724147242472434724447245472464724747248472494725047251472524725347254472554725647257472584725947260472614726247263472644726547266472674726847269472704727147272472734727447275472764727747278472794728047281472824728347284472854728647287472884728947290472914729247293472944729547296472974729847299473004730147302473034730447305473064730747308473094731047311473124731347314473154731647317473184731947320473214732247323473244732547326473274732847329473304733147332473334733447335473364733747338473394734047341473424734347344473454734647347473484734947350473514735247353473544735547356473574735847359473604736147362473634736447365473664736747368473694737047371473724737347374473754737647377473784737947380473814738247383473844738547386473874738847389473904739147392473934739447395473964739747398473994740047401474024740347404474054740647407474084740947410474114741247413474144741547416474174741847419474204742147422474234742447425474264742747428474294743047431474324743347434474354743647437474384743947440474414744247443474444744547446474474744847449474504745147452474534745447455474564745747458474594746047461474624746347464474654746647467474684746947470474714747247473474744747547476474774747847479474804748147482474834748447485474864748747488474894749047491474924749347494474954749647497474984749947500475014750247503475044750547506475074750847509475104751147512475134751447515475164751747518475194752047521475224752347524475254752647527475284752947530475314753247533475344753547536475374753847539475404754147542475434754447545475464754747548475494755047551475524755347554475554755647557475584755947560475614756247563475644756547566475674756847569475704757147572475734757447575475764757747578475794758047581475824758347584475854758647587475884758947590475914759247593475944759547596475974759847599476004760147602476034760447605476064760747608476094761047611476124761347614476154761647617476184761947620476214762247623476244762547626476274762847629476304763147632476334763447635476364763747638476394764047641476424764347644476454764647647476484764947650476514765247653476544765547656476574765847659476604766147662476634766447665476664766747668476694767047671476724767347674476754767647677476784767947680476814768247683476844768547686476874768847689476904769147692476934769447695476964769747698476994770047701477024770347704477054770647707477084770947710477114771247713477144771547716477174771847719477204772147722477234772447725477264772747728477294773047731477324773347734477354773647737477384773947740477414774247743477444774547746477474774847749477504775147752477534775447755477564775747758477594776047761477624776347764477654776647767477684776947770477714777247773477744777547776477774777847779477804778147782477834778447785477864778747788477894779047791477924779347794477954779647797477984779947800478014780247803478044780547806478074780847809478104781147812478134781447815478164781747818478194782047821478224782347824478254782647827478284782947830478314783247833478344783547836478374783847839478404784147842478434784447845478464784747848478494785047851478524785347854478554785647857478584785947860478614786247863478644786547866478674786847869478704787147872478734787447875478764787747878478794788047881478824788347884478854788647887478884788947890478914789247893478944789547896478974789847899479004790147902479034790447905479064790747908479094791047911479124791347914479154791647917479184791947920479214792247923479244792547926479274792847929479304793147932479334793447935479364793747938479394794047941479424794347944479454794647947479484794947950479514795247953479544795547956479574795847959479604796147962479634796447965479664796747968479694797047971479724797347974479754797647977479784797947980479814798247983479844798547986479874798847989479904799147992479934799447995479964799747998479994800048001480024800348004480054800648007480084800948010480114801248013480144801548016480174801848019480204802148022480234802448025480264802748028480294803048031480324803348034480354803648037480384803948040480414804248043480444804548046480474804848049480504805148052480534805448055480564805748058480594806048061480624806348064480654806648067480684806948070480714807248073480744807548076480774807848079480804808148082480834808448085480864808748088480894809048091480924809348094480954809648097480984809948100481014810248103481044810548106481074810848109481104811148112481134811448115481164811748118481194812048121481224812348124481254812648127481284812948130481314813248133481344813548136481374813848139481404814148142481434814448145481464814748148481494815048151481524815348154481554815648157481584815948160481614816248163481644816548166481674816848169481704817148172481734817448175481764817748178481794818048181481824818348184481854818648187481884818948190481914819248193481944819548196481974819848199482004820148202482034820448205482064820748208482094821048211482124821348214482154821648217482184821948220482214822248223482244822548226482274822848229482304823148232482334823448235482364823748238482394824048241482424824348244482454824648247482484824948250482514825248253482544825548256482574825848259482604826148262482634826448265482664826748268482694827048271482724827348274482754827648277482784827948280482814828248283482844828548286482874828848289482904829148292482934829448295482964829748298482994830048301483024830348304483054830648307483084830948310483114831248313483144831548316483174831848319483204832148322483234832448325483264832748328483294833048331483324833348334483354833648337483384833948340483414834248343483444834548346483474834848349483504835148352483534835448355483564835748358483594836048361483624836348364483654836648367483684836948370483714837248373483744837548376483774837848379483804838148382483834838448385483864838748388483894839048391483924839348394483954839648397483984839948400484014840248403484044840548406484074840848409484104841148412484134841448415484164841748418484194842048421484224842348424484254842648427484284842948430484314843248433484344843548436484374843848439484404844148442484434844448445484464844748448484494845048451484524845348454484554845648457484584845948460484614846248463484644846548466484674846848469484704847148472484734847448475484764847748478484794848048481484824848348484484854848648487484884848948490484914849248493484944849548496484974849848499485004850148502485034850448505485064850748508485094851048511485124851348514485154851648517485184851948520485214852248523485244852548526485274852848529485304853148532485334853448535485364853748538485394854048541485424854348544485454854648547485484854948550485514855248553485544855548556485574855848559485604856148562485634856448565485664856748568485694857048571485724857348574485754857648577485784857948580485814858248583485844858548586485874858848589485904859148592485934859448595485964859748598485994860048601486024860348604486054860648607486084860948610486114861248613486144861548616486174861848619486204862148622486234862448625486264862748628486294863048631486324863348634486354863648637486384863948640486414864248643486444864548646486474864848649486504865148652486534865448655486564865748658486594866048661486624866348664486654866648667486684866948670486714867248673486744867548676486774867848679486804868148682486834868448685486864868748688486894869048691486924869348694486954869648697486984869948700487014870248703487044870548706487074870848709487104871148712487134871448715487164871748718487194872048721487224872348724487254872648727487284872948730487314873248733487344873548736487374873848739487404874148742487434874448745487464874748748487494875048751487524875348754487554875648757487584875948760487614876248763487644876548766487674876848769487704877148772487734877448775487764877748778487794878048781487824878348784487854878648787487884878948790487914879248793487944879548796487974879848799488004880148802488034880448805488064880748808488094881048811488124881348814488154881648817488184881948820488214882248823488244882548826488274882848829488304883148832488334883448835488364883748838488394884048841488424884348844488454884648847488484884948850488514885248853488544885548856488574885848859488604886148862488634886448865488664886748868488694887048871488724887348874488754887648877488784887948880488814888248883488844888548886488874888848889488904889148892488934889448895488964889748898488994890048901489024890348904489054890648907489084890948910489114891248913489144891548916489174891848919489204892148922489234892448925489264892748928489294893048931489324893348934489354893648937489384893948940489414894248943489444894548946489474894848949489504895148952489534895448955489564895748958489594896048961489624896348964489654896648967489684896948970489714897248973489744897548976489774897848979489804898148982489834898448985489864898748988489894899048991489924899348994489954899648997489984899949000490014900249003490044900549006490074900849009490104901149012490134901449015490164901749018490194902049021490224902349024490254902649027490284902949030490314903249033490344903549036490374903849039490404904149042490434904449045490464904749048490494905049051490524905349054490554905649057490584905949060490614906249063490644906549066490674906849069490704907149072490734907449075490764907749078490794908049081490824908349084490854908649087490884908949090490914909249093490944909549096490974909849099491004910149102491034910449105491064910749108491094911049111491124911349114491154911649117491184911949120491214912249123491244912549126491274912849129491304913149132491334913449135491364913749138491394914049141491424914349144491454914649147491484914949150491514915249153491544915549156491574915849159491604916149162491634916449165491664916749168491694917049171491724917349174491754917649177491784917949180491814918249183491844918549186491874918849189491904919149192491934919449195491964919749198491994920049201492024920349204492054920649207492084920949210492114921249213492144921549216492174921849219492204922149222492234922449225492264922749228492294923049231492324923349234492354923649237492384923949240492414924249243492444924549246492474924849249492504925149252492534925449255492564925749258492594926049261492624926349264492654926649267492684926949270492714927249273492744927549276492774927849279492804928149282492834928449285492864928749288492894929049291492924929349294492954929649297492984929949300493014930249303493044930549306493074930849309493104931149312493134931449315493164931749318493194932049321493224932349324493254932649327493284932949330493314933249333493344933549336493374933849339493404934149342493434934449345493464934749348493494935049351493524935349354493554935649357493584935949360493614936249363493644936549366493674936849369493704937149372493734937449375493764937749378493794938049381493824938349384493854938649387493884938949390493914939249393493944939549396493974939849399494004940149402494034940449405494064940749408494094941049411494124941349414494154941649417494184941949420494214942249423494244942549426494274942849429494304943149432494334943449435494364943749438494394944049441494424944349444494454944649447494484944949450494514945249453494544945549456494574945849459494604946149462494634946449465494664946749468494694947049471494724947349474494754947649477494784947949480494814948249483494844948549486494874948849489494904949149492494934949449495494964949749498494994950049501495024950349504495054950649507495084950949510495114951249513495144951549516495174951849519495204952149522495234952449525495264952749528495294953049531495324953349534495354953649537495384953949540495414954249543495444954549546495474954849549495504955149552495534955449555495564955749558495594956049561495624956349564495654956649567495684956949570495714957249573495744957549576495774957849579495804958149582495834958449585495864958749588495894959049591495924959349594495954959649597495984959949600496014960249603496044960549606496074960849609496104961149612496134961449615496164961749618496194962049621496224962349624496254962649627496284962949630496314963249633496344963549636496374963849639496404964149642496434964449645496464964749648496494965049651496524965349654496554965649657496584965949660496614966249663496644966549666496674966849669496704967149672496734967449675496764967749678496794968049681496824968349684496854968649687496884968949690496914969249693496944969549696496974969849699497004970149702497034970449705497064970749708497094971049711497124971349714497154971649717497184971949720497214972249723497244972549726497274972849729497304973149732497334973449735497364973749738497394974049741497424974349744497454974649747497484974949750497514975249753497544975549756497574975849759497604976149762497634976449765497664976749768497694977049771497724977349774497754977649777497784977949780497814978249783497844978549786497874978849789497904979149792497934979449795497964979749798497994980049801498024980349804498054980649807498084980949810498114981249813498144981549816498174981849819498204982149822498234982449825498264982749828498294983049831498324983349834498354983649837498384983949840498414984249843498444984549846498474984849849498504985149852498534985449855498564985749858498594986049861498624986349864498654986649867498684986949870498714987249873498744987549876498774987849879498804988149882498834988449885498864988749888498894989049891498924989349894498954989649897498984989949900499014990249903499044990549906499074990849909499104991149912499134991449915499164991749918499194992049921499224992349924499254992649927499284992949930499314993249933499344993549936499374993849939499404994149942499434994449945499464994749948499494995049951499524995349954499554995649957499584995949960499614996249963499644996549966499674996849969499704997149972499734997449975499764997749978499794998049981499824998349984499854998649987499884998949990499914999249993499944999549996499974999849999500005000150002500035000450005500065000750008500095001050011500125001350014500155001650017500185001950020500215002250023500245002550026500275002850029500305003150032500335003450035500365003750038500395004050041500425004350044500455004650047500485004950050500515005250053500545005550056500575005850059500605006150062500635006450065500665006750068500695007050071500725007350074500755007650077500785007950080500815008250083500845008550086500875008850089500905009150092500935009450095500965009750098500995010050101501025010350104501055010650107501085010950110501115011250113501145011550116501175011850119501205012150122501235012450125501265012750128501295013050131501325013350134501355013650137501385013950140501415014250143501445014550146501475014850149501505015150152501535015450155501565015750158501595016050161501625016350164501655016650167501685016950170501715017250173501745017550176501775017850179501805018150182501835018450185501865018750188501895019050191501925019350194501955019650197501985019950200502015020250203502045020550206502075020850209502105021150212502135021450215502165021750218502195022050221502225022350224502255022650227502285022950230502315023250233502345023550236502375023850239502405024150242502435024450245502465024750248502495025050251502525025350254502555025650257502585025950260502615026250263502645026550266502675026850269502705027150272502735027450275502765027750278502795028050281502825028350284502855028650287502885028950290502915029250293502945029550296502975029850299503005030150302503035030450305503065030750308503095031050311503125031350314503155031650317503185031950320503215032250323503245032550326503275032850329503305033150332503335033450335503365033750338503395034050341503425034350344503455034650347503485034950350503515035250353503545035550356503575035850359503605036150362503635036450365503665036750368503695037050371503725037350374503755037650377503785037950380503815038250383503845038550386503875038850389503905039150392503935039450395503965039750398503995040050401504025040350404504055040650407504085040950410504115041250413504145041550416504175041850419504205042150422504235042450425504265042750428504295043050431504325043350434504355043650437504385043950440504415044250443504445044550446504475044850449504505045150452504535045450455504565045750458504595046050461504625046350464504655046650467504685046950470504715047250473504745047550476504775047850479504805048150482504835048450485504865048750488504895049050491504925049350494504955049650497504985049950500505015050250503505045050550506505075050850509505105051150512505135051450515505165051750518505195052050521505225052350524505255052650527505285052950530505315053250533505345053550536505375053850539505405054150542505435054450545505465054750548505495055050551505525055350554505555055650557505585055950560505615056250563505645056550566505675056850569505705057150572505735057450575505765057750578505795058050581505825058350584505855058650587505885058950590505915059250593505945059550596505975059850599506005060150602506035060450605506065060750608506095061050611506125061350614506155061650617506185061950620506215062250623506245062550626506275062850629506305063150632506335063450635506365063750638506395064050641506425064350644506455064650647506485064950650506515065250653506545065550656506575065850659506605066150662506635066450665506665066750668506695067050671506725067350674506755067650677506785067950680506815068250683506845068550686506875068850689506905069150692506935069450695506965069750698506995070050701507025070350704507055070650707507085070950710507115071250713507145071550716507175071850719507205072150722507235072450725507265072750728507295073050731507325073350734507355073650737507385073950740507415074250743507445074550746507475074850749507505075150752507535075450755507565075750758507595076050761507625076350764507655076650767507685076950770507715077250773507745077550776507775077850779507805078150782507835078450785507865078750788507895079050791507925079350794507955079650797507985079950800508015080250803508045080550806508075080850809508105081150812508135081450815508165081750818508195082050821508225082350824508255082650827508285082950830508315083250833508345083550836508375083850839508405084150842508435084450845508465084750848508495085050851508525085350854508555085650857508585085950860508615086250863508645086550866508675086850869508705087150872508735087450875508765087750878508795088050881508825088350884508855088650887508885088950890508915089250893508945089550896508975089850899509005090150902509035090450905509065090750908509095091050911509125091350914509155091650917509185091950920509215092250923509245092550926509275092850929509305093150932509335093450935509365093750938509395094050941509425094350944509455094650947509485094950950509515095250953509545095550956509575095850959509605096150962509635096450965509665096750968509695097050971509725097350974509755097650977509785097950980509815098250983509845098550986509875098850989509905099150992509935099450995509965099750998509995100051001510025100351004510055100651007510085100951010510115101251013510145101551016510175101851019510205102151022510235102451025510265102751028510295103051031510325103351034510355103651037510385103951040510415104251043510445104551046510475104851049510505105151052510535105451055510565105751058510595106051061510625106351064510655106651067510685106951070510715107251073510745107551076510775107851079510805108151082510835108451085510865108751088510895109051091510925109351094510955109651097510985109951100511015110251103511045110551106511075110851109511105111151112511135111451115511165111751118511195112051121511225112351124511255112651127511285112951130511315113251133511345113551136511375113851139511405114151142511435114451145511465114751148511495115051151511525115351154511555115651157511585115951160511615116251163511645116551166511675116851169511705117151172511735117451175511765117751178511795118051181511825118351184511855118651187511885118951190511915119251193511945119551196511975119851199512005120151202512035120451205512065120751208512095121051211512125121351214512155121651217512185121951220512215122251223512245122551226512275122851229512305123151232512335123451235512365123751238512395124051241512425124351244512455124651247512485124951250512515125251253512545125551256512575125851259512605126151262512635126451265512665126751268512695127051271512725127351274512755127651277512785127951280512815128251283512845128551286512875128851289512905129151292512935129451295512965129751298512995130051301513025130351304513055130651307513085130951310513115131251313513145131551316513175131851319513205132151322513235132451325513265132751328513295133051331513325133351334513355133651337513385133951340513415134251343513445134551346513475134851349513505135151352513535135451355513565135751358513595136051361513625136351364513655136651367513685136951370513715137251373513745137551376513775137851379513805138151382513835138451385513865138751388513895139051391513925139351394513955139651397513985139951400514015140251403514045140551406514075140851409514105141151412514135141451415514165141751418514195142051421514225142351424514255142651427514285142951430514315143251433514345143551436514375143851439514405144151442514435144451445514465144751448514495145051451514525145351454514555145651457514585145951460514615146251463514645146551466514675146851469514705147151472514735147451475514765147751478514795148051481514825148351484514855148651487514885148951490514915149251493514945149551496514975149851499515005150151502515035150451505515065150751508515095151051511515125151351514515155151651517515185151951520515215152251523515245152551526515275152851529515305153151532515335153451535515365153751538515395154051541515425154351544515455154651547515485154951550515515155251553515545155551556515575155851559515605156151562515635156451565515665156751568515695157051571515725157351574515755157651577515785157951580515815158251583515845158551586515875158851589515905159151592515935159451595515965159751598515995160051601516025160351604516055160651607516085160951610516115161251613516145161551616516175161851619516205162151622516235162451625516265162751628516295163051631516325163351634516355163651637516385163951640516415164251643516445164551646516475164851649516505165151652516535165451655516565165751658516595166051661516625166351664516655166651667516685166951670516715167251673516745167551676516775167851679516805168151682516835168451685516865168751688516895169051691516925169351694516955169651697516985169951700517015170251703517045170551706517075170851709517105171151712517135171451715517165171751718517195172051721517225172351724517255172651727517285172951730517315173251733517345173551736517375173851739517405174151742517435174451745517465174751748517495175051751517525175351754517555175651757517585175951760517615176251763517645176551766517675176851769517705177151772517735177451775517765177751778517795178051781517825178351784517855178651787517885178951790517915179251793517945179551796517975179851799518005180151802518035180451805518065180751808518095181051811518125181351814518155181651817518185181951820518215182251823518245182551826518275182851829518305183151832518335183451835518365183751838518395184051841518425184351844518455184651847518485184951850518515185251853518545185551856518575185851859518605186151862518635186451865518665186751868518695187051871518725187351874518755187651877518785187951880518815188251883518845188551886518875188851889518905189151892518935189451895518965189751898518995190051901519025190351904519055190651907519085190951910519115191251913519145191551916519175191851919519205192151922519235192451925519265192751928519295193051931519325193351934519355193651937519385193951940519415194251943519445194551946519475194851949519505195151952519535195451955519565195751958519595196051961519625196351964519655196651967519685196951970519715197251973519745197551976519775197851979519805198151982519835198451985519865198751988519895199051991519925199351994519955199651997519985199952000520015200252003520045200552006520075200852009520105201152012520135201452015520165201752018520195202052021520225202352024520255202652027520285202952030520315203252033520345203552036520375203852039520405204152042520435204452045520465204752048520495205052051520525205352054520555205652057520585205952060520615206252063520645206552066520675206852069520705207152072520735207452075520765207752078520795208052081520825208352084520855208652087520885208952090520915209252093520945209552096520975209852099521005210152102521035210452105521065210752108521095211052111521125211352114521155211652117521185211952120521215212252123521245212552126521275212852129521305213152132521335213452135521365213752138521395214052141521425214352144521455214652147521485214952150521515215252153521545215552156521575215852159521605216152162521635216452165521665216752168521695217052171521725217352174521755217652177521785217952180521815218252183521845218552186521875218852189521905219152192521935219452195521965219752198521995220052201522025220352204522055220652207522085220952210522115221252213522145221552216522175221852219522205222152222522235222452225522265222752228522295223052231522325223352234522355223652237522385223952240522415224252243522445224552246522475224852249522505225152252522535225452255522565225752258522595226052261522625226352264522655226652267522685226952270522715227252273522745227552276522775227852279522805228152282522835228452285522865228752288522895229052291522925229352294522955229652297522985229952300523015230252303523045230552306523075230852309523105231152312523135231452315523165231752318523195232052321523225232352324523255232652327523285232952330523315233252333523345233552336523375233852339523405234152342523435234452345523465234752348523495235052351523525235352354523555235652357523585235952360523615236252363523645236552366523675236852369523705237152372523735237452375523765237752378523795238052381523825238352384523855238652387523885238952390523915239252393523945239552396523975239852399524005240152402524035240452405524065240752408524095241052411524125241352414524155241652417524185241952420524215242252423524245242552426524275242852429524305243152432524335243452435524365243752438524395244052441524425244352444524455244652447524485244952450524515245252453524545245552456524575245852459524605246152462524635246452465524665246752468524695247052471524725247352474524755247652477524785247952480524815248252483524845248552486524875248852489524905249152492524935249452495524965249752498524995250052501525025250352504525055250652507525085250952510525115251252513525145251552516525175251852519525205252152522525235252452525525265252752528525295253052531525325253352534525355253652537525385253952540525415254252543525445254552546525475254852549525505255152552525535255452555525565255752558525595256052561525625256352564525655256652567525685256952570525715257252573525745257552576525775257852579525805258152582525835258452585525865258752588525895259052591525925259352594525955259652597525985259952600526015260252603526045260552606526075260852609526105261152612526135261452615526165261752618526195262052621526225262352624526255262652627526285262952630526315263252633526345263552636526375263852639526405264152642526435264452645526465264752648526495265052651526525265352654526555265652657526585265952660526615266252663526645266552666526675266852669526705267152672526735267452675526765267752678526795268052681526825268352684526855268652687526885268952690526915269252693526945269552696526975269852699527005270152702527035270452705527065270752708527095271052711527125271352714527155271652717527185271952720527215272252723527245272552726527275272852729527305273152732527335273452735527365273752738527395274052741527425274352744527455274652747527485274952750527515275252753527545275552756527575275852759527605276152762527635276452765527665276752768527695277052771527725277352774527755277652777527785277952780527815278252783527845278552786527875278852789527905279152792527935279452795527965279752798527995280052801528025280352804528055280652807528085280952810528115281252813528145281552816528175281852819528205282152822528235282452825528265282752828528295283052831528325283352834528355283652837528385283952840528415284252843528445284552846528475284852849528505285152852528535285452855528565285752858528595286052861528625286352864528655286652867528685286952870528715287252873528745287552876528775287852879528805288152882528835288452885528865288752888528895289052891528925289352894528955289652897528985289952900529015290252903529045290552906529075290852909529105291152912529135291452915529165291752918529195292052921529225292352924529255292652927529285292952930529315293252933529345293552936529375293852939529405294152942529435294452945529465294752948529495295052951529525295352954529555295652957529585295952960529615296252963529645296552966529675296852969529705297152972529735297452975529765297752978529795298052981529825298352984529855298652987529885298952990529915299252993529945299552996529975299852999530005300153002530035300453005530065300753008530095301053011530125301353014530155301653017530185301953020530215302253023530245302553026530275302853029530305303153032530335303453035530365303753038530395304053041530425304353044530455304653047530485304953050530515305253053530545305553056530575305853059530605306153062530635306453065530665306753068530695307053071530725307353074530755307653077530785307953080530815308253083530845308553086530875308853089530905309153092530935309453095530965309753098530995310053101531025310353104531055310653107531085310953110531115311253113531145311553116531175311853119531205312153122531235312453125531265312753128531295313053131531325313353134531355313653137531385313953140531415314253143531445314553146531475314853149531505315153152531535315453155531565315753158531595316053161531625316353164531655316653167531685316953170531715317253173531745317553176531775317853179531805318153182531835318453185531865318753188531895319053191531925319353194531955319653197531985319953200532015320253203532045320553206532075320853209532105321153212532135321453215532165321753218532195322053221532225322353224532255322653227532285322953230532315323253233532345323553236532375323853239532405324153242532435324453245532465324753248532495325053251532525325353254532555325653257532585325953260532615326253263532645326553266532675326853269532705327153272532735327453275532765327753278532795328053281532825328353284532855328653287532885328953290532915329253293532945329553296532975329853299533005330153302533035330453305533065330753308533095331053311533125331353314533155331653317533185331953320533215332253323533245332553326533275332853329533305333153332533335333453335533365333753338533395334053341533425334353344533455334653347533485334953350533515335253353533545335553356533575335853359533605336153362533635336453365533665336753368533695337053371533725337353374533755337653377533785337953380533815338253383533845338553386533875338853389533905339153392533935339453395533965339753398533995340053401534025340353404534055340653407534085340953410534115341253413534145341553416534175341853419534205342153422534235342453425534265342753428534295343053431534325343353434534355343653437534385343953440534415344253443534445344553446534475344853449534505345153452534535345453455534565345753458534595346053461534625346353464534655346653467534685346953470534715347253473534745347553476534775347853479534805348153482534835348453485534865348753488534895349053491534925349353494534955349653497534985349953500535015350253503535045350553506535075350853509535105351153512535135351453515535165351753518535195352053521535225352353524535255352653527535285352953530535315353253533535345353553536535375353853539535405354153542535435354453545535465354753548535495355053551535525355353554535555355653557535585355953560535615356253563535645356553566535675356853569535705357153572535735357453575535765357753578535795358053581535825358353584535855358653587535885358953590535915359253593535945359553596535975359853599536005360153602536035360453605536065360753608536095361053611536125361353614536155361653617536185361953620536215362253623536245362553626536275362853629536305363153632536335363453635536365363753638536395364053641536425364353644536455364653647536485364953650536515365253653536545365553656536575365853659536605366153662536635366453665536665366753668536695367053671536725367353674536755367653677536785367953680536815368253683536845368553686536875368853689536905369153692536935369453695536965369753698536995370053701537025370353704537055370653707537085370953710537115371253713537145371553716537175371853719537205372153722537235372453725537265372753728537295373053731537325373353734537355373653737537385373953740537415374253743537445374553746537475374853749537505375153752537535375453755537565375753758537595376053761537625376353764537655376653767537685376953770537715377253773537745377553776537775377853779537805378153782537835378453785537865378753788537895379053791537925379353794537955379653797537985379953800538015380253803538045380553806538075380853809538105381153812538135381453815538165381753818538195382053821538225382353824538255382653827538285382953830538315383253833538345383553836538375383853839538405384153842538435384453845538465384753848538495385053851538525385353854538555385653857538585385953860538615386253863538645386553866538675386853869538705387153872538735387453875538765387753878538795388053881538825388353884538855388653887538885388953890538915389253893538945389553896538975389853899539005390153902539035390453905539065390753908539095391053911539125391353914539155391653917539185391953920539215392253923539245392553926539275392853929539305393153932539335393453935539365393753938539395394053941539425394353944539455394653947539485394953950539515395253953539545395553956539575395853959539605396153962539635396453965539665396753968539695397053971539725397353974539755397653977539785397953980539815398253983539845398553986539875398853989539905399153992539935399453995539965399753998539995400054001540025400354004540055400654007540085400954010540115401254013540145401554016540175401854019540205402154022540235402454025540265402754028540295403054031540325403354034540355403654037540385403954040540415404254043540445404554046540475404854049540505405154052540535405454055540565405754058540595406054061540625406354064540655406654067540685406954070540715407254073540745407554076540775407854079540805408154082540835408454085540865408754088540895409054091540925409354094540955409654097540985409954100541015410254103541045410554106541075410854109541105411154112541135411454115541165411754118541195412054121541225412354124541255412654127541285412954130541315413254133541345413554136541375413854139541405414154142541435414454145541465414754148541495415054151541525415354154541555415654157541585415954160541615416254163541645416554166541675416854169541705417154172541735417454175541765417754178541795418054181541825418354184541855418654187541885418954190541915419254193541945419554196541975419854199542005420154202542035420454205542065420754208542095421054211542125421354214542155421654217542185421954220542215422254223542245422554226542275422854229542305423154232542335423454235542365423754238542395424054241542425424354244542455424654247542485424954250542515425254253542545425554256542575425854259542605426154262542635426454265542665426754268542695427054271542725427354274542755427654277542785427954280542815428254283542845428554286542875428854289542905429154292542935429454295542965429754298542995430054301543025430354304543055430654307543085430954310543115431254313543145431554316543175431854319543205432154322543235432454325543265432754328543295433054331543325433354334543355433654337543385433954340543415434254343543445434554346543475434854349543505435154352543535435454355543565435754358543595436054361543625436354364543655436654367543685436954370543715437254373543745437554376543775437854379543805438154382543835438454385543865438754388543895439054391543925439354394543955439654397543985439954400544015440254403544045440554406544075440854409544105441154412544135441454415544165441754418544195442054421544225442354424544255442654427544285442954430544315443254433544345443554436544375443854439544405444154442544435444454445544465444754448544495445054451544525445354454544555445654457544585445954460544615446254463544645446554466544675446854469544705447154472544735447454475544765447754478544795448054481544825448354484544855448654487544885448954490544915449254493544945449554496544975449854499545005450154502545035450454505545065450754508545095451054511545125451354514545155451654517545185451954520545215452254523545245452554526545275452854529545305453154532545335453454535545365453754538545395454054541545425454354544545455454654547545485454954550545515455254553545545455554556545575455854559545605456154562545635456454565545665456754568545695457054571545725457354574545755457654577545785457954580545815458254583545845458554586545875458854589545905459154592545935459454595545965459754598545995460054601546025460354604546055460654607546085460954610546115461254613546145461554616546175461854619546205462154622546235462454625546265462754628546295463054631546325463354634546355463654637546385463954640546415464254643546445464554646546475464854649546505465154652546535465454655546565465754658546595466054661546625466354664546655466654667546685466954670546715467254673546745467554676546775467854679546805468154682546835468454685546865468754688546895469054691546925469354694546955469654697546985469954700547015470254703547045470554706547075470854709547105471154712547135471454715547165471754718547195472054721547225472354724547255472654727547285472954730547315473254733547345473554736547375473854739547405474154742547435474454745547465474754748547495475054751547525475354754547555475654757547585475954760547615476254763547645476554766547675476854769547705477154772547735477454775547765477754778547795478054781547825478354784547855478654787547885478954790547915479254793547945479554796547975479854799548005480154802548035480454805548065480754808548095481054811548125481354814548155481654817548185481954820548215482254823548245482554826548275482854829548305483154832548335483454835548365483754838548395484054841548425484354844548455484654847548485484954850548515485254853548545485554856548575485854859548605486154862548635486454865548665486754868548695487054871548725487354874548755487654877548785487954880548815488254883548845488554886548875488854889548905489154892548935489454895548965489754898548995490054901549025490354904549055490654907549085490954910549115491254913549145491554916549175491854919549205492154922549235492454925549265492754928549295493054931549325493354934549355493654937549385493954940549415494254943549445494554946549475494854949549505495154952549535495454955549565495754958549595496054961549625496354964549655496654967549685496954970549715497254973549745497554976549775497854979549805498154982549835498454985549865498754988549895499054991549925499354994549955499654997549985499955000550015500255003550045500555006550075500855009550105501155012550135501455015550165501755018550195502055021550225502355024550255502655027550285502955030550315503255033550345503555036550375503855039550405504155042550435504455045550465504755048550495505055051550525505355054550555505655057550585505955060550615506255063550645506555066550675506855069550705507155072550735507455075550765507755078550795508055081550825508355084550855508655087550885508955090550915509255093550945509555096550975509855099551005510155102551035510455105551065510755108551095511055111551125511355114551155511655117551185511955120551215512255123551245512555126551275512855129551305513155132551335513455135551365513755138551395514055141551425514355144551455514655147551485514955150551515515255153551545515555156551575515855159551605516155162551635516455165551665516755168551695517055171551725517355174551755517655177551785517955180551815518255183551845518555186551875518855189551905519155192551935519455195551965519755198551995520055201552025520355204552055520655207552085520955210552115521255213552145521555216552175521855219552205522155222552235522455225552265522755228552295523055231552325523355234552355523655237552385523955240552415524255243552445524555246552475524855249552505525155252552535525455255552565525755258552595526055261552625526355264552655526655267552685526955270552715527255273552745527555276552775527855279552805528155282552835528455285552865528755288552895529055291552925529355294552955529655297552985529955300553015530255303553045530555306553075530855309553105531155312553135531455315553165531755318553195532055321553225532355324553255532655327553285532955330553315533255333553345533555336553375533855339553405534155342553435534455345553465534755348553495535055351553525535355354553555535655357553585535955360553615536255363553645536555366553675536855369553705537155372553735537455375553765537755378553795538055381553825538355384553855538655387553885538955390553915539255393553945539555396553975539855399554005540155402554035540455405554065540755408554095541055411554125541355414554155541655417554185541955420554215542255423554245542555426554275542855429554305543155432554335543455435554365543755438554395544055441554425544355444554455544655447554485544955450554515545255453554545545555456554575545855459554605546155462554635546455465554665546755468554695547055471554725547355474554755547655477554785547955480554815548255483554845548555486554875548855489554905549155492554935549455495554965549755498554995550055501555025550355504555055550655507555085550955510555115551255513555145551555516555175551855519555205552155522555235552455525555265552755528555295553055531555325553355534555355553655537555385553955540555415554255543555445554555546555475554855549555505555155552555535555455555555565555755558555595556055561555625556355564555655556655567555685556955570555715557255573555745557555576555775557855579555805558155582555835558455585555865558755588555895559055591555925559355594555955559655597555985559955600556015560255603556045560555606556075560855609556105561155612556135561455615556165561755618556195562055621556225562355624556255562655627556285562955630556315563255633556345563555636556375563855639556405564155642556435564455645556465564755648556495565055651556525565355654556555565655657556585565955660556615566255663556645566555666556675566855669556705567155672556735567455675556765567755678556795568055681556825568355684556855568655687556885568955690556915569255693556945569555696556975569855699557005570155702557035570455705557065570755708557095571055711557125571355714557155571655717557185571955720557215572255723557245572555726557275572855729557305573155732557335573455735557365573755738557395574055741557425574355744557455574655747557485574955750557515575255753557545575555756557575575855759557605576155762557635576455765557665576755768557695577055771557725577355774557755577655777557785577955780557815578255783557845578555786557875578855789557905579155792557935579455795557965579755798557995580055801558025580355804558055580655807558085580955810558115581255813558145581555816558175581855819558205582155822558235582455825558265582755828558295583055831558325583355834558355583655837558385583955840558415584255843558445584555846558475584855849558505585155852558535585455855558565585755858558595586055861558625586355864558655586655867558685586955870558715587255873558745587555876558775587855879558805588155882558835588455885558865588755888558895589055891558925589355894558955589655897558985589955900559015590255903559045590555906559075590855909559105591155912559135591455915559165591755918559195592055921559225592355924559255592655927559285592955930559315593255933559345593555936559375593855939559405594155942559435594455945559465594755948559495595055951559525595355954559555595655957559585595955960559615596255963559645596555966559675596855969559705597155972559735597455975559765597755978559795598055981559825598355984559855598655987559885598955990559915599255993559945599555996559975599855999560005600156002560035600456005560065600756008560095601056011560125601356014560155601656017560185601956020560215602256023560245602556026560275602856029560305603156032560335603456035560365603756038560395604056041560425604356044560455604656047560485604956050560515605256053560545605556056560575605856059560605606156062560635606456065560665606756068560695607056071560725607356074560755607656077560785607956080560815608256083560845608556086560875608856089560905609156092560935609456095560965609756098560995610056101561025610356104561055610656107561085610956110561115611256113561145611556116561175611856119561205612156122561235612456125561265612756128561295613056131561325613356134561355613656137561385613956140561415614256143561445614556146561475614856149561505615156152561535615456155561565615756158561595616056161561625616356164561655616656167561685616956170561715617256173561745617556176561775617856179561805618156182561835618456185561865618756188561895619056191561925619356194561955619656197561985619956200562015620256203562045620556206562075620856209562105621156212562135621456215562165621756218562195622056221562225622356224562255622656227562285622956230562315623256233562345623556236562375623856239562405624156242562435624456245562465624756248562495625056251562525625356254562555625656257562585625956260562615626256263562645626556266562675626856269562705627156272562735627456275562765627756278562795628056281562825628356284562855628656287562885628956290562915629256293562945629556296562975629856299563005630156302563035630456305563065630756308563095631056311563125631356314563155631656317563185631956320563215632256323563245632556326563275632856329563305633156332563335633456335563365633756338563395634056341563425634356344563455634656347563485634956350563515635256353563545635556356563575635856359563605636156362563635636456365563665636756368563695637056371563725637356374563755637656377563785637956380563815638256383563845638556386563875638856389563905639156392563935639456395563965639756398563995640056401564025640356404564055640656407564085640956410564115641256413564145641556416564175641856419564205642156422564235642456425564265642756428564295643056431564325643356434564355643656437564385643956440564415644256443564445644556446564475644856449564505645156452564535645456455564565645756458564595646056461564625646356464564655646656467564685646956470564715647256473564745647556476564775647856479564805648156482564835648456485564865648756488564895649056491564925649356494564955649656497564985649956500565015650256503565045650556506565075650856509565105651156512565135651456515565165651756518565195652056521565225652356524565255652656527565285652956530565315653256533565345653556536565375653856539565405654156542565435654456545565465654756548565495655056551565525655356554565555655656557565585655956560565615656256563565645656556566565675656856569565705657156572565735657456575565765657756578565795658056581565825658356584565855658656587565885658956590565915659256593565945659556596565975659856599566005660156602566035660456605566065660756608566095661056611566125661356614566155661656617566185661956620566215662256623566245662556626566275662856629566305663156632566335663456635566365663756638566395664056641566425664356644566455664656647566485664956650566515665256653566545665556656566575665856659566605666156662566635666456665566665666756668566695667056671566725667356674566755667656677566785667956680566815668256683566845668556686566875668856689566905669156692566935669456695566965669756698566995670056701567025670356704567055670656707567085670956710567115671256713567145671556716567175671856719567205672156722567235672456725567265672756728567295673056731567325673356734567355673656737567385673956740567415674256743567445674556746567475674856749567505675156752567535675456755567565675756758567595676056761567625676356764567655676656767567685676956770567715677256773567745677556776567775677856779567805678156782567835678456785567865678756788567895679056791567925679356794567955679656797567985679956800568015680256803568045680556806568075680856809568105681156812568135681456815568165681756818568195682056821568225682356824568255682656827568285682956830568315683256833568345683556836568375683856839568405684156842568435684456845568465684756848568495685056851568525685356854568555685656857568585685956860568615686256863568645686556866568675686856869568705687156872568735687456875568765687756878568795688056881568825688356884568855688656887568885688956890568915689256893568945689556896568975689856899569005690156902569035690456905569065690756908569095691056911569125691356914569155691656917569185691956920569215692256923569245692556926569275692856929569305693156932569335693456935569365693756938569395694056941569425694356944569455694656947569485694956950569515695256953569545695556956569575695856959569605696156962569635696456965569665696756968569695697056971569725697356974569755697656977569785697956980569815698256983569845698556986569875698856989569905699156992569935699456995569965699756998569995700057001570025700357004570055700657007570085700957010570115701257013570145701557016570175701857019570205702157022570235702457025570265702757028570295703057031570325703357034570355703657037570385703957040570415704257043570445704557046570475704857049570505705157052570535705457055570565705757058570595706057061570625706357064570655706657067570685706957070570715707257073570745707557076570775707857079570805708157082570835708457085570865708757088570895709057091570925709357094570955709657097570985709957100571015710257103571045710557106571075710857109571105711157112571135711457115571165711757118571195712057121571225712357124571255712657127571285712957130571315713257133571345713557136571375713857139571405714157142571435714457145571465714757148571495715057151571525715357154571555715657157571585715957160571615716257163571645716557166571675716857169571705717157172571735717457175571765717757178571795718057181571825718357184571855718657187571885718957190571915719257193571945719557196571975719857199572005720157202572035720457205572065720757208572095721057211572125721357214572155721657217572185721957220572215722257223572245722557226572275722857229572305723157232572335723457235572365723757238572395724057241572425724357244572455724657247572485724957250572515725257253572545725557256572575725857259572605726157262572635726457265572665726757268572695727057271572725727357274572755727657277572785727957280572815728257283572845728557286572875728857289572905729157292572935729457295572965729757298572995730057301573025730357304573055730657307573085730957310573115731257313573145731557316573175731857319573205732157322573235732457325573265732757328573295733057331573325733357334573355733657337573385733957340573415734257343573445734557346573475734857349573505735157352573535735457355573565735757358573595736057361573625736357364573655736657367573685736957370573715737257373573745737557376573775737857379573805738157382573835738457385573865738757388573895739057391573925739357394573955739657397573985739957400574015740257403574045740557406574075740857409574105741157412574135741457415574165741757418574195742057421574225742357424574255742657427574285742957430574315743257433574345743557436574375743857439574405744157442574435744457445574465744757448574495745057451574525745357454574555745657457574585745957460574615746257463574645746557466574675746857469574705747157472574735747457475574765747757478574795748057481574825748357484574855748657487574885748957490574915749257493574945749557496574975749857499575005750157502575035750457505575065750757508575095751057511575125751357514575155751657517575185751957520575215752257523575245752557526575275752857529575305753157532575335753457535575365753757538575395754057541575425754357544575455754657547575485754957550575515755257553575545755557556575575755857559575605756157562575635756457565575665756757568575695757057571575725757357574575755757657577575785757957580575815758257583575845758557586575875758857589575905759157592575935759457595575965759757598575995760057601576025760357604576055760657607576085760957610576115761257613576145761557616576175761857619576205762157622576235762457625576265762757628576295763057631576325763357634576355763657637576385763957640576415764257643576445764557646576475764857649576505765157652576535765457655576565765757658576595766057661576625766357664576655766657667576685766957670576715767257673576745767557676576775767857679576805768157682576835768457685576865768757688576895769057691576925769357694576955769657697576985769957700577015770257703577045770557706577075770857709577105771157712577135771457715577165771757718577195772057721577225772357724577255772657727577285772957730577315773257733577345773557736577375773857739577405774157742577435774457745577465774757748577495775057751577525775357754577555775657757577585775957760577615776257763577645776557766577675776857769577705777157772577735777457775577765777757778577795778057781577825778357784577855778657787577885778957790577915779257793577945779557796577975779857799578005780157802578035780457805578065780757808578095781057811578125781357814578155781657817578185781957820578215782257823578245782557826578275782857829578305783157832578335783457835578365783757838578395784057841578425784357844578455784657847578485784957850578515785257853578545785557856578575785857859578605786157862578635786457865578665786757868578695787057871578725787357874578755787657877578785787957880578815788257883578845788557886578875788857889578905789157892578935789457895578965789757898578995790057901579025790357904579055790657907579085790957910579115791257913579145791557916579175791857919579205792157922579235792457925579265792757928579295793057931579325793357934579355793657937579385793957940579415794257943579445794557946579475794857949579505795157952579535795457955579565795757958579595796057961579625796357964579655796657967579685796957970579715797257973579745797557976579775797857979579805798157982579835798457985579865798757988579895799057991579925799357994579955799657997579985799958000580015800258003580045800558006580075800858009580105801158012580135801458015580165801758018580195802058021580225802358024580255802658027580285802958030580315803258033580345803558036580375803858039580405804158042580435804458045580465804758048580495805058051580525805358054580555805658057580585805958060580615806258063580645806558066580675806858069580705807158072580735807458075580765807758078580795808058081580825808358084580855808658087580885808958090580915809258093580945809558096580975809858099581005810158102581035810458105581065810758108581095811058111581125811358114581155811658117581185811958120581215812258123581245812558126581275812858129581305813158132581335813458135581365813758138581395814058141581425814358144581455814658147581485814958150581515815258153581545815558156581575815858159581605816158162581635816458165581665816758168581695817058171581725817358174581755817658177581785817958180581815818258183581845818558186581875818858189581905819158192581935819458195581965819758198581995820058201582025820358204582055820658207582085820958210582115821258213582145821558216582175821858219582205822158222582235822458225582265822758228582295823058231582325823358234582355823658237582385823958240582415824258243582445824558246582475824858249582505825158252582535825458255582565825758258582595826058261582625826358264582655826658267582685826958270582715827258273582745827558276582775827858279582805828158282582835828458285582865828758288582895829058291582925829358294582955829658297582985829958300583015830258303583045830558306583075830858309583105831158312583135831458315583165831758318583195832058321583225832358324583255832658327583285832958330583315833258333583345833558336583375833858339583405834158342583435834458345583465834758348583495835058351583525835358354583555835658357583585835958360583615836258363583645836558366583675836858369583705837158372583735837458375583765837758378583795838058381583825838358384583855838658387583885838958390583915839258393583945839558396583975839858399584005840158402584035840458405584065840758408584095841058411584125841358414584155841658417584185841958420584215842258423584245842558426584275842858429584305843158432584335843458435584365843758438584395844058441584425844358444584455844658447584485844958450584515845258453584545845558456584575845858459584605846158462584635846458465584665846758468584695847058471584725847358474584755847658477584785847958480584815848258483584845848558486584875848858489584905849158492584935849458495584965849758498584995850058501585025850358504585055850658507585085850958510585115851258513585145851558516585175851858519585205852158522585235852458525585265852758528585295853058531585325853358534585355853658537585385853958540585415854258543585445854558546585475854858549585505855158552585535855458555585565855758558585595856058561585625856358564585655856658567585685856958570585715857258573585745857558576585775857858579585805858158582585835858458585585865858758588585895859058591585925859358594585955859658597585985859958600586015860258603586045860558606586075860858609586105861158612586135861458615586165861758618586195862058621586225862358624586255862658627586285862958630586315863258633586345863558636586375863858639586405864158642586435864458645586465864758648586495865058651586525865358654586555865658657586585865958660586615866258663586645866558666586675866858669586705867158672586735867458675586765867758678586795868058681586825868358684586855868658687586885868958690586915869258693586945869558696586975869858699587005870158702587035870458705587065870758708587095871058711587125871358714587155871658717587185871958720587215872258723587245872558726587275872858729587305873158732587335873458735587365873758738587395874058741587425874358744587455874658747587485874958750587515875258753587545875558756587575875858759587605876158762587635876458765587665876758768587695877058771587725877358774587755877658777587785877958780587815878258783587845878558786587875878858789587905879158792587935879458795587965879758798587995880058801588025880358804588055880658807588085880958810588115881258813588145881558816588175881858819588205882158822588235882458825588265882758828588295883058831588325883358834588355883658837588385883958840588415884258843588445884558846588475884858849588505885158852588535885458855588565885758858588595886058861588625886358864588655886658867588685886958870588715887258873588745887558876588775887858879588805888158882588835888458885588865888758888588895889058891588925889358894588955889658897588985889958900589015890258903589045890558906589075890858909589105891158912589135891458915589165891758918589195892058921589225892358924589255892658927589285892958930589315893258933589345893558936589375893858939589405894158942589435894458945589465894758948589495895058951589525895358954589555895658957589585895958960589615896258963589645896558966589675896858969589705897158972589735897458975589765897758978589795898058981589825898358984589855898658987589885898958990589915899258993589945899558996589975899858999590005900159002590035900459005590065900759008590095901059011590125901359014590155901659017590185901959020590215902259023590245902559026590275902859029590305903159032590335903459035590365903759038590395904059041590425904359044590455904659047590485904959050590515905259053590545905559056590575905859059590605906159062590635906459065590665906759068590695907059071590725907359074590755907659077590785907959080590815908259083590845908559086590875908859089590905909159092590935909459095590965909759098590995910059101591025910359104591055910659107591085910959110591115911259113591145911559116591175911859119591205912159122591235912459125591265912759128591295913059131591325913359134591355913659137591385913959140591415914259143591445914559146591475914859149591505915159152591535915459155591565915759158591595916059161591625916359164591655916659167591685916959170591715917259173591745917559176591775917859179591805918159182591835918459185591865918759188591895919059191591925919359194591955919659197591985919959200592015920259203592045920559206592075920859209592105921159212592135921459215592165921759218592195922059221592225922359224592255922659227592285922959230592315923259233592345923559236592375923859239592405924159242592435924459245592465924759248592495925059251592525925359254592555925659257592585925959260592615926259263592645926559266592675926859269592705927159272592735927459275592765927759278592795928059281592825928359284592855928659287592885928959290592915929259293592945929559296592975929859299593005930159302593035930459305593065930759308593095931059311593125931359314593155931659317593185931959320593215932259323593245932559326593275932859329593305933159332593335933459335593365933759338593395934059341593425934359344593455934659347593485934959350593515935259353593545935559356593575935859359593605936159362593635936459365593665936759368593695937059371593725937359374593755937659377593785937959380593815938259383593845938559386593875938859389593905939159392593935939459395593965939759398593995940059401594025940359404594055940659407594085940959410594115941259413594145941559416594175941859419594205942159422594235942459425594265942759428594295943059431594325943359434594355943659437594385943959440594415944259443594445944559446594475944859449594505945159452594535945459455594565945759458594595946059461594625946359464594655946659467594685946959470594715947259473594745947559476594775947859479594805948159482594835948459485594865948759488594895949059491594925949359494594955949659497594985949959500595015950259503595045950559506595075950859509595105951159512595135951459515595165951759518595195952059521595225952359524595255952659527595285952959530595315953259533595345953559536595375953859539595405954159542595435954459545595465954759548595495955059551595525955359554595555955659557595585955959560595615956259563595645956559566595675956859569595705957159572595735957459575595765957759578595795958059581595825958359584595855958659587595885958959590595915959259593595945959559596595975959859599596005960159602596035960459605596065960759608596095961059611596125961359614596155961659617596185961959620596215962259623596245962559626596275962859629596305963159632596335963459635596365963759638596395964059641596425964359644596455964659647596485964959650596515965259653596545965559656596575965859659596605966159662596635966459665596665966759668596695967059671596725967359674596755967659677596785967959680596815968259683596845968559686596875968859689596905969159692596935969459695596965969759698596995970059701597025970359704597055970659707597085970959710597115971259713597145971559716597175971859719597205972159722597235972459725597265972759728597295973059731597325973359734597355973659737597385973959740597415974259743597445974559746597475974859749597505975159752597535975459755597565975759758597595976059761597625976359764597655976659767597685976959770597715977259773597745977559776597775977859779597805978159782597835978459785597865978759788597895979059791597925979359794597955979659797597985979959800598015980259803598045980559806598075980859809598105981159812598135981459815598165981759818598195982059821598225982359824598255982659827598285982959830598315983259833598345983559836598375983859839598405984159842598435984459845598465984759848598495985059851598525985359854598555985659857598585985959860598615986259863598645986559866598675986859869598705987159872598735987459875598765987759878598795988059881598825988359884598855988659887598885988959890598915989259893598945989559896598975989859899599005990159902599035990459905599065990759908599095991059911599125991359914599155991659917599185991959920599215992259923599245992559926599275992859929599305993159932599335993459935599365993759938599395994059941599425994359944599455994659947599485994959950599515995259953599545995559956599575995859959599605996159962599635996459965599665996759968599695997059971599725997359974599755997659977599785997959980599815998259983599845998559986599875998859989599905999159992599935999459995599965999759998599996000060001600026000360004600056000660007600086000960010600116001260013600146001560016600176001860019600206002160022600236002460025600266002760028600296003060031600326003360034600356003660037600386003960040600416004260043600446004560046600476004860049600506005160052600536005460055600566005760058600596006060061600626006360064600656006660067600686006960070600716007260073600746007560076600776007860079600806008160082600836008460085600866008760088600896009060091600926009360094600956009660097600986009960100601016010260103601046010560106601076010860109601106011160112601136011460115601166011760118601196012060121601226012360124601256012660127601286012960130601316013260133601346013560136601376013860139601406014160142601436014460145601466014760148601496015060151601526015360154601556015660157601586015960160601616016260163601646016560166601676016860169601706017160172601736017460175601766017760178601796018060181601826018360184601856018660187601886018960190601916019260193601946019560196601976019860199602006020160202602036020460205602066020760208602096021060211602126021360214602156021660217602186021960220602216022260223602246022560226602276022860229602306023160232602336023460235602366023760238602396024060241602426024360244602456024660247602486024960250602516025260253602546025560256602576025860259602606026160262602636026460265602666026760268602696027060271602726027360274602756027660277602786027960280602816028260283602846028560286602876028860289602906029160292602936029460295602966029760298602996030060301603026030360304603056030660307603086030960310603116031260313603146031560316603176031860319603206032160322603236032460325603266032760328603296033060331603326033360334603356033660337603386033960340603416034260343603446034560346603476034860349603506035160352603536035460355603566035760358603596036060361603626036360364603656036660367603686036960370603716037260373603746037560376603776037860379603806038160382603836038460385603866038760388603896039060391603926039360394603956039660397603986039960400604016040260403604046040560406604076040860409604106041160412604136041460415604166041760418604196042060421604226042360424604256042660427604286042960430604316043260433604346043560436604376043860439604406044160442604436044460445604466044760448604496045060451604526045360454604556045660457604586045960460604616046260463604646046560466604676046860469604706047160472604736047460475604766047760478604796048060481604826048360484604856048660487604886048960490604916049260493604946049560496604976049860499605006050160502605036050460505605066050760508605096051060511605126051360514605156051660517605186051960520605216052260523605246052560526605276052860529605306053160532605336053460535605366053760538605396054060541605426054360544605456054660547605486054960550605516055260553605546055560556605576055860559605606056160562605636056460565605666056760568605696057060571605726057360574605756057660577605786057960580605816058260583605846058560586605876058860589605906059160592605936059460595605966059760598605996060060601606026060360604606056060660607606086060960610606116061260613606146061560616606176061860619606206062160622606236062460625606266062760628606296063060631606326063360634606356063660637606386063960640606416064260643606446064560646606476064860649606506065160652606536065460655606566065760658606596066060661606626066360664606656066660667606686066960670606716067260673606746067560676606776067860679606806068160682606836068460685606866068760688606896069060691606926069360694606956069660697606986069960700607016070260703607046070560706607076070860709607106071160712607136071460715607166071760718607196072060721607226072360724607256072660727607286072960730607316073260733607346073560736607376073860739607406074160742607436074460745607466074760748607496075060751607526075360754607556075660757607586075960760607616076260763607646076560766607676076860769607706077160772607736077460775607766077760778607796078060781607826078360784607856078660787607886078960790607916079260793607946079560796607976079860799608006080160802608036080460805608066080760808608096081060811608126081360814608156081660817608186081960820608216082260823608246082560826608276082860829608306083160832608336083460835608366083760838608396084060841608426084360844608456084660847608486084960850608516085260853608546085560856608576085860859608606086160862608636086460865608666086760868608696087060871608726087360874608756087660877608786087960880608816088260883608846088560886608876088860889608906089160892608936089460895608966089760898608996090060901609026090360904609056090660907609086090960910609116091260913609146091560916609176091860919609206092160922609236092460925609266092760928609296093060931609326093360934609356093660937609386093960940609416094260943609446094560946609476094860949609506095160952609536095460955609566095760958609596096060961609626096360964609656096660967609686096960970609716097260973609746097560976609776097860979609806098160982609836098460985609866098760988609896099060991609926099360994609956099660997609986099961000610016100261003610046100561006610076100861009610106101161012610136101461015610166101761018610196102061021610226102361024610256102661027610286102961030610316103261033610346103561036610376103861039610406104161042610436104461045610466104761048610496105061051610526105361054610556105661057610586105961060610616106261063610646106561066610676106861069610706107161072610736107461075610766107761078610796108061081610826108361084610856108661087610886108961090610916109261093610946109561096610976109861099611006110161102611036110461105611066110761108611096111061111611126111361114611156111661117611186111961120611216112261123611246112561126611276112861129611306113161132611336113461135611366113761138611396114061141611426114361144611456114661147611486114961150611516115261153611546115561156611576115861159611606116161162611636116461165611666116761168611696117061171611726117361174611756117661177611786117961180611816118261183611846118561186611876118861189611906119161192611936119461195611966119761198611996120061201612026120361204612056120661207612086120961210612116121261213612146121561216612176121861219612206122161222612236122461225612266122761228612296123061231612326123361234612356123661237612386123961240612416124261243612446124561246612476124861249612506125161252612536125461255612566125761258612596126061261612626126361264612656126661267612686126961270612716127261273612746127561276612776127861279612806128161282612836128461285612866128761288612896129061291612926129361294612956129661297612986129961300613016130261303613046130561306613076130861309613106131161312613136131461315613166131761318613196132061321613226132361324613256132661327613286132961330613316133261333613346133561336613376133861339613406134161342613436134461345613466134761348613496135061351613526135361354613556135661357613586135961360613616136261363613646136561366613676136861369613706137161372613736137461375613766137761378613796138061381613826138361384613856138661387613886138961390613916139261393613946139561396613976139861399614006140161402614036140461405614066140761408614096141061411614126141361414614156141661417614186141961420614216142261423614246142561426614276142861429614306143161432614336143461435614366143761438614396144061441614426144361444614456144661447614486144961450614516145261453614546145561456614576145861459614606146161462614636146461465614666146761468614696147061471614726147361474614756147661477614786147961480614816148261483614846148561486614876148861489614906149161492614936149461495614966149761498614996150061501615026150361504615056150661507615086150961510615116151261513615146151561516615176151861519615206152161522615236152461525615266152761528615296153061531615326153361534615356153661537615386153961540615416154261543615446154561546615476154861549615506155161552615536155461555615566155761558615596156061561615626156361564615656156661567615686156961570615716157261573615746157561576615776157861579615806158161582615836158461585615866158761588615896159061591615926159361594615956159661597615986159961600616016160261603616046160561606616076160861609616106161161612616136161461615616166161761618616196162061621616226162361624616256162661627616286162961630616316163261633616346163561636616376163861639616406164161642616436164461645616466164761648616496165061651616526165361654616556165661657616586165961660616616166261663616646166561666616676166861669616706167161672616736167461675616766167761678616796168061681616826168361684616856168661687616886168961690616916169261693616946169561696616976169861699617006170161702617036170461705617066170761708617096171061711617126171361714617156171661717617186171961720617216172261723617246172561726617276172861729617306173161732617336173461735617366173761738617396174061741617426174361744617456174661747617486174961750617516175261753617546175561756617576175861759617606176161762617636176461765617666176761768617696177061771617726177361774617756177661777617786177961780617816178261783617846178561786617876178861789617906179161792617936179461795617966179761798617996180061801618026180361804618056180661807618086180961810618116181261813618146181561816618176181861819618206182161822618236182461825618266182761828618296183061831618326183361834618356183661837618386183961840618416184261843618446184561846618476184861849618506185161852618536185461855618566185761858618596186061861618626186361864618656186661867618686186961870618716187261873618746187561876618776187861879618806188161882618836188461885618866188761888618896189061891618926189361894618956189661897618986189961900619016190261903619046190561906619076190861909619106191161912619136191461915619166191761918619196192061921619226192361924619256192661927619286192961930619316193261933619346193561936619376193861939619406194161942619436194461945619466194761948619496195061951619526195361954619556195661957619586195961960619616196261963619646196561966619676196861969619706197161972619736197461975619766197761978619796198061981619826198361984619856198661987619886198961990619916199261993619946199561996619976199861999620006200162002620036200462005620066200762008620096201062011620126201362014620156201662017620186201962020620216202262023620246202562026620276202862029620306203162032620336203462035620366203762038620396204062041620426204362044620456204662047620486204962050620516205262053620546205562056620576205862059620606206162062620636206462065620666206762068620696207062071620726207362074620756207662077620786207962080620816208262083620846208562086620876208862089620906209162092620936209462095620966209762098620996210062101621026210362104621056210662107621086210962110621116211262113621146211562116621176211862119621206212162122621236212462125621266212762128621296213062131621326213362134621356213662137621386213962140621416214262143621446214562146621476214862149621506215162152621536215462155621566215762158621596216062161621626216362164621656216662167621686216962170621716217262173621746217562176621776217862179621806218162182621836218462185621866218762188621896219062191621926219362194621956219662197621986219962200622016220262203622046220562206622076220862209622106221162212622136221462215622166221762218622196222062221622226222362224622256222662227622286222962230622316223262233622346223562236622376223862239622406224162242622436224462245622466224762248622496225062251622526225362254622556225662257622586225962260622616226262263622646226562266622676226862269622706227162272622736227462275622766227762278622796228062281622826228362284622856228662287622886228962290622916229262293622946229562296622976229862299623006230162302623036230462305623066230762308623096231062311623126231362314623156231662317623186231962320623216232262323623246232562326623276232862329623306233162332623336233462335623366233762338623396234062341623426234362344623456234662347623486234962350623516235262353623546235562356623576235862359623606236162362623636236462365623666236762368623696237062371623726237362374623756237662377623786237962380623816238262383623846238562386623876238862389623906239162392623936239462395623966239762398623996240062401624026240362404624056240662407624086240962410624116241262413624146241562416624176241862419624206242162422624236242462425624266242762428624296243062431624326243362434624356243662437624386243962440624416244262443624446244562446624476244862449624506245162452624536245462455624566245762458624596246062461624626246362464624656246662467624686246962470624716247262473624746247562476624776247862479624806248162482624836248462485624866248762488624896249062491624926249362494624956249662497624986249962500625016250262503625046250562506625076250862509625106251162512625136251462515625166251762518625196252062521625226252362524625256252662527625286252962530625316253262533625346253562536625376253862539625406254162542625436254462545625466254762548625496255062551625526255362554625556255662557625586255962560625616256262563625646256562566625676256862569625706257162572625736257462575625766257762578625796258062581625826258362584625856258662587625886258962590625916259262593625946259562596625976259862599626006260162602626036260462605626066260762608626096261062611626126261362614626156261662617626186261962620626216262262623626246262562626626276262862629626306263162632626336263462635626366263762638626396264062641626426264362644626456264662647626486264962650626516265262653626546265562656626576265862659626606266162662626636266462665626666266762668626696267062671626726267362674626756267662677626786267962680626816268262683626846268562686626876268862689626906269162692626936269462695626966269762698626996270062701627026270362704627056270662707627086270962710627116271262713627146271562716627176271862719627206272162722627236272462725627266272762728627296273062731627326273362734627356273662737627386273962740627416274262743627446274562746627476274862749627506275162752627536275462755627566275762758627596276062761627626276362764627656276662767627686276962770627716277262773627746277562776627776277862779627806278162782627836278462785627866278762788627896279062791627926279362794627956279662797627986279962800628016280262803628046280562806628076280862809628106281162812628136281462815628166281762818628196282062821628226282362824628256282662827628286282962830628316283262833628346283562836628376283862839628406284162842628436284462845628466284762848628496285062851628526285362854628556285662857628586285962860628616286262863628646286562866628676286862869628706287162872628736287462875628766287762878628796288062881628826288362884628856288662887628886288962890628916289262893628946289562896628976289862899629006290162902629036290462905629066290762908629096291062911629126291362914629156291662917629186291962920629216292262923629246292562926629276292862929629306293162932629336293462935629366293762938629396294062941629426294362944629456294662947629486294962950629516295262953629546295562956629576295862959629606296162962629636296462965629666296762968629696297062971629726297362974629756297662977629786297962980629816298262983629846298562986629876298862989629906299162992629936299462995629966299762998629996300063001630026300363004630056300663007630086300963010630116301263013630146301563016630176301863019630206302163022630236302463025630266302763028630296303063031630326303363034630356303663037630386303963040630416304263043630446304563046630476304863049630506305163052630536305463055630566305763058630596306063061630626306363064630656306663067630686306963070630716307263073630746307563076630776307863079630806308163082630836308463085630866308763088630896309063091630926309363094630956309663097630986309963100631016310263103631046310563106631076310863109631106311163112631136311463115631166311763118631196312063121631226312363124631256312663127631286312963130631316313263133631346313563136631376313863139631406314163142631436314463145631466314763148631496315063151631526315363154631556315663157631586315963160631616316263163631646316563166631676316863169631706317163172631736317463175631766317763178631796318063181631826318363184631856318663187631886318963190631916319263193631946319563196631976319863199632006320163202632036320463205632066320763208632096321063211632126321363214632156321663217632186321963220632216322263223632246322563226632276322863229632306323163232632336323463235632366323763238632396324063241632426324363244632456324663247632486324963250632516325263253632546325563256632576325863259632606326163262632636326463265632666326763268632696327063271632726327363274632756327663277632786327963280632816328263283632846328563286632876328863289632906329163292632936329463295632966329763298632996330063301633026330363304633056330663307633086330963310633116331263313633146331563316633176331863319633206332163322633236332463325633266332763328633296333063331633326333363334633356333663337633386333963340633416334263343633446334563346633476334863349633506335163352633536335463355633566335763358633596336063361633626336363364633656336663367633686336963370633716337263373633746337563376633776337863379633806338163382633836338463385633866338763388633896339063391633926339363394633956339663397633986339963400634016340263403634046340563406634076340863409634106341163412634136341463415634166341763418634196342063421634226342363424634256342663427634286342963430634316343263433634346343563436634376343863439634406344163442634436344463445634466344763448634496345063451634526345363454634556345663457634586345963460634616346263463634646346563466634676346863469634706347163472634736347463475634766347763478634796348063481634826348363484634856348663487634886348963490634916349263493634946349563496634976349863499635006350163502635036350463505635066350763508635096351063511635126351363514635156351663517635186351963520635216352263523635246352563526635276352863529635306353163532635336353463535635366353763538635396354063541635426354363544635456354663547635486354963550635516355263553635546355563556635576355863559635606356163562635636356463565635666356763568635696357063571635726357363574635756357663577635786357963580635816358263583635846358563586635876358863589635906359163592635936359463595635966359763598635996360063601636026360363604636056360663607636086360963610636116361263613636146361563616636176361863619636206362163622636236362463625636266362763628636296363063631636326363363634636356363663637636386363963640636416364263643636446364563646636476364863649636506365163652636536365463655636566365763658636596366063661636626366363664636656366663667636686366963670636716367263673636746367563676636776367863679636806368163682636836368463685636866368763688636896369063691636926369363694636956369663697636986369963700637016370263703637046370563706637076370863709637106371163712637136371463715637166371763718637196372063721637226372363724637256372663727637286372963730637316373263733637346373563736637376373863739637406374163742637436374463745637466374763748637496375063751637526375363754637556375663757637586375963760637616376263763637646376563766637676376863769637706377163772637736377463775637766377763778637796378063781637826378363784637856378663787637886378963790637916379263793637946379563796637976379863799638006380163802638036380463805638066380763808638096381063811638126381363814638156381663817638186381963820638216382263823638246382563826638276382863829638306383163832638336383463835638366383763838638396384063841638426384363844638456384663847638486384963850638516385263853638546385563856638576385863859638606386163862638636386463865638666386763868638696387063871638726387363874638756387663877638786387963880638816388263883638846388563886638876388863889638906389163892638936389463895638966389763898638996390063901639026390363904639056390663907639086390963910639116391263913639146391563916639176391863919639206392163922639236392463925639266392763928639296393063931639326393363934639356393663937639386393963940639416394263943639446394563946639476394863949639506395163952639536395463955639566395763958639596396063961639626396363964639656396663967639686396963970639716397263973639746397563976639776397863979639806398163982639836398463985639866398763988639896399063991639926399363994639956399663997639986399964000640016400264003640046400564006640076400864009640106401164012640136401464015640166401764018640196402064021640226402364024640256402664027640286402964030640316403264033640346403564036640376403864039640406404164042640436404464045640466404764048640496405064051640526405364054640556405664057640586405964060640616406264063640646406564066640676406864069640706407164072640736407464075640766407764078640796408064081640826408364084640856408664087640886408964090640916409264093640946409564096640976409864099641006410164102641036410464105641066410764108641096411064111641126411364114641156411664117641186411964120641216412264123641246412564126641276412864129641306413164132641336413464135641366413764138641396414064141641426414364144641456414664147641486414964150641516415264153641546415564156641576415864159641606416164162641636416464165641666416764168641696417064171641726417364174641756417664177641786417964180641816418264183641846418564186641876418864189641906419164192641936419464195641966419764198641996420064201642026420364204642056420664207642086420964210642116421264213642146421564216642176421864219642206422164222642236422464225642266422764228642296423064231642326423364234642356423664237642386423964240642416424264243642446424564246642476424864249642506425164252642536425464255642566425764258642596426064261642626426364264642656426664267642686426964270642716427264273642746427564276642776427864279642806428164282642836428464285642866428764288642896429064291642926429364294642956429664297642986429964300643016430264303643046430564306643076430864309643106431164312643136431464315643166431764318643196432064321643226432364324643256432664327643286432964330643316433264333643346433564336643376433864339643406434164342643436434464345643466434764348643496435064351643526435364354643556435664357643586435964360643616436264363643646436564366643676436864369643706437164372643736437464375643766437764378643796438064381643826438364384643856438664387643886438964390643916439264393643946439564396643976439864399644006440164402644036440464405644066440764408644096441064411644126441364414644156441664417644186441964420644216442264423644246442564426644276442864429644306443164432644336443464435644366443764438644396444064441644426444364444644456444664447644486444964450644516445264453644546445564456644576445864459644606446164462644636446464465644666446764468644696447064471644726447364474644756447664477644786447964480644816448264483644846448564486644876448864489644906449164492644936449464495644966449764498644996450064501645026450364504645056450664507645086450964510645116451264513645146451564516645176451864519645206452164522645236452464525645266452764528645296453064531645326453364534645356453664537645386453964540645416454264543645446454564546645476454864549645506455164552645536455464555645566455764558645596456064561645626456364564645656456664567645686456964570645716457264573645746457564576645776457864579645806458164582645836458464585645866458764588645896459064591645926459364594645956459664597645986459964600646016460264603646046460564606646076460864609646106461164612646136461464615646166461764618646196462064621646226462364624646256462664627646286462964630646316463264633646346463564636646376463864639646406464164642646436464464645646466464764648646496465064651646526465364654646556465664657646586465964660646616466264663646646466564666646676466864669646706467164672646736467464675646766467764678646796468064681646826468364684646856468664687646886468964690646916469264693646946469564696646976469864699647006470164702647036470464705647066470764708647096471064711647126471364714647156471664717647186471964720647216472264723647246472564726647276472864729647306473164732647336473464735647366473764738647396474064741647426474364744647456474664747647486474964750647516475264753647546475564756647576475864759647606476164762647636476464765647666476764768647696477064771647726477364774647756477664777647786477964780647816478264783647846478564786647876478864789647906479164792647936479464795647966479764798647996480064801648026480364804648056480664807648086480964810648116481264813648146481564816648176481864819648206482164822648236482464825648266482764828648296483064831648326483364834648356483664837648386483964840648416484264843648446484564846648476484864849648506485164852648536485464855648566485764858648596486064861648626486364864648656486664867648686486964870648716487264873648746487564876648776487864879648806488164882648836488464885648866488764888648896489064891648926489364894648956489664897648986489964900649016490264903649046490564906649076490864909649106491164912649136491464915649166491764918649196492064921649226492364924649256492664927649286492964930649316493264933649346493564936649376493864939649406494164942649436494464945649466494764948649496495064951649526495364954649556495664957649586495964960649616496264963649646496564966649676496864969649706497164972649736497464975649766497764978649796498064981649826498364984649856498664987649886498964990649916499264993649946499564996649976499864999650006500165002650036500465005650066500765008650096501065011650126501365014650156501665017650186501965020650216502265023650246502565026650276502865029650306503165032650336503465035650366503765038650396504065041650426504365044650456504665047650486504965050650516505265053650546505565056650576505865059650606506165062650636506465065650666506765068650696507065071650726507365074650756507665077650786507965080650816508265083650846508565086650876508865089650906509165092650936509465095650966509765098650996510065101651026510365104651056510665107651086510965110651116511265113651146511565116651176511865119651206512165122651236512465125651266512765128651296513065131651326513365134651356513665137651386513965140651416514265143651446514565146651476514865149651506515165152651536515465155651566515765158651596516065161651626516365164651656516665167651686516965170651716517265173651746517565176651776517865179651806518165182651836518465185651866518765188651896519065191651926519365194651956519665197651986519965200652016520265203652046520565206652076520865209652106521165212652136521465215652166521765218652196522065221652226522365224652256522665227652286522965230652316523265233652346523565236652376523865239652406524165242652436524465245652466524765248652496525065251652526525365254652556525665257652586525965260652616526265263652646526565266652676526865269652706527165272652736527465275652766527765278652796528065281652826528365284652856528665287652886528965290652916529265293652946529565296652976529865299653006530165302653036530465305653066530765308653096531065311653126531365314653156531665317653186531965320653216532265323653246532565326653276532865329653306533165332653336533465335653366533765338653396534065341653426534365344653456534665347653486534965350653516535265353653546535565356653576535865359653606536165362653636536465365653666536765368653696537065371653726537365374653756537665377653786537965380653816538265383653846538565386653876538865389653906539165392653936539465395653966539765398653996540065401654026540365404654056540665407654086540965410654116541265413654146541565416654176541865419654206542165422654236542465425654266542765428654296543065431654326543365434654356543665437654386543965440654416544265443654446544565446654476544865449654506545165452654536545465455654566545765458654596546065461654626546365464654656546665467654686546965470654716547265473654746547565476654776547865479654806548165482654836548465485654866548765488654896549065491654926549365494654956549665497654986549965500655016550265503655046550565506655076550865509655106551165512655136551465515655166551765518655196552065521655226552365524655256552665527655286552965530655316553265533655346553565536655376553865539655406554165542655436554465545655466554765548655496555065551655526555365554655556555665557655586555965560655616556265563655646556565566655676556865569655706557165572655736557465575655766557765578655796558065581655826558365584655856558665587655886558965590655916559265593655946559565596655976559865599656006560165602656036560465605656066560765608656096561065611656126561365614656156561665617656186561965620656216562265623656246562565626656276562865629656306563165632656336563465635656366563765638656396564065641656426564365644656456564665647656486564965650656516565265653656546565565656656576565865659656606566165662656636566465665656666566765668656696567065671656726567365674656756567665677656786567965680656816568265683656846568565686656876568865689656906569165692656936569465695656966569765698656996570065701657026570365704657056570665707657086570965710657116571265713657146571565716657176571865719657206572165722657236572465725657266572765728657296573065731657326573365734657356573665737657386573965740657416574265743657446574565746657476574865749657506575165752657536575465755657566575765758657596576065761657626576365764657656576665767657686576965770657716577265773657746577565776657776577865779657806578165782657836578465785657866578765788657896579065791657926579365794657956579665797657986579965800658016580265803658046580565806658076580865809658106581165812658136581465815658166581765818658196582065821658226582365824658256582665827658286582965830658316583265833658346583565836658376583865839658406584165842658436584465845658466584765848658496585065851658526585365854658556585665857658586585965860658616586265863658646586565866658676586865869658706587165872658736587465875658766587765878658796588065881658826588365884658856588665887658886588965890658916589265893658946589565896658976589865899659006590165902659036590465905659066590765908659096591065911659126591365914659156591665917659186591965920659216592265923659246592565926659276592865929659306593165932659336593465935659366593765938659396594065941659426594365944659456594665947659486594965950659516595265953659546595565956659576595865959659606596165962659636596465965659666596765968659696597065971659726597365974659756597665977659786597965980659816598265983659846598565986659876598865989659906599165992659936599465995659966599765998659996600066001660026600366004660056600666007660086600966010660116601266013660146601566016660176601866019660206602166022660236602466025660266602766028660296603066031660326603366034660356603666037660386603966040660416604266043660446604566046660476604866049660506605166052660536605466055660566605766058660596606066061660626606366064660656606666067660686606966070660716607266073660746607566076660776607866079660806608166082660836608466085660866608766088660896609066091660926609366094660956609666097660986609966100661016610266103661046610566106661076610866109661106611166112661136611466115661166611766118661196612066121661226612366124661256612666127661286612966130661316613266133661346613566136661376613866139661406614166142661436614466145661466614766148661496615066151661526615366154661556615666157661586615966160661616616266163661646616566166661676616866169661706617166172661736617466175661766617766178661796618066181661826618366184661856618666187661886618966190661916619266193661946619566196661976619866199662006620166202662036620466205662066620766208662096621066211662126621366214662156621666217662186621966220662216622266223662246622566226662276622866229662306623166232662336623466235662366623766238662396624066241662426624366244662456624666247662486624966250662516625266253662546625566256662576625866259662606626166262662636626466265662666626766268662696627066271662726627366274662756627666277662786627966280662816628266283662846628566286662876628866289662906629166292662936629466295662966629766298662996630066301663026630366304663056630666307663086630966310663116631266313663146631566316663176631866319663206632166322663236632466325663266632766328663296633066331663326633366334663356633666337663386633966340663416634266343663446634566346663476634866349663506635166352663536635466355663566635766358663596636066361663626636366364663656636666367663686636966370663716637266373663746637566376663776637866379663806638166382663836638466385663866638766388663896639066391663926639366394663956639666397663986639966400664016640266403664046640566406664076640866409664106641166412664136641466415664166641766418664196642066421664226642366424664256642666427664286642966430664316643266433664346643566436664376643866439664406644166442664436644466445664466644766448664496645066451664526645366454664556645666457664586645966460664616646266463664646646566466664676646866469664706647166472664736647466475664766647766478664796648066481664826648366484664856648666487664886648966490664916649266493664946649566496664976649866499665006650166502665036650466505665066650766508665096651066511665126651366514665156651666517665186651966520665216652266523665246652566526665276652866529665306653166532665336653466535665366653766538665396654066541665426654366544665456654666547665486654966550665516655266553665546655566556665576655866559665606656166562665636656466565665666656766568665696657066571665726657366574665756657666577665786657966580665816658266583665846658566586665876658866589665906659166592665936659466595665966659766598665996660066601666026660366604666056660666607666086660966610666116661266613666146661566616666176661866619666206662166622666236662466625666266662766628666296663066631666326663366634666356663666637666386663966640666416664266643666446664566646666476664866649666506665166652666536665466655666566665766658666596666066661666626666366664666656666666667666686666966670666716667266673666746667566676666776667866679666806668166682666836668466685666866668766688666896669066691666926669366694666956669666697666986669966700667016670266703667046670566706667076670866709667106671166712667136671466715667166671766718667196672066721667226672366724667256672666727667286672966730667316673266733667346673566736667376673866739667406674166742667436674466745667466674766748667496675066751667526675366754667556675666757667586675966760667616676266763667646676566766667676676866769667706677166772667736677466775667766677766778667796678066781667826678366784667856678666787667886678966790667916679266793667946679566796667976679866799668006680166802668036680466805668066680766808668096681066811668126681366814668156681666817668186681966820668216682266823668246682566826668276682866829668306683166832668336683466835668366683766838668396684066841668426684366844668456684666847668486684966850668516685266853668546685566856668576685866859668606686166862668636686466865668666686766868668696687066871668726687366874668756687666877668786687966880668816688266883668846688566886668876688866889668906689166892668936689466895668966689766898668996690066901669026690366904669056690666907669086690966910669116691266913669146691566916669176691866919669206692166922669236692466925669266692766928669296693066931669326693366934669356693666937669386693966940669416694266943669446694566946669476694866949669506695166952669536695466955669566695766958669596696066961669626696366964669656696666967669686696966970669716697266973669746697566976669776697866979669806698166982669836698466985669866698766988669896699066991669926699366994669956699666997669986699967000670016700267003670046700567006670076700867009670106701167012670136701467015670166701767018670196702067021670226702367024670256702667027670286702967030670316703267033670346703567036670376703867039670406704167042670436704467045670466704767048670496705067051670526705367054670556705667057670586705967060670616706267063670646706567066670676706867069670706707167072670736707467075670766707767078670796708067081670826708367084670856708667087670886708967090670916709267093670946709567096670976709867099671006710167102671036710467105671066710767108671096711067111671126711367114671156711667117671186711967120671216712267123671246712567126671276712867129671306713167132671336713467135671366713767138671396714067141671426714367144671456714667147671486714967150671516715267153671546715567156671576715867159671606716167162671636716467165671666716767168671696717067171671726717367174671756717667177671786717967180671816718267183671846718567186671876718867189671906719167192671936719467195671966719767198671996720067201672026720367204672056720667207672086720967210672116721267213672146721567216672176721867219672206722167222672236722467225672266722767228672296723067231672326723367234672356723667237672386723967240672416724267243672446724567246672476724867249672506725167252672536725467255672566725767258672596726067261672626726367264672656726667267672686726967270672716727267273672746727567276672776727867279672806728167282672836728467285672866728767288672896729067291672926729367294672956729667297672986729967300673016730267303673046730567306673076730867309673106731167312673136731467315673166731767318673196732067321673226732367324673256732667327673286732967330673316733267333673346733567336673376733867339673406734167342673436734467345673466734767348673496735067351673526735367354673556735667357673586735967360673616736267363673646736567366673676736867369673706737167372673736737467375673766737767378673796738067381673826738367384673856738667387673886738967390673916739267393673946739567396673976739867399674006740167402674036740467405674066740767408674096741067411674126741367414674156741667417674186741967420674216742267423674246742567426674276742867429674306743167432674336743467435674366743767438674396744067441674426744367444674456744667447674486744967450674516745267453674546745567456674576745867459674606746167462674636746467465674666746767468674696747067471674726747367474674756747667477674786747967480674816748267483674846748567486674876748867489674906749167492674936749467495674966749767498674996750067501675026750367504675056750667507675086750967510675116751267513675146751567516675176751867519675206752167522675236752467525675266752767528675296753067531675326753367534675356753667537675386753967540675416754267543675446754567546675476754867549675506755167552675536755467555675566755767558675596756067561675626756367564675656756667567675686756967570675716757267573675746757567576675776757867579675806758167582675836758467585675866758767588675896759067591675926759367594675956759667597675986759967600676016760267603676046760567606676076760867609676106761167612676136761467615676166761767618676196762067621676226762367624676256762667627676286762967630676316763267633676346763567636676376763867639676406764167642676436764467645676466764767648676496765067651676526765367654676556765667657676586765967660676616766267663676646766567666676676766867669676706767167672676736767467675676766767767678676796768067681676826768367684676856768667687676886768967690676916769267693676946769567696676976769867699677006770167702677036770467705677066770767708677096771067711677126771367714677156771667717677186771967720677216772267723677246772567726677276772867729677306773167732677336773467735677366773767738677396774067741677426774367744677456774667747677486774967750677516775267753677546775567756677576775867759677606776167762677636776467765677666776767768677696777067771677726777367774677756777667777677786777967780677816778267783677846778567786677876778867789677906779167792677936779467795677966779767798677996780067801678026780367804678056780667807678086780967810678116781267813678146781567816678176781867819678206782167822678236782467825678266782767828678296783067831678326783367834678356783667837678386783967840678416784267843678446784567846678476784867849678506785167852678536785467855678566785767858678596786067861678626786367864678656786667867678686786967870678716787267873678746787567876678776787867879678806788167882678836788467885678866788767888678896789067891678926789367894678956789667897678986789967900679016790267903679046790567906679076790867909679106791167912679136791467915679166791767918679196792067921679226792367924679256792667927679286792967930679316793267933679346793567936679376793867939679406794167942679436794467945679466794767948679496795067951679526795367954679556795667957679586795967960679616796267963679646796567966679676796867969679706797167972679736797467975679766797767978679796798067981679826798367984679856798667987679886798967990679916799267993679946799567996679976799867999680006800168002680036800468005680066800768008680096801068011680126801368014680156801668017680186801968020680216802268023680246802568026680276802868029680306803168032680336803468035680366803768038680396804068041680426804368044680456804668047680486804968050680516805268053680546805568056680576805868059680606806168062680636806468065680666806768068680696807068071680726807368074680756807668077680786807968080680816808268083680846808568086680876808868089680906809168092680936809468095680966809768098680996810068101681026810368104681056810668107681086810968110681116811268113681146811568116681176811868119681206812168122681236812468125681266812768128681296813068131681326813368134681356813668137681386813968140681416814268143681446814568146681476814868149681506815168152681536815468155681566815768158681596816068161681626816368164681656816668167681686816968170681716817268173681746817568176681776817868179681806818168182681836818468185681866818768188681896819068191681926819368194681956819668197681986819968200682016820268203682046820568206682076820868209682106821168212682136821468215682166821768218682196822068221682226822368224682256822668227682286822968230682316823268233682346823568236682376823868239682406824168242682436824468245682466824768248682496825068251682526825368254682556825668257682586825968260682616826268263682646826568266682676826868269682706827168272682736827468275682766827768278682796828068281682826828368284682856828668287682886828968290682916829268293682946829568296682976829868299683006830168302683036830468305683066830768308683096831068311683126831368314683156831668317683186831968320683216832268323683246832568326683276832868329683306833168332683336833468335683366833768338683396834068341683426834368344683456834668347683486834968350683516835268353683546835568356683576835868359683606836168362683636836468365683666836768368683696837068371683726837368374683756837668377683786837968380683816838268383683846838568386683876838868389683906839168392683936839468395683966839768398683996840068401684026840368404684056840668407684086840968410684116841268413684146841568416684176841868419684206842168422684236842468425684266842768428684296843068431684326843368434684356843668437684386843968440684416844268443684446844568446684476844868449684506845168452684536845468455684566845768458684596846068461684626846368464684656846668467684686846968470684716847268473684746847568476684776847868479684806848168482684836848468485684866848768488684896849068491684926849368494684956849668497684986849968500685016850268503685046850568506685076850868509685106851168512685136851468515685166851768518685196852068521685226852368524685256852668527685286852968530685316853268533685346853568536685376853868539685406854168542685436854468545685466854768548685496855068551685526855368554685556855668557685586855968560685616856268563685646856568566685676856868569685706857168572685736857468575685766857768578685796858068581685826858368584685856858668587685886858968590685916859268593685946859568596685976859868599686006860168602686036860468605686066860768608686096861068611686126861368614686156861668617686186861968620686216862268623686246862568626686276862868629686306863168632686336863468635686366863768638686396864068641686426864368644686456864668647686486864968650686516865268653686546865568656686576865868659686606866168662686636866468665686666866768668686696867068671686726867368674686756867668677686786867968680686816868268683686846868568686686876868868689686906869168692686936869468695686966869768698686996870068701687026870368704687056870668707687086870968710687116871268713687146871568716687176871868719687206872168722687236872468725687266872768728687296873068731687326873368734687356873668737687386873968740687416874268743687446874568746687476874868749687506875168752687536875468755687566875768758687596876068761687626876368764687656876668767687686876968770687716877268773687746877568776687776877868779687806878168782687836878468785687866878768788687896879068791687926879368794687956879668797687986879968800688016880268803688046880568806688076880868809688106881168812688136881468815688166881768818688196882068821688226882368824688256882668827688286882968830688316883268833688346883568836688376883868839688406884168842688436884468845688466884768848688496885068851688526885368854688556885668857688586885968860688616886268863688646886568866688676886868869688706887168872688736887468875688766887768878688796888068881688826888368884688856888668887688886888968890688916889268893688946889568896688976889868899689006890168902689036890468905689066890768908689096891068911689126891368914689156891668917689186891968920689216892268923689246892568926689276892868929689306893168932689336893468935689366893768938689396894068941689426894368944689456894668947689486894968950689516895268953689546895568956689576895868959689606896168962689636896468965689666896768968689696897068971689726897368974689756897668977689786897968980689816898268983689846898568986689876898868989689906899168992689936899468995689966899768998689996900069001690026900369004690056900669007690086900969010690116901269013690146901569016690176901869019690206902169022690236902469025690266902769028690296903069031690326903369034690356903669037690386903969040690416904269043690446904569046690476904869049690506905169052690536905469055690566905769058690596906069061690626906369064690656906669067690686906969070690716907269073690746907569076690776907869079690806908169082690836908469085690866908769088690896909069091690926909369094690956909669097690986909969100691016910269103691046910569106691076910869109691106911169112691136911469115691166911769118691196912069121691226912369124691256912669127691286912969130691316913269133691346913569136691376913869139691406914169142691436914469145691466914769148691496915069151691526915369154691556915669157691586915969160691616916269163691646916569166691676916869169691706917169172691736917469175691766917769178691796918069181691826918369184691856918669187691886918969190691916919269193691946919569196691976919869199692006920169202692036920469205692066920769208692096921069211692126921369214692156921669217692186921969220692216922269223692246922569226692276922869229692306923169232692336923469235692366923769238692396924069241692426924369244692456924669247692486924969250692516925269253692546925569256692576925869259692606926169262692636926469265692666926769268692696927069271692726927369274692756927669277692786927969280692816928269283692846928569286692876928869289692906929169292692936929469295692966929769298692996930069301693026930369304693056930669307693086930969310693116931269313693146931569316693176931869319693206932169322693236932469325693266932769328693296933069331693326933369334693356933669337693386933969340693416934269343693446934569346693476934869349693506935169352693536935469355693566935769358693596936069361693626936369364693656936669367693686936969370693716937269373693746937569376693776937869379693806938169382693836938469385693866938769388693896939069391693926939369394693956939669397693986939969400694016940269403694046940569406694076940869409694106941169412694136941469415694166941769418694196942069421694226942369424694256942669427694286942969430694316943269433694346943569436694376943869439694406944169442694436944469445694466944769448694496945069451694526945369454694556945669457694586945969460694616946269463694646946569466694676946869469694706947169472694736947469475694766947769478694796948069481694826948369484694856948669487694886948969490694916949269493694946949569496694976949869499695006950169502695036950469505695066950769508695096951069511695126951369514695156951669517695186951969520695216952269523695246952569526695276952869529695306953169532695336953469535695366953769538695396954069541695426954369544695456954669547695486954969550695516955269553695546955569556695576955869559695606956169562695636956469565695666956769568695696957069571695726957369574695756957669577695786957969580695816958269583695846958569586695876958869589695906959169592695936959469595695966959769598695996960069601696026960369604696056960669607696086960969610696116961269613696146961569616696176961869619696206962169622696236962469625696266962769628696296963069631696326963369634696356963669637696386963969640696416964269643696446964569646696476964869649696506965169652696536965469655696566965769658696596966069661696626966369664696656966669667696686966969670696716967269673696746967569676696776967869679696806968169682696836968469685696866968769688696896969069691696926969369694696956969669697696986969969700697016970269703697046970569706697076970869709697106971169712697136971469715697166971769718697196972069721697226972369724697256972669727697286972969730697316973269733697346973569736697376973869739697406974169742697436974469745697466974769748697496975069751697526975369754697556975669757697586975969760697616976269763697646976569766697676976869769697706977169772697736977469775697766977769778697796978069781697826978369784697856978669787697886978969790697916979269793697946979569796697976979869799698006980169802698036980469805698066980769808698096981069811698126981369814698156981669817698186981969820698216982269823698246982569826698276982869829698306983169832698336983469835698366983769838698396984069841698426984369844698456984669847698486984969850698516985269853698546985569856698576985869859698606986169862698636986469865698666986769868698696987069871698726987369874698756987669877698786987969880698816988269883698846988569886698876988869889698906989169892698936989469895698966989769898698996990069901699026990369904699056990669907699086990969910699116991269913699146991569916699176991869919699206992169922699236992469925699266992769928699296993069931699326993369934699356993669937699386993969940699416994269943699446994569946699476994869949699506995169952699536995469955699566995769958699596996069961699626996369964699656996669967699686996969970699716997269973699746997569976699776997869979699806998169982699836998469985699866998769988699896999069991699926999369994699956999669997699986999970000700017000270003700047000570006700077000870009700107001170012700137001470015700167001770018700197002070021700227002370024700257002670027700287002970030700317003270033700347003570036700377003870039700407004170042700437004470045700467004770048700497005070051700527005370054700557005670057700587005970060700617006270063700647006570066700677006870069700707007170072700737007470075700767007770078700797008070081700827008370084700857008670087700887008970090700917009270093700947009570096700977009870099701007010170102701037010470105701067010770108701097011070111701127011370114701157011670117701187011970120701217012270123701247012570126701277012870129701307013170132701337013470135701367013770138701397014070141701427014370144701457014670147701487014970150701517015270153701547015570156701577015870159701607016170162701637016470165701667016770168701697017070171701727017370174701757017670177701787017970180701817018270183701847018570186701877018870189701907019170192701937019470195701967019770198701997020070201702027020370204702057020670207702087020970210702117021270213702147021570216702177021870219702207022170222702237022470225702267022770228702297023070231702327023370234702357023670237702387023970240702417024270243702447024570246702477024870249702507025170252702537025470255702567025770258702597026070261702627026370264702657026670267702687026970270702717027270273702747027570276702777027870279702807028170282702837028470285702867028770288702897029070291702927029370294702957029670297702987029970300703017030270303703047030570306703077030870309703107031170312703137031470315703167031770318703197032070321703227032370324703257032670327703287032970330703317033270333703347033570336703377033870339703407034170342703437034470345703467034770348703497035070351703527035370354703557035670357703587035970360703617036270363703647036570366703677036870369703707037170372703737037470375703767037770378703797038070381703827038370384703857038670387703887038970390703917039270393703947039570396703977039870399704007040170402704037040470405704067040770408704097041070411704127041370414704157041670417704187041970420704217042270423704247042570426704277042870429704307043170432704337043470435704367043770438704397044070441704427044370444704457044670447704487044970450704517045270453704547045570456704577045870459704607046170462704637046470465704667046770468704697047070471704727047370474704757047670477704787047970480704817048270483704847048570486704877048870489704907049170492704937049470495704967049770498704997050070501705027050370504705057050670507705087050970510705117051270513705147051570516705177051870519705207052170522705237052470525705267052770528705297053070531705327053370534705357053670537705387053970540705417054270543705447054570546705477054870549705507055170552705537055470555705567055770558705597056070561705627056370564705657056670567705687056970570705717057270573705747057570576705777057870579705807058170582705837058470585705867058770588705897059070591705927059370594705957059670597705987059970600706017060270603706047060570606706077060870609706107061170612706137061470615706167061770618706197062070621706227062370624706257062670627706287062970630706317063270633706347063570636706377063870639706407064170642706437064470645706467064770648706497065070651706527065370654706557065670657706587065970660706617066270663706647066570666706677066870669706707067170672706737067470675706767067770678706797068070681706827068370684706857068670687706887068970690706917069270693706947069570696706977069870699707007070170702707037070470705707067070770708707097071070711707127071370714707157071670717707187071970720707217072270723707247072570726707277072870729707307073170732707337073470735707367073770738707397074070741707427074370744707457074670747707487074970750707517075270753707547075570756707577075870759707607076170762707637076470765707667076770768707697077070771707727077370774707757077670777707787077970780707817078270783707847078570786707877078870789707907079170792707937079470795707967079770798707997080070801708027080370804708057080670807708087080970810708117081270813708147081570816708177081870819708207082170822708237082470825708267082770828708297083070831708327083370834708357083670837708387083970840708417084270843708447084570846708477084870849708507085170852708537085470855708567085770858708597086070861708627086370864708657086670867708687086970870708717087270873708747087570876708777087870879708807088170882708837088470885708867088770888708897089070891708927089370894708957089670897708987089970900709017090270903709047090570906709077090870909709107091170912709137091470915709167091770918709197092070921709227092370924709257092670927709287092970930709317093270933709347093570936709377093870939709407094170942709437094470945709467094770948709497095070951709527095370954709557095670957709587095970960709617096270963709647096570966709677096870969709707097170972709737097470975709767097770978709797098070981709827098370984709857098670987709887098970990709917099270993709947099570996709977099870999710007100171002710037100471005710067100771008710097101071011710127101371014710157101671017710187101971020710217102271023710247102571026710277102871029710307103171032710337103471035710367103771038710397104071041710427104371044710457104671047710487104971050710517105271053710547105571056710577105871059710607106171062710637106471065710667106771068710697107071071710727107371074710757107671077710787107971080710817108271083710847108571086710877108871089710907109171092710937109471095710967109771098710997110071101711027110371104711057110671107711087110971110711117111271113711147111571116711177111871119711207112171122711237112471125711267112771128711297113071131711327113371134711357113671137711387113971140711417114271143711447114571146711477114871149711507115171152711537115471155711567115771158711597116071161711627116371164711657116671167711687116971170711717117271173711747117571176711777117871179711807118171182711837118471185711867118771188711897119071191711927119371194711957119671197711987119971200712017120271203712047120571206712077120871209712107121171212712137121471215712167121771218712197122071221712227122371224712257122671227712287122971230712317123271233712347123571236712377123871239712407124171242712437124471245712467124771248712497125071251712527125371254712557125671257712587125971260712617126271263712647126571266712677126871269712707127171272712737127471275712767127771278712797128071281712827128371284712857128671287712887128971290712917129271293712947129571296712977129871299713007130171302713037130471305713067130771308713097131071311713127131371314713157131671317713187131971320713217132271323713247132571326713277132871329713307133171332713337133471335713367133771338713397134071341713427134371344713457134671347713487134971350713517135271353713547135571356713577135871359713607136171362713637136471365713667136771368713697137071371713727137371374713757137671377713787137971380713817138271383713847138571386713877138871389713907139171392713937139471395713967139771398713997140071401714027140371404714057140671407714087140971410714117141271413714147141571416714177141871419714207142171422714237142471425714267142771428714297143071431714327143371434714357143671437714387143971440714417144271443714447144571446714477144871449714507145171452714537145471455714567145771458714597146071461714627146371464714657146671467714687146971470714717147271473714747147571476714777147871479714807148171482714837148471485714867148771488714897149071491714927149371494714957149671497714987149971500715017150271503715047150571506715077150871509715107151171512715137151471515715167151771518715197152071521715227152371524715257152671527715287152971530715317153271533715347153571536715377153871539715407154171542715437154471545715467154771548715497155071551715527155371554715557155671557715587155971560715617156271563715647156571566715677156871569715707157171572715737157471575715767157771578715797158071581715827158371584715857158671587715887158971590715917159271593715947159571596715977159871599716007160171602716037160471605716067160771608716097161071611716127161371614716157161671617716187161971620716217162271623716247162571626716277162871629716307163171632716337163471635716367163771638716397164071641716427164371644716457164671647716487164971650716517165271653716547165571656716577165871659716607166171662716637166471665716667166771668716697167071671716727167371674716757167671677716787167971680716817168271683716847168571686716877168871689716907169171692716937169471695716967169771698716997170071701717027170371704717057170671707717087170971710717117171271713717147171571716717177171871719717207172171722717237172471725717267172771728717297173071731717327173371734717357173671737717387173971740717417174271743717447174571746717477174871749717507175171752717537175471755717567175771758717597176071761717627176371764717657176671767717687176971770717717177271773717747177571776717777177871779717807178171782717837178471785717867178771788717897179071791717927179371794717957179671797717987179971800718017180271803718047180571806718077180871809718107181171812718137181471815718167181771818718197182071821718227182371824718257182671827718287182971830718317183271833718347183571836718377183871839718407184171842718437184471845718467184771848718497185071851718527185371854718557185671857718587185971860718617186271863718647186571866718677186871869718707187171872718737187471875718767187771878718797188071881718827188371884718857188671887718887188971890718917189271893718947189571896718977189871899719007190171902719037190471905719067190771908719097191071911719127191371914719157191671917719187191971920719217192271923719247192571926719277192871929719307193171932719337193471935719367193771938719397194071941719427194371944719457194671947719487194971950719517195271953719547195571956719577195871959719607196171962719637196471965719667196771968719697197071971719727197371974719757197671977719787197971980719817198271983719847198571986719877198871989719907199171992719937199471995719967199771998719997200072001720027200372004720057200672007720087200972010720117201272013720147201572016720177201872019720207202172022720237202472025720267202772028720297203072031720327203372034720357203672037720387203972040720417204272043720447204572046720477204872049720507205172052720537205472055720567205772058720597206072061720627206372064720657206672067720687206972070720717207272073720747207572076720777207872079720807208172082720837208472085720867208772088720897209072091720927209372094720957209672097720987209972100721017210272103721047210572106721077210872109721107211172112721137211472115721167211772118721197212072121721227212372124721257212672127721287212972130721317213272133721347213572136721377213872139721407214172142721437214472145721467214772148721497215072151721527215372154721557215672157721587215972160721617216272163721647216572166721677216872169721707217172172721737217472175721767217772178721797218072181721827218372184721857218672187721887218972190721917219272193721947219572196721977219872199722007220172202722037220472205722067220772208722097221072211722127221372214722157221672217722187221972220722217222272223722247222572226722277222872229722307223172232722337223472235722367223772238722397224072241722427224372244722457224672247722487224972250722517225272253722547225572256722577225872259722607226172262722637226472265722667226772268722697227072271722727227372274722757227672277722787227972280722817228272283722847228572286722877228872289722907229172292722937229472295722967229772298722997230072301723027230372304723057230672307723087230972310723117231272313723147231572316723177231872319723207232172322723237232472325723267232772328723297233072331723327233372334723357233672337723387233972340723417234272343723447234572346723477234872349723507235172352723537235472355723567235772358723597236072361723627236372364723657236672367723687236972370723717237272373723747237572376723777237872379723807238172382723837238472385723867238772388723897239072391723927239372394723957239672397723987239972400724017240272403724047240572406724077240872409724107241172412724137241472415724167241772418724197242072421724227242372424724257242672427724287242972430724317243272433724347243572436724377243872439724407244172442724437244472445724467244772448724497245072451724527245372454724557245672457724587245972460724617246272463724647246572466724677246872469724707247172472724737247472475724767247772478724797248072481724827248372484724857248672487724887248972490724917249272493724947249572496724977249872499725007250172502725037250472505725067250772508725097251072511725127251372514725157251672517725187251972520725217252272523725247252572526725277252872529725307253172532725337253472535725367253772538725397254072541725427254372544725457254672547725487254972550725517255272553725547255572556725577255872559725607256172562725637256472565725667256772568725697257072571725727257372574725757257672577725787257972580725817258272583725847258572586725877258872589725907259172592725937259472595725967259772598725997260072601726027260372604726057260672607726087260972610726117261272613726147261572616726177261872619726207262172622726237262472625726267262772628726297263072631726327263372634726357263672637726387263972640726417264272643726447264572646726477264872649726507265172652726537265472655726567265772658726597266072661726627266372664726657266672667726687266972670726717267272673726747267572676726777267872679726807268172682726837268472685726867268772688726897269072691726927269372694726957269672697726987269972700727017270272703727047270572706727077270872709727107271172712727137271472715727167271772718727197272072721727227272372724727257272672727727287272972730727317273272733727347273572736727377273872739727407274172742727437274472745727467274772748727497275072751727527275372754727557275672757727587275972760727617276272763727647276572766727677276872769727707277172772727737277472775727767277772778727797278072781727827278372784727857278672787727887278972790727917279272793727947279572796727977279872799728007280172802728037280472805728067280772808728097281072811728127281372814728157281672817728187281972820728217282272823728247282572826728277282872829728307283172832728337283472835728367283772838728397284072841728427284372844728457284672847728487284972850728517285272853728547285572856728577285872859728607286172862728637286472865728667286772868728697287072871728727287372874728757287672877728787287972880728817288272883728847288572886728877288872889728907289172892728937289472895728967289772898728997290072901729027290372904729057290672907729087290972910729117291272913729147291572916729177291872919729207292172922729237292472925729267292772928729297293072931729327293372934729357293672937729387293972940729417294272943729447294572946729477294872949729507295172952729537295472955729567295772958729597296072961729627296372964729657296672967729687296972970729717297272973729747297572976729777297872979729807298172982729837298472985729867298772988729897299072991729927299372994729957299672997729987299973000730017300273003730047300573006730077300873009730107301173012730137301473015730167301773018730197302073021730227302373024730257302673027730287302973030730317303273033730347303573036730377303873039730407304173042730437304473045730467304773048730497305073051730527305373054730557305673057730587305973060730617306273063730647306573066730677306873069730707307173072730737307473075730767307773078730797308073081730827308373084730857308673087730887308973090730917309273093730947309573096730977309873099731007310173102731037310473105731067310773108731097311073111731127311373114731157311673117731187311973120731217312273123731247312573126731277312873129731307313173132731337313473135731367313773138731397314073141731427314373144731457314673147731487314973150731517315273153731547315573156731577315873159731607316173162731637316473165731667316773168731697317073171731727317373174731757317673177731787317973180731817318273183731847318573186731877318873189731907319173192731937319473195731967319773198731997320073201732027320373204732057320673207732087320973210732117321273213732147321573216732177321873219732207322173222732237322473225732267322773228732297323073231732327323373234732357323673237732387323973240732417324273243732447324573246732477324873249732507325173252732537325473255732567325773258732597326073261732627326373264732657326673267732687326973270732717327273273732747327573276732777327873279732807328173282732837328473285732867328773288732897329073291732927329373294732957329673297732987329973300733017330273303733047330573306733077330873309733107331173312733137331473315733167331773318733197332073321733227332373324733257332673327733287332973330733317333273333733347333573336733377333873339733407334173342733437334473345733467334773348733497335073351733527335373354733557335673357733587335973360733617336273363733647336573366733677336873369733707337173372733737337473375733767337773378733797338073381733827338373384733857338673387733887338973390733917339273393733947339573396733977339873399734007340173402734037340473405734067340773408734097341073411734127341373414734157341673417734187341973420734217342273423734247342573426734277342873429734307343173432734337343473435734367343773438734397344073441734427344373444734457344673447734487344973450734517345273453734547345573456734577345873459734607346173462734637346473465734667346773468734697347073471734727347373474734757347673477734787347973480734817348273483734847348573486734877348873489734907349173492734937349473495734967349773498734997350073501735027350373504735057350673507735087350973510735117351273513735147351573516735177351873519735207352173522735237352473525735267352773528735297353073531735327353373534735357353673537735387353973540735417354273543735447354573546735477354873549735507355173552735537355473555735567355773558735597356073561735627356373564735657356673567735687356973570735717357273573735747357573576735777357873579735807358173582735837358473585735867358773588735897359073591735927359373594735957359673597735987359973600736017360273603736047360573606736077360873609736107361173612736137361473615736167361773618736197362073621736227362373624736257362673627736287362973630736317363273633736347363573636736377363873639736407364173642736437364473645736467364773648736497365073651736527365373654736557365673657736587365973660736617366273663736647366573666736677366873669736707367173672736737367473675736767367773678736797368073681736827368373684736857368673687736887368973690736917369273693736947369573696736977369873699737007370173702737037370473705737067370773708737097371073711737127371373714737157371673717737187371973720737217372273723737247372573726737277372873729737307373173732737337373473735737367373773738737397374073741737427374373744737457374673747737487374973750737517375273753737547375573756737577375873759737607376173762737637376473765737667376773768737697377073771737727377373774737757377673777737787377973780737817378273783737847378573786737877378873789737907379173792737937379473795737967379773798737997380073801738027380373804738057380673807738087380973810738117381273813738147381573816738177381873819738207382173822738237382473825738267382773828738297383073831738327383373834738357383673837738387383973840738417384273843738447384573846738477384873849738507385173852738537385473855738567385773858738597386073861738627386373864738657386673867738687386973870738717387273873738747387573876738777387873879738807388173882738837388473885738867388773888738897389073891738927389373894738957389673897738987389973900739017390273903739047390573906739077390873909739107391173912739137391473915739167391773918739197392073921739227392373924739257392673927739287392973930739317393273933739347393573936739377393873939739407394173942739437394473945739467394773948739497395073951739527395373954739557395673957739587395973960739617396273963739647396573966739677396873969739707397173972739737397473975739767397773978739797398073981739827398373984739857398673987739887398973990739917399273993739947399573996739977399873999740007400174002740037400474005740067400774008740097401074011740127401374014740157401674017740187401974020740217402274023740247402574026740277402874029740307403174032740337403474035740367403774038740397404074041740427404374044740457404674047740487404974050740517405274053740547405574056740577405874059740607406174062740637406474065740667406774068740697407074071740727407374074740757407674077740787407974080740817408274083740847408574086740877408874089740907409174092740937409474095740967409774098740997410074101741027410374104741057410674107741087410974110741117411274113741147411574116741177411874119741207412174122741237412474125741267412774128741297413074131741327413374134741357413674137741387413974140741417414274143741447414574146741477414874149741507415174152741537415474155741567415774158741597416074161741627416374164741657416674167741687416974170741717417274173741747417574176741777417874179741807418174182741837418474185741867418774188741897419074191741927419374194741957419674197741987419974200742017420274203742047420574206742077420874209742107421174212742137421474215742167421774218742197422074221742227422374224742257422674227742287422974230742317423274233742347423574236742377423874239742407424174242742437424474245742467424774248742497425074251742527425374254742557425674257742587425974260742617426274263742647426574266742677426874269742707427174272742737427474275742767427774278742797428074281742827428374284742857428674287742887428974290742917429274293742947429574296742977429874299743007430174302743037430474305743067430774308743097431074311743127431374314743157431674317743187431974320743217432274323743247432574326743277432874329743307433174332743337433474335743367433774338743397434074341743427434374344743457434674347743487434974350743517435274353743547435574356743577435874359743607436174362743637436474365743667436774368743697437074371743727437374374743757437674377743787437974380743817438274383743847438574386743877438874389743907439174392743937439474395743967439774398743997440074401744027440374404744057440674407744087440974410744117441274413744147441574416744177441874419744207442174422744237442474425744267442774428744297443074431744327443374434744357443674437744387443974440744417444274443744447444574446744477444874449744507445174452744537445474455744567445774458744597446074461744627446374464744657446674467744687446974470744717447274473744747447574476744777447874479744807448174482744837448474485744867448774488744897449074491744927449374494744957449674497744987449974500745017450274503745047450574506745077450874509745107451174512745137451474515745167451774518745197452074521745227452374524745257452674527745287452974530745317453274533745347453574536745377453874539745407454174542745437454474545745467454774548745497455074551745527455374554745557455674557745587455974560745617456274563745647456574566745677456874569745707457174572745737457474575745767457774578745797458074581745827458374584745857458674587745887458974590745917459274593745947459574596745977459874599746007460174602746037460474605746067460774608746097461074611746127461374614746157461674617746187461974620746217462274623746247462574626746277462874629746307463174632746337463474635746367463774638746397464074641746427464374644746457464674647746487464974650746517465274653746547465574656746577465874659746607466174662746637466474665746667466774668746697467074671746727467374674746757467674677746787467974680746817468274683746847468574686746877468874689746907469174692746937469474695746967469774698746997470074701747027470374704747057470674707747087470974710747117471274713747147471574716747177471874719747207472174722747237472474725747267472774728747297473074731747327473374734747357473674737747387473974740747417474274743747447474574746747477474874749747507475174752747537475474755747567475774758747597476074761747627476374764747657476674767747687476974770747717477274773747747477574776747777477874779747807478174782747837478474785747867478774788747897479074791747927479374794747957479674797747987479974800748017480274803748047480574806748077480874809748107481174812748137481474815748167481774818748197482074821748227482374824748257482674827748287482974830748317483274833748347483574836748377483874839748407484174842748437484474845748467484774848748497485074851748527485374854748557485674857748587485974860748617486274863748647486574866748677486874869748707487174872748737487474875748767487774878748797488074881748827488374884748857488674887748887488974890748917489274893748947489574896748977489874899749007490174902749037490474905749067490774908749097491074911749127491374914749157491674917749187491974920749217492274923749247492574926749277492874929749307493174932749337493474935749367493774938749397494074941749427494374944749457494674947749487494974950749517495274953749547495574956749577495874959749607496174962749637496474965749667496774968749697497074971749727497374974749757497674977749787497974980749817498274983749847498574986749877498874989749907499174992749937499474995749967499774998749997500075001750027500375004750057500675007750087500975010750117501275013750147501575016750177501875019750207502175022750237502475025750267502775028750297503075031750327503375034750357503675037750387503975040750417504275043750447504575046750477504875049750507505175052750537505475055750567505775058750597506075061750627506375064750657506675067750687506975070750717507275073750747507575076750777507875079750807508175082750837508475085750867508775088750897509075091750927509375094750957509675097750987509975100751017510275103751047510575106751077510875109751107511175112751137511475115751167511775118751197512075121751227512375124751257512675127751287512975130751317513275133751347513575136751377513875139751407514175142751437514475145751467514775148751497515075151751527515375154751557515675157751587515975160751617516275163751647516575166751677516875169751707517175172751737517475175751767517775178751797518075181751827518375184751857518675187751887518975190751917519275193751947519575196751977519875199752007520175202752037520475205752067520775208752097521075211752127521375214752157521675217752187521975220752217522275223752247522575226752277522875229752307523175232752337523475235752367523775238752397524075241752427524375244752457524675247752487524975250752517525275253752547525575256752577525875259752607526175262752637526475265752667526775268752697527075271752727527375274752757527675277752787527975280752817528275283752847528575286752877528875289752907529175292752937529475295752967529775298752997530075301753027530375304753057530675307753087530975310753117531275313753147531575316753177531875319753207532175322753237532475325753267532775328753297533075331753327533375334753357533675337753387533975340753417534275343753447534575346753477534875349753507535175352753537535475355753567535775358753597536075361753627536375364753657536675367753687536975370753717537275373753747537575376753777537875379753807538175382753837538475385753867538775388753897539075391753927539375394753957539675397753987539975400754017540275403754047540575406754077540875409754107541175412754137541475415754167541775418754197542075421754227542375424754257542675427754287542975430754317543275433754347543575436754377543875439754407544175442754437544475445754467544775448754497545075451754527545375454754557545675457754587545975460754617546275463754647546575466754677546875469754707547175472754737547475475754767547775478754797548075481754827548375484754857548675487754887548975490754917549275493754947549575496754977549875499755007550175502755037550475505755067550775508755097551075511755127551375514755157551675517755187551975520755217552275523755247552575526755277552875529755307553175532755337553475535755367553775538755397554075541755427554375544755457554675547755487554975550755517555275553755547555575556755577555875559755607556175562755637556475565755667556775568755697557075571755727557375574755757557675577755787557975580755817558275583755847558575586755877558875589755907559175592755937559475595755967559775598755997560075601756027560375604756057560675607756087560975610756117561275613756147561575616756177561875619756207562175622756237562475625756267562775628756297563075631756327563375634756357563675637756387563975640756417564275643756447564575646756477564875649756507565175652756537565475655756567565775658756597566075661756627566375664756657566675667756687566975670756717567275673756747567575676756777567875679756807568175682756837568475685756867568775688756897569075691756927569375694756957569675697756987569975700757017570275703757047570575706757077570875709757107571175712757137571475715757167571775718757197572075721757227572375724757257572675727757287572975730757317573275733757347573575736757377573875739757407574175742757437574475745757467574775748757497575075751757527575375754757557575675757757587575975760757617576275763757647576575766757677576875769757707577175772757737577475775757767577775778757797578075781757827578375784757857578675787757887578975790757917579275793757947579575796757977579875799758007580175802758037580475805758067580775808758097581075811758127581375814758157581675817758187581975820758217582275823758247582575826758277582875829758307583175832758337583475835758367583775838758397584075841758427584375844758457584675847758487584975850758517585275853758547585575856758577585875859758607586175862758637586475865758667586775868758697587075871758727587375874758757587675877758787587975880758817588275883758847588575886758877588875889758907589175892758937589475895758967589775898758997590075901759027590375904759057590675907759087590975910759117591275913759147591575916759177591875919759207592175922759237592475925759267592775928759297593075931759327593375934759357593675937759387593975940759417594275943759447594575946759477594875949759507595175952759537595475955759567595775958759597596075961759627596375964759657596675967759687596975970759717597275973759747597575976759777597875979759807598175982759837598475985759867598775988759897599075991759927599375994759957599675997759987599976000760017600276003760047600576006760077600876009760107601176012760137601476015760167601776018760197602076021760227602376024760257602676027760287602976030760317603276033760347603576036760377603876039760407604176042760437604476045760467604776048760497605076051760527605376054760557605676057760587605976060760617606276063760647606576066760677606876069760707607176072760737607476075760767607776078760797608076081760827608376084760857608676087760887608976090760917609276093760947609576096760977609876099761007610176102761037610476105761067610776108761097611076111761127611376114761157611676117761187611976120761217612276123761247612576126761277612876129761307613176132761337613476135761367613776138761397614076141761427614376144761457614676147761487614976150761517615276153761547615576156761577615876159761607616176162761637616476165761667616776168761697617076171761727617376174761757617676177761787617976180761817618276183761847618576186761877618876189761907619176192761937619476195761967619776198761997620076201762027620376204762057620676207762087620976210762117621276213762147621576216762177621876219762207622176222762237622476225762267622776228762297623076231762327623376234762357623676237762387623976240762417624276243762447624576246762477624876249762507625176252762537625476255762567625776258762597626076261762627626376264762657626676267762687626976270762717627276273762747627576276762777627876279762807628176282762837628476285762867628776288762897629076291762927629376294762957629676297762987629976300763017630276303763047630576306763077630876309763107631176312763137631476315763167631776318763197632076321763227632376324763257632676327763287632976330763317633276333763347633576336763377633876339763407634176342763437634476345763467634776348763497635076351763527635376354763557635676357763587635976360763617636276363763647636576366763677636876369763707637176372763737637476375763767637776378763797638076381763827638376384763857638676387763887638976390763917639276393763947639576396763977639876399764007640176402764037640476405764067640776408764097641076411764127641376414764157641676417764187641976420764217642276423764247642576426764277642876429764307643176432764337643476435764367643776438764397644076441764427644376444764457644676447764487644976450764517645276453764547645576456764577645876459764607646176462764637646476465764667646776468764697647076471764727647376474764757647676477764787647976480764817648276483764847648576486764877648876489764907649176492764937649476495764967649776498764997650076501765027650376504765057650676507765087650976510765117651276513765147651576516765177651876519765207652176522765237652476525765267652776528765297653076531765327653376534765357653676537765387653976540765417654276543765447654576546765477654876549765507655176552765537655476555765567655776558765597656076561765627656376564765657656676567765687656976570765717657276573765747657576576765777657876579765807658176582765837658476585765867658776588765897659076591765927659376594765957659676597765987659976600766017660276603766047660576606766077660876609766107661176612766137661476615766167661776618766197662076621766227662376624766257662676627766287662976630766317663276633766347663576636766377663876639766407664176642766437664476645766467664776648766497665076651766527665376654766557665676657766587665976660766617666276663766647666576666766677666876669766707667176672766737667476675766767667776678766797668076681766827668376684766857668676687766887668976690766917669276693766947669576696766977669876699767007670176702767037670476705767067670776708767097671076711767127671376714767157671676717767187671976720767217672276723767247672576726767277672876729767307673176732767337673476735767367673776738767397674076741767427674376744767457674676747767487674976750767517675276753767547675576756767577675876759767607676176762767637676476765767667676776768767697677076771767727677376774767757677676777767787677976780767817678276783767847678576786767877678876789767907679176792767937679476795767967679776798767997680076801768027680376804768057680676807768087680976810768117681276813768147681576816768177681876819768207682176822768237682476825768267682776828768297683076831768327683376834768357683676837768387683976840768417684276843768447684576846768477684876849768507685176852768537685476855768567685776858768597686076861768627686376864768657686676867768687686976870768717687276873768747687576876768777687876879768807688176882768837688476885768867688776888768897689076891768927689376894768957689676897768987689976900769017690276903769047690576906769077690876909769107691176912769137691476915769167691776918769197692076921769227692376924769257692676927769287692976930769317693276933769347693576936769377693876939769407694176942769437694476945769467694776948769497695076951769527695376954769557695676957769587695976960769617696276963769647696576966769677696876969769707697176972769737697476975769767697776978769797698076981769827698376984769857698676987769887698976990769917699276993769947699576996769977699876999770007700177002770037700477005770067700777008770097701077011770127701377014770157701677017770187701977020770217702277023770247702577026770277702877029770307703177032770337703477035770367703777038770397704077041770427704377044770457704677047770487704977050770517705277053770547705577056770577705877059770607706177062770637706477065770667706777068770697707077071770727707377074770757707677077770787707977080770817708277083770847708577086770877708877089770907709177092770937709477095770967709777098770997710077101771027710377104771057710677107771087710977110771117711277113771147711577116771177711877119771207712177122771237712477125771267712777128771297713077131771327713377134771357713677137771387713977140771417714277143771447714577146771477714877149771507715177152771537715477155771567715777158771597716077161771627716377164771657716677167771687716977170771717717277173771747717577176771777717877179771807718177182771837718477185771867718777188771897719077191771927719377194771957719677197771987719977200772017720277203772047720577206772077720877209772107721177212772137721477215772167721777218772197722077221772227722377224772257722677227772287722977230772317723277233772347723577236772377723877239772407724177242772437724477245772467724777248772497725077251772527725377254772557725677257772587725977260772617726277263772647726577266772677726877269772707727177272772737727477275772767727777278772797728077281772827728377284772857728677287772887728977290772917729277293772947729577296772977729877299773007730177302773037730477305773067730777308773097731077311773127731377314773157731677317773187731977320773217732277323773247732577326773277732877329773307733177332773337733477335773367733777338773397734077341773427734377344773457734677347773487734977350773517735277353773547735577356773577735877359773607736177362773637736477365773667736777368773697737077371773727737377374773757737677377773787737977380773817738277383773847738577386773877738877389773907739177392773937739477395773967739777398773997740077401774027740377404774057740677407774087740977410774117741277413774147741577416774177741877419774207742177422774237742477425774267742777428774297743077431774327743377434774357743677437774387743977440774417744277443774447744577446774477744877449774507745177452774537745477455774567745777458774597746077461774627746377464774657746677467774687746977470774717747277473774747747577476774777747877479774807748177482774837748477485774867748777488774897749077491774927749377494774957749677497774987749977500775017750277503775047750577506775077750877509775107751177512775137751477515775167751777518775197752077521775227752377524775257752677527775287752977530775317753277533775347753577536775377753877539775407754177542775437754477545775467754777548775497755077551775527755377554775557755677557775587755977560775617756277563775647756577566775677756877569775707757177572775737757477575775767757777578775797758077581775827758377584775857758677587775887758977590775917759277593775947759577596775977759877599776007760177602776037760477605776067760777608776097761077611776127761377614776157761677617776187761977620776217762277623776247762577626776277762877629776307763177632776337763477635776367763777638776397764077641776427764377644776457764677647776487764977650776517765277653776547765577656776577765877659776607766177662776637766477665776667766777668776697767077671776727767377674776757767677677776787767977680776817768277683776847768577686776877768877689776907769177692776937769477695776967769777698776997770077701777027770377704777057770677707777087770977710777117771277713777147771577716777177771877719777207772177722777237772477725777267772777728777297773077731777327773377734777357773677737777387773977740777417774277743777447774577746777477774877749777507775177752777537775477755777567775777758777597776077761777627776377764777657776677767777687776977770777717777277773777747777577776777777777877779777807778177782777837778477785777867778777788777897779077791777927779377794777957779677797777987779977800778017780277803778047780577806778077780877809778107781177812778137781477815778167781777818778197782077821778227782377824778257782677827778287782977830778317783277833778347783577836778377783877839778407784177842778437784477845778467784777848778497785077851778527785377854778557785677857778587785977860778617786277863778647786577866778677786877869778707787177872778737787477875778767787777878778797788077881778827788377884778857788677887778887788977890778917789277893778947789577896778977789877899779007790177902779037790477905779067790777908779097791077911779127791377914779157791677917779187791977920779217792277923779247792577926779277792877929779307793177932779337793477935779367793777938779397794077941779427794377944779457794677947779487794977950779517795277953779547795577956779577795877959779607796177962779637796477965779667796777968779697797077971779727797377974779757797677977779787797977980779817798277983779847798577986779877798877989779907799177992779937799477995779967799777998779997800078001780027800378004780057800678007780087800978010780117801278013780147801578016780177801878019780207802178022780237802478025780267802778028780297803078031780327803378034780357803678037780387803978040780417804278043780447804578046780477804878049780507805178052780537805478055780567805778058780597806078061780627806378064780657806678067780687806978070780717807278073780747807578076780777807878079780807808178082780837808478085780867808778088780897809078091780927809378094780957809678097780987809978100781017810278103781047810578106781077810878109781107811178112781137811478115781167811778118781197812078121781227812378124781257812678127781287812978130781317813278133781347813578136781377813878139781407814178142781437814478145781467814778148781497815078151781527815378154781557815678157781587815978160781617816278163781647816578166781677816878169781707817178172781737817478175781767817778178781797818078181781827818378184781857818678187781887818978190781917819278193781947819578196781977819878199782007820178202782037820478205782067820778208782097821078211782127821378214782157821678217782187821978220782217822278223782247822578226782277822878229782307823178232782337823478235782367823778238782397824078241782427824378244782457824678247782487824978250782517825278253782547825578256782577825878259782607826178262782637826478265782667826778268782697827078271782727827378274782757827678277782787827978280782817828278283782847828578286782877828878289782907829178292782937829478295782967829778298782997830078301783027830378304783057830678307783087830978310783117831278313783147831578316783177831878319783207832178322783237832478325783267832778328783297833078331783327833378334783357833678337783387833978340783417834278343783447834578346783477834878349783507835178352783537835478355783567835778358783597836078361783627836378364783657836678367783687836978370783717837278373783747837578376783777837878379783807838178382783837838478385783867838778388783897839078391783927839378394783957839678397783987839978400784017840278403784047840578406784077840878409784107841178412784137841478415784167841778418784197842078421784227842378424784257842678427784287842978430784317843278433784347843578436784377843878439784407844178442784437844478445784467844778448784497845078451784527845378454784557845678457784587845978460784617846278463784647846578466784677846878469784707847178472784737847478475784767847778478784797848078481784827848378484784857848678487784887848978490784917849278493784947849578496784977849878499785007850178502785037850478505785067850778508785097851078511785127851378514785157851678517785187851978520785217852278523785247852578526785277852878529785307853178532785337853478535785367853778538785397854078541785427854378544785457854678547785487854978550785517855278553785547855578556785577855878559785607856178562785637856478565785667856778568785697857078571785727857378574785757857678577785787857978580785817858278583785847858578586785877858878589785907859178592785937859478595785967859778598785997860078601786027860378604786057860678607786087860978610786117861278613786147861578616786177861878619786207862178622786237862478625786267862778628786297863078631786327863378634786357863678637786387863978640786417864278643786447864578646786477864878649786507865178652786537865478655786567865778658786597866078661786627866378664786657866678667786687866978670786717867278673786747867578676786777867878679786807868178682786837868478685786867868778688786897869078691786927869378694786957869678697786987869978700787017870278703787047870578706787077870878709787107871178712787137871478715787167871778718787197872078721787227872378724787257872678727787287872978730787317873278733787347873578736787377873878739787407874178742787437874478745787467874778748787497875078751787527875378754787557875678757787587875978760787617876278763787647876578766787677876878769787707877178772787737877478775787767877778778787797878078781787827878378784787857878678787787887878978790787917879278793787947879578796787977879878799788007880178802788037880478805788067880778808788097881078811788127881378814788157881678817788187881978820788217882278823788247882578826788277882878829788307883178832788337883478835788367883778838788397884078841788427884378844788457884678847788487884978850788517885278853788547885578856788577885878859788607886178862788637886478865788667886778868788697887078871788727887378874788757887678877788787887978880788817888278883788847888578886788877888878889788907889178892788937889478895788967889778898788997890078901789027890378904789057890678907789087890978910789117891278913789147891578916789177891878919789207892178922789237892478925789267892778928789297893078931789327893378934789357893678937789387893978940789417894278943789447894578946789477894878949789507895178952789537895478955789567895778958789597896078961789627896378964789657896678967789687896978970789717897278973789747897578976789777897878979789807898178982789837898478985789867898778988789897899078991789927899378994789957899678997789987899979000790017900279003790047900579006790077900879009790107901179012790137901479015790167901779018790197902079021790227902379024790257902679027790287902979030790317903279033790347903579036790377903879039790407904179042790437904479045790467904779048790497905079051790527905379054790557905679057790587905979060790617906279063790647906579066790677906879069790707907179072790737907479075790767907779078790797908079081790827908379084790857908679087790887908979090790917909279093790947909579096790977909879099791007910179102791037910479105791067910779108791097911079111791127911379114791157911679117791187911979120791217912279123791247912579126791277912879129791307913179132791337913479135791367913779138791397914079141791427914379144791457914679147791487914979150791517915279153791547915579156791577915879159791607916179162791637916479165791667916779168791697917079171791727917379174791757917679177791787917979180791817918279183791847918579186791877918879189791907919179192791937919479195791967919779198791997920079201792027920379204792057920679207792087920979210792117921279213792147921579216792177921879219792207922179222792237922479225792267922779228792297923079231792327923379234792357923679237792387923979240792417924279243792447924579246792477924879249792507925179252792537925479255792567925779258792597926079261792627926379264792657926679267792687926979270792717927279273792747927579276792777927879279792807928179282792837928479285792867928779288792897929079291792927929379294792957929679297792987929979300793017930279303793047930579306793077930879309793107931179312793137931479315793167931779318793197932079321793227932379324793257932679327793287932979330793317933279333793347933579336793377933879339793407934179342793437934479345793467934779348793497935079351793527935379354793557935679357793587935979360793617936279363793647936579366793677936879369793707937179372793737937479375793767937779378793797938079381793827938379384793857938679387793887938979390793917939279393793947939579396793977939879399794007940179402794037940479405794067940779408794097941079411794127941379414794157941679417794187941979420794217942279423794247942579426794277942879429794307943179432794337943479435794367943779438794397944079441794427944379444794457944679447794487944979450794517945279453794547945579456794577945879459794607946179462794637946479465794667946779468794697947079471794727947379474794757947679477794787947979480794817948279483794847948579486794877948879489794907949179492794937949479495794967949779498794997950079501795027950379504795057950679507795087950979510795117951279513795147951579516795177951879519795207952179522795237952479525795267952779528795297953079531795327953379534795357953679537795387953979540795417954279543795447954579546795477954879549795507955179552795537955479555795567955779558795597956079561795627956379564795657956679567795687956979570795717957279573795747957579576795777957879579795807958179582795837958479585795867958779588795897959079591795927959379594795957959679597795987959979600796017960279603796047960579606796077960879609796107961179612796137961479615796167961779618796197962079621796227962379624796257962679627796287962979630796317963279633796347963579636796377963879639796407964179642796437964479645796467964779648796497965079651796527965379654796557965679657796587965979660796617966279663796647966579666796677966879669796707967179672796737967479675796767967779678796797968079681796827968379684796857968679687796887968979690796917969279693796947969579696796977969879699797007970179702797037970479705797067970779708797097971079711797127971379714797157971679717797187971979720797217972279723797247972579726797277972879729797307973179732797337973479735797367973779738797397974079741797427974379744797457974679747797487974979750797517975279753797547975579756797577975879759797607976179762797637976479765797667976779768797697977079771797727977379774797757977679777797787977979780797817978279783797847978579786797877978879789797907979179792797937979479795797967979779798797997980079801798027980379804798057980679807798087980979810798117981279813798147981579816798177981879819798207982179822798237982479825798267982779828798297983079831798327983379834798357983679837798387983979840798417984279843798447984579846798477984879849798507985179852798537985479855
  1. /**
  2. * @license
  3. * Copyright 2010-2025 Three.js Authors
  4. * SPDX-License-Identifier: MIT
  5. */
  6. import { Color, Vector2, Vector3, Vector4, Matrix2, Matrix3, Matrix4, error, EventDispatcher, MathUtils, warn, WebGLCoordinateSystem, WebGPUCoordinateSystem, ColorManagement, SRGBTransfer, NoToneMapping, StaticDrawUsage, InterleavedBufferAttribute, InterleavedBuffer, DynamicDrawUsage, NoColorSpace, log as log$1, warnOnce, Texture, UnsignedIntType, IntType, NearestFilter, Sphere, BackSide, DoubleSide, Euler, CubeTexture, CubeReflectionMapping, CubeRefractionMapping, TangentSpaceNormalMap, ObjectSpaceNormalMap, InstancedInterleavedBuffer, InstancedBufferAttribute, DataArrayTexture, FloatType, FramebufferTexture, LinearMipmapLinearFilter, DepthTexture, Material, LineBasicMaterial, LineDashedMaterial, NoBlending, MeshNormalMaterial, SRGBColorSpace, WebGLCubeRenderTarget, BoxGeometry, Mesh, Scene, LinearFilter, CubeCamera, EquirectangularReflectionMapping, EquirectangularRefractionMapping, AddOperation, MixOperation, MultiplyOperation, MeshBasicMaterial, MeshLambertMaterial, MeshPhongMaterial, DataTexture, RGFormat, HalfFloatType, ClampToEdgeWrapping, BufferGeometry, OrthographicCamera, PerspectiveCamera, RenderTarget, LinearSRGBColorSpace, RGBAFormat, CubeUVReflectionMapping, BufferAttribute, MeshStandardMaterial, MeshPhysicalMaterial, MeshToonMaterial, MeshMatcapMaterial, SpriteMaterial, PointsMaterial, ShadowMaterial, Uint32BufferAttribute, Uint16BufferAttribute, arrayNeedsUint32, Camera, DepthStencilFormat, DepthFormat, UnsignedInt248Type, UnsignedByteType, Plane, Object3D, LinearMipMapLinearFilter, Float32BufferAttribute, UVMapping, VSMShadowMap, LessCompare, BasicShadowMap, SphereGeometry, NormalBlending, LinearMipmapNearestFilter, NearestMipmapLinearFilter, Float16BufferAttribute, REVISION, ArrayCamera, PlaneGeometry, FrontSide, CustomBlending, AddEquation, ZeroFactor, CylinderGeometry, Quaternion, WebXRController, RAD2DEG, PCFShadowMap, FrustumArray, Frustum, RedIntegerFormat, RedFormat, ShortType, ByteType, UnsignedShortType, RGIntegerFormat, RGBIntegerFormat, RGBFormat, RGBAIntegerFormat, TimestampQuery, createCanvasElement, ReverseSubtractEquation, SubtractEquation, OneMinusDstAlphaFactor, OneMinusDstColorFactor, OneMinusSrcAlphaFactor, OneMinusSrcColorFactor, DstAlphaFactor, DstColorFactor, SrcAlphaSaturateFactor, SrcAlphaFactor, SrcColorFactor, OneFactor, CullFaceNone, CullFaceBack, CullFaceFront, MultiplyBlending, SubtractiveBlending, AdditiveBlending, NotEqualDepth, GreaterDepth, GreaterEqualDepth, EqualDepth, LessEqualDepth, LessDepth, AlwaysDepth, NeverDepth, UnsignedShort4444Type, UnsignedShort5551Type, UnsignedInt5999Type, UnsignedInt101111Type, AlphaFormat, 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, MirroredRepeatWrapping, RepeatWrapping, NearestMipmapNearestFilter, NotEqualCompare, GreaterCompare, GreaterEqualCompare, EqualCompare, LessEqualCompare, AlwaysCompare, NeverCompare, LinearTransfer, getByteLength, 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, ArrowHelper, AttachedBindMode, Audio, AudioAnalyser, AudioContext, AudioListener, AudioLoader, AxesHelper, BasicDepthPacking, BatchedMesh, Bone, BooleanKeyframeTrack, Box2, Box3, Box3Helper, BoxHelper, BufferGeometryLoader, Cache, CameraHelper, CanvasTexture, CapsuleGeometry, CatmullRomCurve3, CircleGeometry, Clock, ColorKeyframeTrack, CompressedArrayTexture, CompressedCubeTexture, CompressedTexture, CompressedTextureLoader, ConeGeometry, ConstantAlphaFactor, ConstantColorFactor, Controls, CubeTextureLoader, CubicBezierCurve, CubicBezierCurve3, CubicInterpolant, CullFaceFrontBack, Curve, CurvePath, CustomToneMapping, Cylindrical, Data3DTexture, DataTextureLoader, DataUtils, DefaultLoadingManager, DetachedBindMode, DirectionalLightHelper, DiscreteInterpolant, DodecahedronGeometry, DynamicCopyUsage, DynamicReadUsage, EdgesGeometry, EllipseCurve, ExternalTexture, ExtrudeGeometry, Fog, FogExp2, GLBufferAttribute, GLSL1, GLSL3, GridHelper, HemisphereLightHelper, IcosahedronGeometry, ImageBitmapLoader, ImageLoader, ImageUtils, InstancedBufferGeometry, InstancedMesh, Int16BufferAttribute, Int32BufferAttribute, Int8BufferAttribute, Interpolant, InterpolateDiscrete, InterpolateLinear, InterpolateSmooth, InterpolationSamplingMode, InterpolationSamplingType, KeyframeTrack, LOD, LatheGeometry, Layers, Light, Line, Line3, LineCurve, LineCurve3, LineLoop, LineSegments, LinearInterpolant, LinearMipMapNearestFilter, LoaderUtils, LoadingManager, LoopOnce, LoopPingPong, LoopRepeat, MOUSE, MeshDepthMaterial, MeshDistanceMaterial, NearestMipMapLinearFilter, NearestMipMapNearestFilter, NormalAnimationBlendMode, NumberKeyframeTrack, OctahedronGeometry, OneMinusConstantAlphaFactor, OneMinusConstantColorFactor, PCFSoftShadowMap, Path, PlaneHelper, PointLightHelper, Points, PolarGridHelper, PolyhedronGeometry, PositionalAudio, PropertyBinding, PropertyMixer, QuadraticBezierCurve, QuadraticBezierCurve3, QuaternionKeyframeTrack, QuaternionLinearInterpolant, RGBADepthPacking, RGBDepthPacking, RGB_BPTC_SIGNED_Format, RGB_BPTC_UNSIGNED_Format, RGDepthPacking, RawShaderMaterial, Ray, Raycaster, RenderTarget3D, RingGeometry, ShaderMaterial, Shape, ShapeGeometry, ShapePath, ShapeUtils, Skeleton, SkeletonHelper, SkinnedMesh, Source, Spherical, SphericalHarmonics3, SplineCurve, SpotLightHelper, Sprite, StaticCopyUsage, StaticReadUsage, StereoCamera, StreamCopyUsage, StreamDrawUsage, StreamReadUsage, StringKeyframeTrack, TOUCH, TetrahedronGeometry, TextureLoader, TextureUtils, Timer, TorusGeometry, TorusKnotGeometry, Triangle, TriangleFanDrawMode, TriangleStripDrawMode, TrianglesDrawMode, TubeGeometry, Uint8BufferAttribute, Uint8ClampedBufferAttribute, Uniform, UniformsGroup, VectorKeyframeTrack, VideoFrameTexture, VideoTexture, WebGL3DRenderTarget, WebGLArrayRenderTarget, WebGLRenderTarget, WireframeGeometry, WrapAroundEnding, ZeroCurvatureEnding, ZeroSlopeEnding, getConsoleFunction, setConsoleFunction } from './three.core.js';
  8. const refreshUniforms = [
  9. 'alphaMap',
  10. 'alphaTest',
  11. 'anisotropy',
  12. 'anisotropyMap',
  13. 'anisotropyRotation',
  14. 'aoMap',
  15. 'aoMapIntensity',
  16. 'attenuationColor',
  17. 'attenuationDistance',
  18. 'bumpMap',
  19. 'clearcoat',
  20. 'clearcoatMap',
  21. 'clearcoatNormalMap',
  22. 'clearcoatNormalScale',
  23. 'clearcoatRoughness',
  24. 'color',
  25. 'dispersion',
  26. 'displacementMap',
  27. 'emissive',
  28. 'emissiveIntensity',
  29. 'emissiveMap',
  30. 'envMap',
  31. 'envMapIntensity',
  32. 'gradientMap',
  33. 'ior',
  34. 'iridescence',
  35. 'iridescenceIOR',
  36. 'iridescenceMap',
  37. 'iridescenceThicknessMap',
  38. 'lightMap',
  39. 'lightMapIntensity',
  40. 'map',
  41. 'matcap',
  42. 'metalness',
  43. 'metalnessMap',
  44. 'normalMap',
  45. 'normalScale',
  46. 'opacity',
  47. 'roughness',
  48. 'roughnessMap',
  49. 'sheen',
  50. 'sheenColor',
  51. 'sheenColorMap',
  52. 'sheenRoughnessMap',
  53. 'shininess',
  54. 'specular',
  55. 'specularColor',
  56. 'specularColorMap',
  57. 'specularIntensity',
  58. 'specularIntensityMap',
  59. 'specularMap',
  60. 'thickness',
  61. 'transmission',
  62. 'transmissionMap'
  63. ];
  64. /**
  65. * A WeakMap to cache lights data for node materials.
  66. * Cache lights data by render ID to avoid unnecessary recalculations.
  67. *
  68. * @private
  69. * @type {WeakMap<LightsNode,Object>}
  70. */
  71. const _lightsCache = new WeakMap();
  72. /**
  73. * This class is used by {@link WebGPURenderer} as management component.
  74. * It's primary purpose is to determine whether render objects require a
  75. * refresh right before they are going to be rendered or not.
  76. */
  77. class NodeMaterialObserver {
  78. /**
  79. * Constructs a new node material observer.
  80. *
  81. * @param {NodeBuilder} builder - The node builder.
  82. */
  83. constructor( builder ) {
  84. /**
  85. * A node material can be used by more than one render object so the
  86. * monitor must maintain a list of render objects.
  87. *
  88. * @type {WeakMap<RenderObject,Object>}
  89. */
  90. this.renderObjects = new WeakMap();
  91. /**
  92. * Whether the material uses node objects or not.
  93. *
  94. * @type {boolean}
  95. */
  96. this.hasNode = this.containsNode( builder );
  97. /**
  98. * Whether the node builder's 3D object is animated or not.
  99. *
  100. * @type {boolean}
  101. */
  102. this.hasAnimation = builder.object.isSkinnedMesh === true;
  103. /**
  104. * A list of all possible material uniforms
  105. *
  106. * @type {Array<string>}
  107. */
  108. this.refreshUniforms = refreshUniforms;
  109. /**
  110. * Holds the current render ID from the node frame.
  111. *
  112. * @type {number}
  113. * @default 0
  114. */
  115. this.renderId = 0;
  116. }
  117. /**
  118. * Returns `true` if the given render object is verified for the first time of this observer.
  119. *
  120. * @param {RenderObject} renderObject - The render object.
  121. * @return {boolean} Whether the given render object is verified for the first time of this observer.
  122. */
  123. firstInitialization( renderObject ) {
  124. const hasInitialized = this.renderObjects.has( renderObject );
  125. if ( hasInitialized === false ) {
  126. this.getRenderObjectData( renderObject );
  127. return true;
  128. }
  129. return false;
  130. }
  131. /**
  132. * Returns `true` if the current rendering produces motion vectors.
  133. *
  134. * @param {Renderer} renderer - The renderer.
  135. * @return {boolean} Whether the current rendering produces motion vectors or not.
  136. */
  137. needsVelocity( renderer ) {
  138. const mrt = renderer.getMRT();
  139. return ( mrt !== null && mrt.has( 'velocity' ) );
  140. }
  141. /**
  142. * Returns monitoring data for the given render object.
  143. *
  144. * @param {RenderObject} renderObject - The render object.
  145. * @return {Object} The monitoring data.
  146. */
  147. getRenderObjectData( renderObject ) {
  148. let data = this.renderObjects.get( renderObject );
  149. if ( data === undefined ) {
  150. const { geometry, material, object } = renderObject;
  151. data = {
  152. material: this.getMaterialData( material ),
  153. geometry: {
  154. id: geometry.id,
  155. attributes: this.getAttributesData( geometry.attributes ),
  156. indexVersion: geometry.index ? geometry.index.version : null,
  157. drawRange: { start: geometry.drawRange.start, count: geometry.drawRange.count }
  158. },
  159. worldMatrix: object.matrixWorld.clone()
  160. };
  161. if ( object.center ) {
  162. data.center = object.center.clone();
  163. }
  164. if ( object.morphTargetInfluences ) {
  165. data.morphTargetInfluences = object.morphTargetInfluences.slice();
  166. }
  167. if ( renderObject.bundle !== null ) {
  168. data.version = renderObject.bundle.version;
  169. }
  170. if ( data.material.transmission > 0 ) {
  171. const { width, height } = renderObject.context;
  172. data.bufferWidth = width;
  173. data.bufferHeight = height;
  174. }
  175. data.lights = this.getLightsData( renderObject.lightsNode.getLights() );
  176. this.renderObjects.set( renderObject, data );
  177. }
  178. return data;
  179. }
  180. /**
  181. * Returns an attribute data structure holding the attributes versions for
  182. * monitoring.
  183. *
  184. * @param {Object} attributes - The geometry attributes.
  185. * @return {Object} An object for monitoring the versions of attributes.
  186. */
  187. getAttributesData( attributes ) {
  188. const attributesData = {};
  189. for ( const name in attributes ) {
  190. const attribute = attributes[ name ];
  191. attributesData[ name ] = {
  192. version: attribute.version
  193. };
  194. }
  195. return attributesData;
  196. }
  197. /**
  198. * Returns `true` if the node builder's material uses
  199. * node properties.
  200. *
  201. * @param {NodeBuilder} builder - The current node builder.
  202. * @return {boolean} Whether the node builder's material uses node properties or not.
  203. */
  204. containsNode( builder ) {
  205. const material = builder.material;
  206. for ( const property in material ) {
  207. if ( material[ property ] && material[ property ].isNode )
  208. return true;
  209. }
  210. if ( builder.renderer.overrideNodes.modelViewMatrix !== null || builder.renderer.overrideNodes.modelNormalViewMatrix !== null )
  211. return true;
  212. return false;
  213. }
  214. /**
  215. * Returns a material data structure holding the material property values for
  216. * monitoring.
  217. *
  218. * @param {Material} material - The material.
  219. * @return {Object} An object for monitoring material properties.
  220. */
  221. getMaterialData( material ) {
  222. const data = {};
  223. for ( const property of this.refreshUniforms ) {
  224. const value = material[ property ];
  225. if ( value === null || value === undefined ) continue;
  226. if ( typeof value === 'object' && value.clone !== undefined ) {
  227. if ( value.isTexture === true ) {
  228. data[ property ] = { id: value.id, version: value.version };
  229. } else {
  230. data[ property ] = value.clone();
  231. }
  232. } else {
  233. data[ property ] = value;
  234. }
  235. }
  236. return data;
  237. }
  238. /**
  239. * Returns `true` if the given render object has not changed its state.
  240. *
  241. * @param {RenderObject} renderObject - The render object.
  242. * @param {Array<Light>} lightsData - The current material lights.
  243. * @return {boolean} Whether the given render object has changed its state or not.
  244. */
  245. equals( renderObject, lightsData ) {
  246. const { object, material, geometry } = renderObject;
  247. const renderObjectData = this.getRenderObjectData( renderObject );
  248. // world matrix
  249. if ( renderObjectData.worldMatrix.equals( object.matrixWorld ) !== true ) {
  250. renderObjectData.worldMatrix.copy( object.matrixWorld );
  251. return false;
  252. }
  253. // material
  254. const materialData = renderObjectData.material;
  255. for ( const property in materialData ) {
  256. const value = materialData[ property ];
  257. const mtlValue = material[ property ];
  258. if ( value.equals !== undefined ) {
  259. if ( value.equals( mtlValue ) === false ) {
  260. value.copy( mtlValue );
  261. return false;
  262. }
  263. } else if ( mtlValue.isTexture === true ) {
  264. if ( value.id !== mtlValue.id || value.version !== mtlValue.version ) {
  265. value.id = mtlValue.id;
  266. value.version = mtlValue.version;
  267. return false;
  268. }
  269. } else if ( value !== mtlValue ) {
  270. materialData[ property ] = mtlValue;
  271. return false;
  272. }
  273. }
  274. if ( materialData.transmission > 0 ) {
  275. const { width, height } = renderObject.context;
  276. if ( renderObjectData.bufferWidth !== width || renderObjectData.bufferHeight !== height ) {
  277. renderObjectData.bufferWidth = width;
  278. renderObjectData.bufferHeight = height;
  279. return false;
  280. }
  281. }
  282. // geometry
  283. const storedGeometryData = renderObjectData.geometry;
  284. const attributes = geometry.attributes;
  285. const storedAttributes = storedGeometryData.attributes;
  286. const storedAttributeNames = Object.keys( storedAttributes );
  287. const currentAttributeNames = Object.keys( attributes );
  288. if ( storedGeometryData.id !== geometry.id ) {
  289. storedGeometryData.id = geometry.id;
  290. return false;
  291. }
  292. if ( storedAttributeNames.length !== currentAttributeNames.length ) {
  293. renderObjectData.geometry.attributes = this.getAttributesData( attributes );
  294. return false;
  295. }
  296. // compare each attribute
  297. for ( const name of storedAttributeNames ) {
  298. const storedAttributeData = storedAttributes[ name ];
  299. const attribute = attributes[ name ];
  300. if ( attribute === undefined ) {
  301. // attribute was removed
  302. delete storedAttributes[ name ];
  303. return false;
  304. }
  305. if ( storedAttributeData.version !== attribute.version ) {
  306. storedAttributeData.version = attribute.version;
  307. return false;
  308. }
  309. }
  310. // check index
  311. const index = geometry.index;
  312. const storedIndexVersion = storedGeometryData.indexVersion;
  313. const currentIndexVersion = index ? index.version : null;
  314. if ( storedIndexVersion !== currentIndexVersion ) {
  315. storedGeometryData.indexVersion = currentIndexVersion;
  316. return false;
  317. }
  318. // check drawRange
  319. if ( storedGeometryData.drawRange.start !== geometry.drawRange.start || storedGeometryData.drawRange.count !== geometry.drawRange.count ) {
  320. storedGeometryData.drawRange.start = geometry.drawRange.start;
  321. storedGeometryData.drawRange.count = geometry.drawRange.count;
  322. return false;
  323. }
  324. // morph targets
  325. if ( renderObjectData.morphTargetInfluences ) {
  326. let morphChanged = false;
  327. for ( let i = 0; i < renderObjectData.morphTargetInfluences.length; i ++ ) {
  328. if ( renderObjectData.morphTargetInfluences[ i ] !== object.morphTargetInfluences[ i ] ) {
  329. renderObjectData.morphTargetInfluences[ i ] = object.morphTargetInfluences[ i ];
  330. morphChanged = true;
  331. }
  332. }
  333. if ( morphChanged ) return false;
  334. }
  335. // lights
  336. if ( renderObjectData.lights ) {
  337. for ( let i = 0; i < lightsData.length; i ++ ) {
  338. if ( renderObjectData.lights[ i ].map !== lightsData[ i ].map ) {
  339. return false;
  340. }
  341. }
  342. }
  343. // center
  344. if ( renderObjectData.center ) {
  345. if ( renderObjectData.center.equals( object.center ) === false ) {
  346. renderObjectData.center.copy( object.center );
  347. return true;
  348. }
  349. }
  350. // bundle
  351. if ( renderObject.bundle !== null ) {
  352. renderObjectData.version = renderObject.bundle.version;
  353. }
  354. return true;
  355. }
  356. /**
  357. * Returns the lights data for the given material lights.
  358. *
  359. * @param {Array<Light>} materialLights - The material lights.
  360. * @return {Array<Object>} The lights data for the given material lights.
  361. */
  362. getLightsData( materialLights ) {
  363. const lights = [];
  364. for ( const light of materialLights ) {
  365. if ( light.isSpotLight === true && light.map !== null ) {
  366. // only add lights that have a map
  367. lights.push( { map: light.map.version } );
  368. }
  369. }
  370. return lights;
  371. }
  372. /**
  373. * Returns the lights for the given lights node and render ID.
  374. *
  375. * @param {LightsNode} lightsNode - The lights node.
  376. * @param {number} renderId - The render ID.
  377. * @return {Array<Object>} The lights for the given lights node and render ID.
  378. */
  379. getLights( lightsNode, renderId ) {
  380. if ( _lightsCache.has( lightsNode ) ) {
  381. const cached = _lightsCache.get( lightsNode );
  382. if ( cached.renderId === renderId ) {
  383. return cached.lightsData;
  384. }
  385. }
  386. const lightsData = this.getLightsData( lightsNode.getLights() );
  387. _lightsCache.set( lightsNode, { renderId, lightsData } );
  388. return lightsData;
  389. }
  390. /**
  391. * Checks if the given render object requires a refresh.
  392. *
  393. * @param {RenderObject} renderObject - The render object.
  394. * @param {NodeFrame} nodeFrame - The current node frame.
  395. * @return {boolean} Whether the given render object requires a refresh or not.
  396. */
  397. needsRefresh( renderObject, nodeFrame ) {
  398. if ( this.hasNode || this.hasAnimation || this.firstInitialization( renderObject ) || this.needsVelocity( nodeFrame.renderer ) )
  399. return true;
  400. const { renderId } = nodeFrame;
  401. if ( this.renderId !== renderId ) {
  402. this.renderId = renderId;
  403. return true;
  404. }
  405. const isStatic = renderObject.object.static === true;
  406. const isBundle = renderObject.bundle !== null && renderObject.bundle.static === true && this.getRenderObjectData( renderObject ).version === renderObject.bundle.version;
  407. if ( isStatic || isBundle )
  408. return false;
  409. const lightsData = this.getLights( renderObject.lightsNode, renderId );
  410. const notEqual = this.equals( renderObject, lightsData ) !== true;
  411. return notEqual;
  412. }
  413. }
  414. // cyrb53 (c) 2018 bryc (github.com/bryc). License: Public domain. Attribution appreciated.
  415. // A fast and simple 64-bit (or 53-bit) string hash function with decent collision resistance.
  416. // Largely inspired by MurmurHash2/3, but with a focus on speed/simplicity.
  417. // See https://stackoverflow.com/questions/7616461/generate-a-hash-from-string-in-javascript/52171480#52171480
  418. // https://github.com/bryc/code/blob/master/jshash/experimental/cyrb53.js
  419. function cyrb53( value, seed = 0 ) {
  420. let h1 = 0xdeadbeef ^ seed, h2 = 0x41c6ce57 ^ seed;
  421. if ( value instanceof Array ) {
  422. for ( let i = 0, val; i < value.length; i ++ ) {
  423. val = value[ i ];
  424. h1 = Math.imul( h1 ^ val, 2654435761 );
  425. h2 = Math.imul( h2 ^ val, 1597334677 );
  426. }
  427. } else {
  428. for ( let i = 0, ch; i < value.length; i ++ ) {
  429. ch = value.charCodeAt( i );
  430. h1 = Math.imul( h1 ^ ch, 2654435761 );
  431. h2 = Math.imul( h2 ^ ch, 1597334677 );
  432. }
  433. }
  434. h1 = Math.imul( h1 ^ ( h1 >>> 16 ), 2246822507 );
  435. h1 ^= Math.imul( h2 ^ ( h2 >>> 13 ), 3266489909 );
  436. h2 = Math.imul( h2 ^ ( h2 >>> 16 ), 2246822507 );
  437. h2 ^= Math.imul( h1 ^ ( h1 >>> 13 ), 3266489909 );
  438. return 4294967296 * ( 2097151 & h2 ) + ( h1 >>> 0 );
  439. }
  440. /**
  441. * Computes a hash for the given string.
  442. *
  443. * @private
  444. * @method
  445. * @param {string} str - The string to be hashed.
  446. * @return {number} The hash.
  447. */
  448. const hashString = ( str ) => cyrb53( str );
  449. /**
  450. * Computes a hash for the given array.
  451. *
  452. * @private
  453. * @method
  454. * @param {Array<number>} array - The array to be hashed.
  455. * @return {number} The hash.
  456. */
  457. const hashArray = ( array ) => cyrb53( array );
  458. /**
  459. * Computes a hash for the given list of parameters.
  460. *
  461. * @private
  462. * @method
  463. * @param {...number} params - A list of parameters.
  464. * @return {number} The hash.
  465. */
  466. const hash$1 = ( ...params ) => cyrb53( params );
  467. const typeFromLength = /*@__PURE__*/ new Map( [
  468. [ 1, 'float' ],
  469. [ 2, 'vec2' ],
  470. [ 3, 'vec3' ],
  471. [ 4, 'vec4' ],
  472. [ 9, 'mat3' ],
  473. [ 16, 'mat4' ]
  474. ] );
  475. const dataFromObject = /*@__PURE__*/ new WeakMap();
  476. /**
  477. * Returns the data type for the given the length.
  478. *
  479. * @private
  480. * @method
  481. * @param {number} length - The length.
  482. * @return {string} The data type.
  483. */
  484. function getTypeFromLength( length ) {
  485. return typeFromLength.get( length );
  486. }
  487. /**
  488. * Returns the typed array for the given data type.
  489. *
  490. * @private
  491. * @method
  492. * @param {string} type - The data type.
  493. * @return {TypedArray} The typed array.
  494. */
  495. function getTypedArrayFromType( type ) {
  496. // Handle component type for vectors and matrices
  497. if ( /[iu]?vec\d/.test( type ) ) {
  498. // Handle int vectors
  499. if ( type.startsWith( 'ivec' ) ) return Int32Array;
  500. // Handle uint vectors
  501. if ( type.startsWith( 'uvec' ) ) return Uint32Array;
  502. // Default to float vectors
  503. return Float32Array;
  504. }
  505. // Handle matrices (always float)
  506. if ( /mat\d/.test( type ) ) return Float32Array;
  507. // Basic types
  508. if ( /float/.test( type ) ) return Float32Array;
  509. if ( /uint/.test( type ) ) return Uint32Array;
  510. if ( /int/.test( type ) ) return Int32Array;
  511. throw new Error( `THREE.NodeUtils: Unsupported type: ${type}` );
  512. }
  513. /**
  514. * Returns the length for the given data type.
  515. *
  516. * @private
  517. * @method
  518. * @param {string} type - The data type.
  519. * @return {number} The length.
  520. */
  521. function getLengthFromType( type ) {
  522. if ( /float|int|uint/.test( type ) ) return 1;
  523. if ( /vec2/.test( type ) ) return 2;
  524. if ( /vec3/.test( type ) ) return 3;
  525. if ( /vec4/.test( type ) ) return 4;
  526. if ( /mat2/.test( type ) ) return 4;
  527. if ( /mat3/.test( type ) ) return 9;
  528. if ( /mat4/.test( type ) ) return 16;
  529. error( 'TSL: Unsupported type:', type );
  530. }
  531. /**
  532. * Returns the gpu memory length for the given data type.
  533. *
  534. * @private
  535. * @method
  536. * @param {string} type - The data type.
  537. * @return {number} The length.
  538. */
  539. function getMemoryLengthFromType( type ) {
  540. if ( /float|int|uint/.test( type ) ) return 1;
  541. if ( /vec2/.test( type ) ) return 2;
  542. if ( /vec3/.test( type ) ) return 3;
  543. if ( /vec4/.test( type ) ) return 4;
  544. if ( /mat2/.test( type ) ) return 4;
  545. if ( /mat3/.test( type ) ) return 12;
  546. if ( /mat4/.test( type ) ) return 16;
  547. error( 'TSL: Unsupported type:', type );
  548. }
  549. /**
  550. * Returns the byte boundary for the given data type.
  551. *
  552. * @private
  553. * @method
  554. * @param {string} type - The data type.
  555. * @return {number} The byte boundary.
  556. */
  557. function getByteBoundaryFromType( type ) {
  558. if ( /float|int|uint/.test( type ) ) return 4;
  559. if ( /vec2/.test( type ) ) return 8;
  560. if ( /vec3/.test( type ) ) return 16;
  561. if ( /vec4/.test( type ) ) return 16;
  562. if ( /mat2/.test( type ) ) return 8;
  563. if ( /mat3/.test( type ) ) return 48;
  564. if ( /mat4/.test( type ) ) return 64;
  565. error( 'TSL: Unsupported type:', type );
  566. }
  567. /**
  568. * Returns the data type for the given value.
  569. *
  570. * @private
  571. * @method
  572. * @param {any} value - The value.
  573. * @return {?string} The data type.
  574. */
  575. function getValueType( value ) {
  576. if ( value === undefined || value === null ) return null;
  577. const typeOf = typeof value;
  578. if ( value.isNode === true ) {
  579. return 'node';
  580. } else if ( typeOf === 'number' ) {
  581. return 'float';
  582. } else if ( typeOf === 'boolean' ) {
  583. return 'bool';
  584. } else if ( typeOf === 'string' ) {
  585. return 'string';
  586. } else if ( typeOf === 'function' ) {
  587. return 'shader';
  588. } else if ( value.isVector2 === true ) {
  589. return 'vec2';
  590. } else if ( value.isVector3 === true ) {
  591. return 'vec3';
  592. } else if ( value.isVector4 === true ) {
  593. return 'vec4';
  594. } else if ( value.isMatrix2 === true ) {
  595. return 'mat2';
  596. } else if ( value.isMatrix3 === true ) {
  597. return 'mat3';
  598. } else if ( value.isMatrix4 === true ) {
  599. return 'mat4';
  600. } else if ( value.isColor === true ) {
  601. return 'color';
  602. } else if ( value instanceof ArrayBuffer ) {
  603. return 'ArrayBuffer';
  604. }
  605. return null;
  606. }
  607. /**
  608. * Returns the value/object for the given data type and parameters.
  609. *
  610. * @private
  611. * @method
  612. * @param {string} type - The given type.
  613. * @param {...any} params - A parameter list.
  614. * @return {any} The value/object.
  615. */
  616. function getValueFromType( type, ...params ) {
  617. const last4 = type ? type.slice( -4 ) : undefined;
  618. if ( params.length === 1 ) { // ensure same behaviour as in NodeBuilder.format()
  619. if ( last4 === 'vec2' ) params = [ params[ 0 ], params[ 0 ] ];
  620. else if ( last4 === 'vec3' ) params = [ params[ 0 ], params[ 0 ], params[ 0 ] ];
  621. else if ( last4 === 'vec4' ) params = [ params[ 0 ], params[ 0 ], params[ 0 ], params[ 0 ] ];
  622. }
  623. if ( type === 'color' ) {
  624. return new Color( ...params );
  625. } else if ( last4 === 'vec2' ) {
  626. return new Vector2( ...params );
  627. } else if ( last4 === 'vec3' ) {
  628. return new Vector3( ...params );
  629. } else if ( last4 === 'vec4' ) {
  630. return new Vector4( ...params );
  631. } else if ( last4 === 'mat2' ) {
  632. return new Matrix2( ...params );
  633. } else if ( last4 === 'mat3' ) {
  634. return new Matrix3( ...params );
  635. } else if ( last4 === 'mat4' ) {
  636. return new Matrix4( ...params );
  637. } else if ( type === 'bool' ) {
  638. return params[ 0 ] || false;
  639. } else if ( ( type === 'float' ) || ( type === 'int' ) || ( type === 'uint' ) ) {
  640. return params[ 0 ] || 0;
  641. } else if ( type === 'string' ) {
  642. return params[ 0 ] || '';
  643. } else if ( type === 'ArrayBuffer' ) {
  644. return base64ToArrayBuffer( params[ 0 ] );
  645. }
  646. return null;
  647. }
  648. /**
  649. * Gets the object data that can be shared between different rendering steps.
  650. *
  651. * @private
  652. * @param {Object} object - The object to get the data for.
  653. * @return {Object} The object data.
  654. */
  655. function getDataFromObject( object ) {
  656. let data = dataFromObject.get( object );
  657. if ( data === undefined ) {
  658. data = {};
  659. dataFromObject.set( object, data );
  660. }
  661. return data;
  662. }
  663. /**
  664. * Converts the given array buffer to a Base64 string.
  665. *
  666. * @private
  667. * @method
  668. * @param {ArrayBuffer} arrayBuffer - The array buffer.
  669. * @return {string} The Base64 string.
  670. */
  671. function arrayBufferToBase64( arrayBuffer ) {
  672. let chars = '';
  673. const array = new Uint8Array( arrayBuffer );
  674. for ( let i = 0; i < array.length; i ++ ) {
  675. chars += String.fromCharCode( array[ i ] );
  676. }
  677. return btoa( chars );
  678. }
  679. /**
  680. * Converts the given Base64 string to an array buffer.
  681. *
  682. * @private
  683. * @method
  684. * @param {string} base64 - The Base64 string.
  685. * @return {ArrayBuffer} The array buffer.
  686. */
  687. function base64ToArrayBuffer( base64 ) {
  688. return Uint8Array.from( atob( base64 ), c => c.charCodeAt( 0 ) ).buffer;
  689. }
  690. var NodeUtils = /*#__PURE__*/Object.freeze({
  691. __proto__: null,
  692. arrayBufferToBase64: arrayBufferToBase64,
  693. base64ToArrayBuffer: base64ToArrayBuffer,
  694. getByteBoundaryFromType: getByteBoundaryFromType,
  695. getDataFromObject: getDataFromObject,
  696. getLengthFromType: getLengthFromType,
  697. getMemoryLengthFromType: getMemoryLengthFromType,
  698. getTypeFromLength: getTypeFromLength,
  699. getTypedArrayFromType: getTypedArrayFromType,
  700. getValueFromType: getValueFromType,
  701. getValueType: getValueType,
  702. hash: hash$1,
  703. hashArray: hashArray,
  704. hashString: hashString
  705. });
  706. /**
  707. * Possible shader stages.
  708. *
  709. * @property {string} VERTEX The vertex shader stage.
  710. * @property {string} FRAGMENT The fragment shader stage.
  711. */
  712. const NodeShaderStage = {
  713. VERTEX: 'vertex',
  714. FRAGMENT: 'fragment'
  715. };
  716. /**
  717. * Update types of a node.
  718. *
  719. * @property {string} NONE The update method is not executed.
  720. * @property {string} FRAME The update method is executed per frame.
  721. * @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.
  722. * @property {string} OBJECT The update method is executed per {@link Object3D} that uses the node for rendering.
  723. */
  724. const NodeUpdateType = {
  725. NONE: 'none',
  726. FRAME: 'frame',
  727. RENDER: 'render',
  728. OBJECT: 'object'
  729. };
  730. /**
  731. * Data types of a node.
  732. *
  733. * @property {string} BOOLEAN Boolean type.
  734. * @property {string} INTEGER Integer type.
  735. * @property {string} FLOAT Float type.
  736. * @property {string} VECTOR2 Two-dimensional vector type.
  737. * @property {string} VECTOR3 Three-dimensional vector type.
  738. * @property {string} VECTOR4 Four-dimensional vector type.
  739. * @property {string} MATRIX2 2x2 matrix type.
  740. * @property {string} MATRIX3 3x3 matrix type.
  741. * @property {string} MATRIX4 4x4 matrix type.
  742. */
  743. const NodeType = {
  744. BOOLEAN: 'bool',
  745. INTEGER: 'int',
  746. FLOAT: 'float',
  747. VECTOR2: 'vec2',
  748. VECTOR3: 'vec3',
  749. VECTOR4: 'vec4',
  750. MATRIX2: 'mat2',
  751. MATRIX3: 'mat3',
  752. MATRIX4: 'mat4'
  753. };
  754. /**
  755. * Access types of a node. These are relevant for compute and storage usage.
  756. *
  757. * @property {string} READ_ONLY Read-only access
  758. * @property {string} WRITE_ONLY Write-only access.
  759. * @property {string} READ_WRITE Read and write access.
  760. */
  761. const NodeAccess = {
  762. READ_ONLY: 'readOnly',
  763. WRITE_ONLY: 'writeOnly',
  764. READ_WRITE: 'readWrite',
  765. };
  766. const defaultShaderStages = [ 'fragment', 'vertex' ];
  767. const defaultBuildStages = [ 'setup', 'analyze', 'generate' ];
  768. const shaderStages = [ ...defaultShaderStages, 'compute' ];
  769. const vectorComponents = [ 'x', 'y', 'z', 'w' ];
  770. const _parentBuildStage = {
  771. analyze: 'setup',
  772. generate: 'analyze'
  773. };
  774. let _nodeId = 0;
  775. /**
  776. * Base class for all nodes.
  777. *
  778. * @augments EventDispatcher
  779. */
  780. class Node extends EventDispatcher {
  781. static get type() {
  782. return 'Node';
  783. }
  784. /**
  785. * Constructs a new node.
  786. *
  787. * @param {?string} nodeType - The node type.
  788. */
  789. constructor( nodeType = null ) {
  790. super();
  791. /**
  792. * The node type. This represents the result type of the node (e.g. `float` or `vec3`).
  793. *
  794. * @type {?string}
  795. * @default null
  796. */
  797. this.nodeType = nodeType;
  798. /**
  799. * The update type of the node's {@link Node#update} method. Possible values are listed in {@link NodeUpdateType}.
  800. *
  801. * @type {string}
  802. * @default 'none'
  803. */
  804. this.updateType = NodeUpdateType.NONE;
  805. /**
  806. * The update type of the node's {@link Node#updateBefore} method. Possible values are listed in {@link NodeUpdateType}.
  807. *
  808. * @type {string}
  809. * @default 'none'
  810. */
  811. this.updateBeforeType = NodeUpdateType.NONE;
  812. /**
  813. * The update type of the node's {@link Node#updateAfter} method. Possible values are listed in {@link NodeUpdateType}.
  814. *
  815. * @type {string}
  816. * @default 'none'
  817. */
  818. this.updateAfterType = NodeUpdateType.NONE;
  819. /**
  820. * The UUID of the node.
  821. *
  822. * @type {string}
  823. * @readonly
  824. */
  825. this.uuid = MathUtils.generateUUID();
  826. /**
  827. * The version of the node. The version automatically is increased when {@link Node#needsUpdate} is set to `true`.
  828. *
  829. * @type {number}
  830. * @readonly
  831. * @default 0
  832. */
  833. this.version = 0;
  834. /**
  835. * The name of the node.
  836. *
  837. * @type {string}
  838. * @default ''
  839. */
  840. this.name = '';
  841. /**
  842. * Whether this node is global or not. This property is relevant for the internal
  843. * node caching system. All nodes which should be declared just once should
  844. * set this flag to `true` (a typical example is {@link AttributeNode}).
  845. *
  846. * @type {boolean}
  847. * @default false
  848. */
  849. this.global = false;
  850. /**
  851. * Create a list of parents for this node during the build process.
  852. *
  853. * @type {boolean}
  854. * @default false
  855. */
  856. this.parents = false;
  857. /**
  858. * This flag can be used for type testing.
  859. *
  860. * @type {boolean}
  861. * @readonly
  862. * @default true
  863. */
  864. this.isNode = true;
  865. // private
  866. this._beforeNodes = null;
  867. /**
  868. * The cache key of this node.
  869. *
  870. * @private
  871. * @type {?number}
  872. * @default null
  873. */
  874. this._cacheKey = null;
  875. /**
  876. * The cache key 's version.
  877. *
  878. * @private
  879. * @type {number}
  880. * @default 0
  881. */
  882. this._cacheKeyVersion = 0;
  883. Object.defineProperty( this, 'id', { value: _nodeId ++ } );
  884. }
  885. /**
  886. * Set this property to `true` when the node should be regenerated.
  887. *
  888. * @type {boolean}
  889. * @default false
  890. * @param {boolean} value
  891. */
  892. set needsUpdate( value ) {
  893. if ( value === true ) {
  894. this.version ++;
  895. }
  896. }
  897. /**
  898. * The type of the class. The value is usually the constructor name.
  899. *
  900. * @type {string}
  901. * @readonly
  902. */
  903. get type() {
  904. return this.constructor.type;
  905. }
  906. /**
  907. * Convenient method for defining {@link Node#update}.
  908. *
  909. * @param {Function} callback - The update method.
  910. * @param {string} updateType - The update type.
  911. * @return {Node} A reference to this node.
  912. */
  913. onUpdate( callback, updateType ) {
  914. this.updateType = updateType;
  915. this.update = callback.bind( this );
  916. return this;
  917. }
  918. /**
  919. * Convenient method for defining {@link Node#update}. Similar to {@link Node#onUpdate}, but
  920. * this method automatically sets the update type to `FRAME`.
  921. *
  922. * @param {Function} callback - The update method.
  923. * @return {Node} A reference to this node.
  924. */
  925. onFrameUpdate( callback ) {
  926. return this.onUpdate( callback, NodeUpdateType.FRAME );
  927. }
  928. /**
  929. * Convenient method for defining {@link Node#update}. Similar to {@link Node#onUpdate}, but
  930. * this method automatically sets the update type to `RENDER`.
  931. *
  932. * @param {Function} callback - The update method.
  933. * @return {Node} A reference to this node.
  934. */
  935. onRenderUpdate( callback ) {
  936. return this.onUpdate( callback, NodeUpdateType.RENDER );
  937. }
  938. /**
  939. * Convenient method for defining {@link Node#update}. Similar to {@link Node#onUpdate}, but
  940. * this method automatically sets the update type to `OBJECT`.
  941. *
  942. * @param {Function} callback - The update method.
  943. * @return {Node} A reference to this node.
  944. */
  945. onObjectUpdate( callback ) {
  946. return this.onUpdate( callback, NodeUpdateType.OBJECT );
  947. }
  948. /**
  949. * Convenient method for defining {@link Node#updateReference}.
  950. *
  951. * @param {Function} callback - The update method.
  952. * @return {Node} A reference to this node.
  953. */
  954. onReference( callback ) {
  955. this.updateReference = callback.bind( this );
  956. return this;
  957. }
  958. /**
  959. * Nodes might refer to other objects like materials. This method allows to dynamically update the reference
  960. * to such objects based on a given state (e.g. the current node frame or builder).
  961. *
  962. * @param {any} state - This method can be invocated in different contexts so `state` can refer to any object type.
  963. * @return {any} The updated reference.
  964. */
  965. updateReference( /*state*/ ) {
  966. return this;
  967. }
  968. /**
  969. * By default this method returns the value of the {@link Node#global} flag. This method
  970. * can be overwritten in derived classes if an analytical way is required to determine the
  971. * global cache referring to the current shader-stage.
  972. *
  973. * @param {NodeBuilder} builder - The current node builder.
  974. * @return {boolean} Whether this node is global or not.
  975. */
  976. isGlobal( /*builder*/ ) {
  977. return this.global;
  978. }
  979. /**
  980. * Generator function that can be used to iterate over the child nodes.
  981. *
  982. * @generator
  983. * @yields {Node} A child node.
  984. */
  985. * getChildren() {
  986. for ( const { childNode } of this._getChildren() ) {
  987. yield childNode;
  988. }
  989. }
  990. /**
  991. * Calling this method dispatches the `dispose` event. This event can be used
  992. * to register event listeners for clean up tasks.
  993. */
  994. dispose() {
  995. this.dispatchEvent( { type: 'dispose' } );
  996. }
  997. /**
  998. * Callback for {@link Node#traverse}.
  999. *
  1000. * @callback traverseCallback
  1001. * @param {Node} node - The current node.
  1002. */
  1003. /**
  1004. * Can be used to traverse through the node's hierarchy.
  1005. *
  1006. * @param {traverseCallback} callback - A callback that is executed per node.
  1007. */
  1008. traverse( callback ) {
  1009. callback( this );
  1010. for ( const childNode of this.getChildren() ) {
  1011. childNode.traverse( callback );
  1012. }
  1013. }
  1014. /**
  1015. * Returns the child nodes of this node.
  1016. *
  1017. * @private
  1018. * @param {Set<Node>} [ignores=new Set()] - A set of nodes to ignore during the search to avoid circular references.
  1019. * @returns {Array<Object>} An array of objects describing the child nodes.
  1020. */
  1021. _getChildren( ignores = new Set() ) {
  1022. const children = [];
  1023. // avoid circular references
  1024. ignores.add( this );
  1025. for ( const property of Object.getOwnPropertyNames( this ) ) {
  1026. const object = this[ property ];
  1027. // Ignore private properties and ignored nodes.
  1028. if ( property.startsWith( '_' ) === true || ignores.has( object ) ) continue;
  1029. if ( Array.isArray( object ) === true ) {
  1030. for ( let i = 0; i < object.length; i ++ ) {
  1031. const child = object[ i ];
  1032. if ( child && child.isNode === true ) {
  1033. children.push( { property, index: i, childNode: child } );
  1034. }
  1035. }
  1036. } else if ( object && object.isNode === true ) {
  1037. children.push( { property, childNode: object } );
  1038. } else if ( object && Object.getPrototypeOf( object ) === Object.prototype ) {
  1039. for ( const subProperty in object ) {
  1040. // Ignore private sub-properties.
  1041. if ( subProperty.startsWith( '_' ) === true ) continue;
  1042. const child = object[ subProperty ];
  1043. if ( child && child.isNode === true ) {
  1044. children.push( { property, index: subProperty, childNode: child } );
  1045. }
  1046. }
  1047. }
  1048. }
  1049. //
  1050. return children;
  1051. }
  1052. /**
  1053. * Returns the cache key for this node.
  1054. *
  1055. * @param {boolean} [force=false] - When set to `true`, a recomputation of the cache key is forced.
  1056. * @param {Set<Node>} [ignores=null] - A set of nodes to ignore during the computation of the cache key.
  1057. * @return {number} The cache key of the node.
  1058. */
  1059. getCacheKey( force = false, ignores = null ) {
  1060. force = force || this.version !== this._cacheKeyVersion;
  1061. if ( force === true || this._cacheKey === null ) {
  1062. if ( ignores === null ) ignores = new Set();
  1063. //
  1064. const values = [];
  1065. for ( const { property, childNode } of this._getChildren( ignores ) ) {
  1066. values.push( hashString( property.slice( 0, -4 ) ), childNode.getCacheKey( force, ignores ) );
  1067. }
  1068. //
  1069. this._cacheKey = hash$1( hashArray( values ), this.customCacheKey() );
  1070. this._cacheKeyVersion = this.version;
  1071. }
  1072. return this._cacheKey;
  1073. }
  1074. /**
  1075. * Generate a custom cache key for this node.
  1076. *
  1077. * @return {number} The cache key of the node.
  1078. */
  1079. customCacheKey() {
  1080. return this.id;
  1081. }
  1082. /**
  1083. * Returns the references to this node which is by default `this`.
  1084. *
  1085. * @return {Node} A reference to this node.
  1086. */
  1087. getScope() {
  1088. return this;
  1089. }
  1090. /**
  1091. * Returns the hash of the node which is used to identify the node. By default it's
  1092. * the {@link Node#uuid} however derived node classes might have to overwrite this method
  1093. * depending on their implementation.
  1094. *
  1095. * @param {NodeBuilder} builder - The current node builder.
  1096. * @return {string} The hash.
  1097. */
  1098. getHash( /*builder*/ ) {
  1099. return this.uuid;
  1100. }
  1101. /**
  1102. * Returns the update type of {@link Node#update}.
  1103. *
  1104. * @return {NodeUpdateType} The update type.
  1105. */
  1106. getUpdateType() {
  1107. return this.updateType;
  1108. }
  1109. /**
  1110. * Returns the update type of {@link Node#updateBefore}.
  1111. *
  1112. * @return {NodeUpdateType} The update type.
  1113. */
  1114. getUpdateBeforeType() {
  1115. return this.updateBeforeType;
  1116. }
  1117. /**
  1118. * Returns the update type of {@link Node#updateAfter}.
  1119. *
  1120. * @return {NodeUpdateType} The update type.
  1121. */
  1122. getUpdateAfterType() {
  1123. return this.updateAfterType;
  1124. }
  1125. /**
  1126. * Certain types are composed of multiple elements. For example a `vec3`
  1127. * is composed of three `float` values. This method returns the type of
  1128. * these elements.
  1129. *
  1130. * @param {NodeBuilder} builder - The current node builder.
  1131. * @return {string} The type of the node.
  1132. */
  1133. getElementType( builder ) {
  1134. const type = this.getNodeType( builder );
  1135. const elementType = builder.getElementType( type );
  1136. return elementType;
  1137. }
  1138. /**
  1139. * Returns the node member type for the given name.
  1140. *
  1141. * @param {NodeBuilder} builder - The current node builder.
  1142. * @param {string} name - The name of the member.
  1143. * @return {string} The type of the node.
  1144. */
  1145. getMemberType( /*builder, name*/ ) {
  1146. return 'void';
  1147. }
  1148. /**
  1149. * Returns the node's type.
  1150. *
  1151. * @param {NodeBuilder} builder - The current node builder.
  1152. * @return {string} The type of the node.
  1153. */
  1154. getNodeType( builder ) {
  1155. const nodeProperties = builder.getNodeProperties( this );
  1156. if ( nodeProperties.outputNode ) {
  1157. return nodeProperties.outputNode.getNodeType( builder );
  1158. }
  1159. return this.nodeType;
  1160. }
  1161. /**
  1162. * This method is used during the build process of a node and ensures
  1163. * equal nodes are not built multiple times but just once. For example if
  1164. * `attribute( 'uv' )` is used multiple times by the user, the build
  1165. * process makes sure to process just the first node.
  1166. *
  1167. * @param {NodeBuilder} builder - The current node builder.
  1168. * @return {Node} The shared node if possible. Otherwise `this` is returned.
  1169. */
  1170. getShared( builder ) {
  1171. const hash = this.getHash( builder );
  1172. const nodeFromHash = builder.getNodeFromHash( hash );
  1173. return nodeFromHash || this;
  1174. }
  1175. /**
  1176. * Returns the number of elements in the node array.
  1177. *
  1178. * @param {NodeBuilder} builder - The current node builder.
  1179. * @return {?number} The number of elements in the node array.
  1180. */
  1181. getArrayCount( /*builder*/ ) {
  1182. return null;
  1183. }
  1184. /**
  1185. * Represents the setup stage which is the first step of the build process, see {@link Node#build} method.
  1186. * This method is often overwritten in derived modules to prepare the node which is used as a node's output/result.
  1187. * If an output node is prepared, then it must be returned in the `return` statement of the derived module's setup function.
  1188. *
  1189. * @param {NodeBuilder} builder - The current node builder.
  1190. * @return {?Node} The output node.
  1191. */
  1192. setup( builder ) {
  1193. const nodeProperties = builder.getNodeProperties( this );
  1194. let index = 0;
  1195. for ( const childNode of this.getChildren() ) {
  1196. nodeProperties[ 'node' + index ++ ] = childNode;
  1197. }
  1198. // return a outputNode if exists or null
  1199. return nodeProperties.outputNode || null;
  1200. }
  1201. /**
  1202. * Represents the analyze stage which is the second step of the build process, see {@link Node#build} method.
  1203. * This stage analyzes the node hierarchy and ensures descendent nodes are built.
  1204. *
  1205. * @param {NodeBuilder} builder - The current node builder.
  1206. * @param {?Node} output - The target output node.
  1207. */
  1208. analyze( builder, output = null ) {
  1209. const usageCount = builder.increaseUsage( this );
  1210. if ( this.parents === true ) {
  1211. const nodeData = builder.getDataFromNode( this, 'any' );
  1212. nodeData.stages = nodeData.stages || {};
  1213. nodeData.stages[ builder.shaderStage ] = nodeData.stages[ builder.shaderStage ] || [];
  1214. nodeData.stages[ builder.shaderStage ].push( output );
  1215. }
  1216. if ( usageCount === 1 ) {
  1217. // node flow children
  1218. const nodeProperties = builder.getNodeProperties( this );
  1219. for ( const childNode of Object.values( nodeProperties ) ) {
  1220. if ( childNode && childNode.isNode === true ) {
  1221. childNode.build( builder, this );
  1222. }
  1223. }
  1224. }
  1225. }
  1226. /**
  1227. * Represents the generate stage which is the third step of the build process, see {@link Node#build} method.
  1228. * This state builds the output node and returns the resulting shader string.
  1229. *
  1230. * @param {NodeBuilder} builder - The current node builder.
  1231. * @param {?string} [output] - Can be used to define the output type.
  1232. * @return {?string} The generated shader string.
  1233. */
  1234. generate( builder, output ) {
  1235. const { outputNode } = builder.getNodeProperties( this );
  1236. if ( outputNode && outputNode.isNode === true ) {
  1237. return outputNode.build( builder, output );
  1238. }
  1239. }
  1240. /**
  1241. * The method can be implemented to update the node's internal state before it is used to render an object.
  1242. * The {@link Node#updateBeforeType} property defines how often the update is executed.
  1243. *
  1244. * @abstract
  1245. * @param {NodeFrame} frame - A reference to the current node frame.
  1246. * @return {?boolean} An optional bool that indicates whether the implementation actually performed an update or not (e.g. due to caching).
  1247. */
  1248. updateBefore( /*frame*/ ) {
  1249. warn( 'Abstract function.' );
  1250. }
  1251. /**
  1252. * The method can be implemented to update the node's internal state after it was used to render an object.
  1253. * The {@link Node#updateAfterType} property defines how often the update is executed.
  1254. *
  1255. * @abstract
  1256. * @param {NodeFrame} frame - A reference to the current node frame.
  1257. * @return {?boolean} An optional bool that indicates whether the implementation actually performed an update or not (e.g. due to caching).
  1258. */
  1259. updateAfter( /*frame*/ ) {
  1260. warn( 'Abstract function.' );
  1261. }
  1262. /**
  1263. * The method can be implemented to update the node's internal state when it is used to render an object.
  1264. * The {@link Node#updateType} property defines how often the update is executed.
  1265. *
  1266. * @abstract
  1267. * @param {NodeFrame} frame - A reference to the current node frame.
  1268. * @return {?boolean} An optional bool that indicates whether the implementation actually performed an update or not (e.g. due to caching).
  1269. */
  1270. update( /*frame*/ ) {
  1271. warn( 'Abstract function.' );
  1272. }
  1273. before( node ) {
  1274. if ( this._beforeNodes === null ) this._beforeNodes = [];
  1275. this._beforeNodes.push( node );
  1276. return this;
  1277. }
  1278. /**
  1279. * This method performs the build of a node. The behavior and return value depend on the current build stage:
  1280. * - **setup**: Prepares the node and its children for the build process. This process can also create new nodes. Returns the node itself or a variant.
  1281. * - **analyze**: Analyzes the node hierarchy for optimizations in the code generation stage. Returns `null`.
  1282. * - **generate**: Generates the shader code for the node. Returns the generated shader string.
  1283. *
  1284. * @param {NodeBuilder} builder - The current node builder.
  1285. * @param {?(string|Node)} [output=null] - Can be used to define the output type.
  1286. * @return {?(Node|string)} The result of the build process, depending on the build stage.
  1287. */
  1288. build( builder, output = null ) {
  1289. const refNode = this.getShared( builder );
  1290. if ( this !== refNode ) {
  1291. return refNode.build( builder, output );
  1292. }
  1293. //
  1294. if ( this._beforeNodes !== null ) {
  1295. const currentBeforeNodes = this._beforeNodes;
  1296. this._beforeNodes = null;
  1297. for ( const beforeNode of currentBeforeNodes ) {
  1298. beforeNode.build( builder, output );
  1299. }
  1300. this._beforeNodes = currentBeforeNodes;
  1301. }
  1302. //
  1303. const nodeData = builder.getDataFromNode( this );
  1304. nodeData.buildStages = nodeData.buildStages || {};
  1305. nodeData.buildStages[ builder.buildStage ] = true;
  1306. const parentBuildStage = _parentBuildStage[ builder.buildStage ];
  1307. if ( parentBuildStage && nodeData.buildStages[ parentBuildStage ] !== true ) {
  1308. // force parent build stage (setup or analyze)
  1309. const previousBuildStage = builder.getBuildStage();
  1310. builder.setBuildStage( parentBuildStage );
  1311. this.build( builder );
  1312. builder.setBuildStage( previousBuildStage );
  1313. }
  1314. //
  1315. builder.addNode( this );
  1316. builder.addChain( this );
  1317. /* Build stages expected results:
  1318. - "setup" -> Node
  1319. - "analyze" -> null
  1320. - "generate" -> String
  1321. */
  1322. let result = null;
  1323. const buildStage = builder.getBuildStage();
  1324. if ( buildStage === 'setup' ) {
  1325. this.updateReference( builder );
  1326. const properties = builder.getNodeProperties( this );
  1327. if ( properties.initialized !== true ) {
  1328. //const stackNodesBeforeSetup = builder.stack.nodes.length;
  1329. properties.initialized = true;
  1330. properties.outputNode = this.setup( builder ) || properties.outputNode || null;
  1331. /*if ( isNodeOutput && builder.stack.nodes.length !== stackNodesBeforeSetup ) {
  1332. // !! no outputNode !!
  1333. //outputNode = builder.stack;
  1334. }*/
  1335. for ( const childNode of Object.values( properties ) ) {
  1336. if ( childNode && childNode.isNode === true ) {
  1337. if ( childNode.parents === true ) {
  1338. const childProperties = builder.getNodeProperties( childNode );
  1339. childProperties.parents = childProperties.parents || [];
  1340. childProperties.parents.push( this );
  1341. }
  1342. childNode.build( builder );
  1343. }
  1344. }
  1345. }
  1346. result = properties.outputNode;
  1347. } else if ( buildStage === 'analyze' ) {
  1348. this.analyze( builder, output );
  1349. } else if ( buildStage === 'generate' ) {
  1350. // If generate has just one argument, it means the output type is not required.
  1351. // This means that the node does not handle output conversions internally,
  1352. // so the value is stored in a cache and the builder handles the conversion
  1353. // for all requested output types.
  1354. const isGenerateOnce = this.generate.length < 2;
  1355. if ( isGenerateOnce ) {
  1356. const type = this.getNodeType( builder );
  1357. const nodeData = builder.getDataFromNode( this );
  1358. result = nodeData.snippet;
  1359. if ( result === undefined ) {
  1360. if ( nodeData.generated === undefined ) {
  1361. nodeData.generated = true;
  1362. result = this.generate( builder ) || '';
  1363. nodeData.snippet = result;
  1364. } else {
  1365. warn( 'Node: Recursion detected.', this );
  1366. result = '/* Recursion detected. */';
  1367. }
  1368. } else if ( nodeData.flowCodes !== undefined && builder.context.nodeBlock !== undefined ) {
  1369. builder.addFlowCodeHierarchy( this, builder.context.nodeBlock );
  1370. }
  1371. result = builder.format( result, type, output );
  1372. } else {
  1373. result = this.generate( builder, output ) || '';
  1374. }
  1375. if ( result === '' && output !== null && output !== 'void' && output !== 'OutputType' ) {
  1376. // if no snippet is generated, return a default value
  1377. error( `TSL: Invalid generated code, expected a "${ output }".` );
  1378. result = builder.generateConst( output );
  1379. }
  1380. }
  1381. builder.removeChain( this );
  1382. builder.addSequentialNode( this );
  1383. return result;
  1384. }
  1385. /**
  1386. * Returns the child nodes as a JSON object.
  1387. *
  1388. * @return {Generator<Object>} An iterable list of serialized child objects as JSON.
  1389. */
  1390. getSerializeChildren() {
  1391. return this._getChildren();
  1392. }
  1393. /**
  1394. * Serializes the node to JSON.
  1395. *
  1396. * @param {Object} json - The output JSON object.
  1397. */
  1398. serialize( json ) {
  1399. const nodeChildren = this.getSerializeChildren();
  1400. const inputNodes = {};
  1401. for ( const { property, index, childNode } of nodeChildren ) {
  1402. if ( index !== undefined ) {
  1403. if ( inputNodes[ property ] === undefined ) {
  1404. inputNodes[ property ] = Number.isInteger( index ) ? [] : {};
  1405. }
  1406. inputNodes[ property ][ index ] = childNode.toJSON( json.meta ).uuid;
  1407. } else {
  1408. inputNodes[ property ] = childNode.toJSON( json.meta ).uuid;
  1409. }
  1410. }
  1411. if ( Object.keys( inputNodes ).length > 0 ) {
  1412. json.inputNodes = inputNodes;
  1413. }
  1414. }
  1415. /**
  1416. * Deserializes the node from the given JSON.
  1417. *
  1418. * @param {Object} json - The JSON object.
  1419. */
  1420. deserialize( json ) {
  1421. if ( json.inputNodes !== undefined ) {
  1422. const nodes = json.meta.nodes;
  1423. for ( const property in json.inputNodes ) {
  1424. if ( Array.isArray( json.inputNodes[ property ] ) ) {
  1425. const inputArray = [];
  1426. for ( const uuid of json.inputNodes[ property ] ) {
  1427. inputArray.push( nodes[ uuid ] );
  1428. }
  1429. this[ property ] = inputArray;
  1430. } else if ( typeof json.inputNodes[ property ] === 'object' ) {
  1431. const inputObject = {};
  1432. for ( const subProperty in json.inputNodes[ property ] ) {
  1433. const uuid = json.inputNodes[ property ][ subProperty ];
  1434. inputObject[ subProperty ] = nodes[ uuid ];
  1435. }
  1436. this[ property ] = inputObject;
  1437. } else {
  1438. const uuid = json.inputNodes[ property ];
  1439. this[ property ] = nodes[ uuid ];
  1440. }
  1441. }
  1442. }
  1443. }
  1444. /**
  1445. * Serializes the node into the three.js JSON Object/Scene format.
  1446. *
  1447. * @param {?Object} meta - An optional JSON object that already holds serialized data from other scene objects.
  1448. * @return {Object} The serialized node.
  1449. */
  1450. toJSON( meta ) {
  1451. const { uuid, type } = this;
  1452. const isRoot = ( meta === undefined || typeof meta === 'string' );
  1453. if ( isRoot ) {
  1454. meta = {
  1455. textures: {},
  1456. images: {},
  1457. nodes: {}
  1458. };
  1459. }
  1460. // serialize
  1461. let data = meta.nodes[ uuid ];
  1462. if ( data === undefined ) {
  1463. data = {
  1464. uuid,
  1465. type,
  1466. meta,
  1467. metadata: {
  1468. version: 4.7,
  1469. type: 'Node',
  1470. generator: 'Node.toJSON'
  1471. }
  1472. };
  1473. if ( isRoot !== true ) meta.nodes[ data.uuid ] = data;
  1474. this.serialize( data );
  1475. delete data.meta;
  1476. }
  1477. // TODO: Copied from Object3D.toJSON
  1478. function extractFromCache( cache ) {
  1479. const values = [];
  1480. for ( const key in cache ) {
  1481. const data = cache[ key ];
  1482. delete data.metadata;
  1483. values.push( data );
  1484. }
  1485. return values;
  1486. }
  1487. if ( isRoot ) {
  1488. const textures = extractFromCache( meta.textures );
  1489. const images = extractFromCache( meta.images );
  1490. const nodes = extractFromCache( meta.nodes );
  1491. if ( textures.length > 0 ) data.textures = textures;
  1492. if ( images.length > 0 ) data.images = images;
  1493. if ( nodes.length > 0 ) data.nodes = nodes;
  1494. }
  1495. return data;
  1496. }
  1497. }
  1498. /**
  1499. * Base class for representing element access on an array-like
  1500. * node data structures.
  1501. *
  1502. * @augments Node
  1503. */
  1504. class ArrayElementNode extends Node { // @TODO: If extending from TempNode it breaks webgpu_compute
  1505. static get type() {
  1506. return 'ArrayElementNode';
  1507. }
  1508. /**
  1509. * Constructs an array element node.
  1510. *
  1511. * @param {Node} node - The array-like node.
  1512. * @param {Node} indexNode - The index node that defines the element access.
  1513. */
  1514. constructor( node, indexNode ) {
  1515. super();
  1516. /**
  1517. * The array-like node.
  1518. *
  1519. * @type {Node}
  1520. */
  1521. this.node = node;
  1522. /**
  1523. * The index node that defines the element access.
  1524. *
  1525. * @type {Node}
  1526. */
  1527. this.indexNode = indexNode;
  1528. /**
  1529. * This flag can be used for type testing.
  1530. *
  1531. * @type {boolean}
  1532. * @readonly
  1533. * @default true
  1534. */
  1535. this.isArrayElementNode = true;
  1536. }
  1537. /**
  1538. * This method is overwritten since the node type is inferred from the array-like node.
  1539. *
  1540. * @param {NodeBuilder} builder - The current node builder.
  1541. * @return {string} The node type.
  1542. */
  1543. getNodeType( builder ) {
  1544. return this.node.getElementType( builder );
  1545. }
  1546. generate( builder ) {
  1547. const indexType = this.indexNode.getNodeType( builder );
  1548. const nodeSnippet = this.node.build( builder );
  1549. const indexSnippet = this.indexNode.build( builder, ! builder.isVector( indexType ) && builder.isInteger( indexType ) ? indexType : 'uint' );
  1550. return `${ nodeSnippet }[ ${ indexSnippet } ]`;
  1551. }
  1552. }
  1553. /**
  1554. * This module is part of the TSL core and usually not used in app level code.
  1555. * It represents a convert operation during the shader generation process
  1556. * meaning it converts the data type of a node to a target data type.
  1557. *
  1558. * @augments Node
  1559. */
  1560. class ConvertNode extends Node {
  1561. static get type() {
  1562. return 'ConvertNode';
  1563. }
  1564. /**
  1565. * Constructs a new convert node.
  1566. *
  1567. * @param {Node} node - The node which type should be converted.
  1568. * @param {string} convertTo - The target node type. Multiple types can be defined by separating them with a `|` sign.
  1569. */
  1570. constructor( node, convertTo ) {
  1571. super();
  1572. /**
  1573. * The node which type should be converted.
  1574. *
  1575. * @type {Node}
  1576. */
  1577. this.node = node;
  1578. /**
  1579. * The target node type. Multiple types can be defined by separating them with a `|` sign.
  1580. *
  1581. * @type {string}
  1582. */
  1583. this.convertTo = convertTo;
  1584. }
  1585. /**
  1586. * This method is overwritten since the implementation tries to infer the best
  1587. * matching type from the {@link ConvertNode#convertTo} property.
  1588. *
  1589. * @param {NodeBuilder} builder - The current node builder.
  1590. * @return {string} The node type.
  1591. */
  1592. getNodeType( builder ) {
  1593. const requestType = this.node.getNodeType( builder );
  1594. let convertTo = null;
  1595. for ( const overloadingType of this.convertTo.split( '|' ) ) {
  1596. if ( convertTo === null || builder.getTypeLength( requestType ) === builder.getTypeLength( overloadingType ) ) {
  1597. convertTo = overloadingType;
  1598. }
  1599. }
  1600. return convertTo;
  1601. }
  1602. serialize( data ) {
  1603. super.serialize( data );
  1604. data.convertTo = this.convertTo;
  1605. }
  1606. deserialize( data ) {
  1607. super.deserialize( data );
  1608. this.convertTo = data.convertTo;
  1609. }
  1610. generate( builder, output ) {
  1611. const node = this.node;
  1612. const type = this.getNodeType( builder );
  1613. const snippet = node.build( builder, type );
  1614. return builder.format( snippet, type, output );
  1615. }
  1616. }
  1617. /**
  1618. * This module uses cache management to create temporary variables
  1619. * if the node is used more than once to prevent duplicate calculations.
  1620. *
  1621. * The class acts as a base class for many other nodes types.
  1622. *
  1623. * @augments Node
  1624. */
  1625. class TempNode extends Node {
  1626. static get type() {
  1627. return 'TempNode';
  1628. }
  1629. /**
  1630. * Constructs a temp node.
  1631. *
  1632. * @param {?string} nodeType - The node type.
  1633. */
  1634. constructor( nodeType = null ) {
  1635. super( nodeType );
  1636. /**
  1637. * This flag can be used for type testing.
  1638. *
  1639. * @type {boolean}
  1640. * @readonly
  1641. * @default true
  1642. */
  1643. this.isTempNode = true;
  1644. }
  1645. /**
  1646. * Whether this node is used more than once in context of other nodes.
  1647. *
  1648. * @param {NodeBuilder} builder - The node builder.
  1649. * @return {boolean} A flag that indicates if there is more than one dependency to other nodes.
  1650. */
  1651. hasDependencies( builder ) {
  1652. return builder.getDataFromNode( this ).usageCount > 1;
  1653. }
  1654. build( builder, output ) {
  1655. const buildStage = builder.getBuildStage();
  1656. if ( buildStage === 'generate' ) {
  1657. const type = builder.getVectorType( this.getNodeType( builder, output ) );
  1658. const nodeData = builder.getDataFromNode( this );
  1659. if ( nodeData.propertyName !== undefined ) {
  1660. return builder.format( nodeData.propertyName, type, output );
  1661. } else if ( type !== 'void' && output !== 'void' && this.hasDependencies( builder ) ) {
  1662. const snippet = super.build( builder, type );
  1663. const nodeVar = builder.getVarFromNode( this, null, type );
  1664. const propertyName = builder.getPropertyName( nodeVar );
  1665. builder.addLineFlowCode( `${ propertyName } = ${ snippet }`, this );
  1666. nodeData.snippet = snippet;
  1667. nodeData.propertyName = propertyName;
  1668. return builder.format( nodeData.propertyName, type, output );
  1669. }
  1670. }
  1671. return super.build( builder, output );
  1672. }
  1673. }
  1674. /**
  1675. * This module is part of the TSL core and usually not used in app level code.
  1676. * It represents a join operation during the shader generation process.
  1677. * For example in can compose/join two single floats into a `vec2` type.
  1678. *
  1679. * @augments TempNode
  1680. */
  1681. class JoinNode extends TempNode {
  1682. static get type() {
  1683. return 'JoinNode';
  1684. }
  1685. /**
  1686. * Constructs a new join node.
  1687. *
  1688. * @param {Array<Node>} nodes - An array of nodes that should be joined.
  1689. * @param {?string} [nodeType=null] - The node type.
  1690. */
  1691. constructor( nodes = [], nodeType = null ) {
  1692. super( nodeType );
  1693. /**
  1694. * An array of nodes that should be joined.
  1695. *
  1696. * @type {Array<Node>}
  1697. */
  1698. this.nodes = nodes;
  1699. }
  1700. /**
  1701. * This method is overwritten since the node type must be inferred from the
  1702. * joined data length if not explicitly defined.
  1703. *
  1704. * @param {NodeBuilder} builder - The current node builder.
  1705. * @return {string} The node type.
  1706. */
  1707. getNodeType( builder ) {
  1708. if ( this.nodeType !== null ) {
  1709. return builder.getVectorType( this.nodeType );
  1710. }
  1711. return builder.getTypeFromLength( this.nodes.reduce( ( count, cur ) => count + builder.getTypeLength( cur.getNodeType( builder ) ), 0 ) );
  1712. }
  1713. generate( builder, output ) {
  1714. const type = this.getNodeType( builder );
  1715. const maxLength = builder.getTypeLength( type );
  1716. const nodes = this.nodes;
  1717. const primitiveType = builder.getComponentType( type );
  1718. const snippetValues = [];
  1719. let length = 0;
  1720. for ( const input of nodes ) {
  1721. if ( length >= maxLength ) {
  1722. error( `TSL: Length of parameters exceeds maximum length of function '${ type }()' type.` );
  1723. break;
  1724. }
  1725. let inputType = input.getNodeType( builder );
  1726. let inputTypeLength = builder.getTypeLength( inputType );
  1727. let inputSnippet;
  1728. if ( length + inputTypeLength > maxLength ) {
  1729. error( `TSL: Length of '${ type }()' data exceeds maximum length of output type.` );
  1730. inputTypeLength = maxLength - length;
  1731. inputType = builder.getTypeFromLength( inputTypeLength );
  1732. }
  1733. length += inputTypeLength;
  1734. inputSnippet = input.build( builder, inputType );
  1735. const inputPrimitiveType = builder.getComponentType( inputType );
  1736. if ( inputPrimitiveType !== primitiveType ) {
  1737. const targetType = builder.getTypeFromLength( inputTypeLength, primitiveType );
  1738. inputSnippet = builder.format( inputSnippet, inputType, targetType );
  1739. }
  1740. snippetValues.push( inputSnippet );
  1741. }
  1742. const snippet = `${ builder.getType( type ) }( ${ snippetValues.join( ', ' ) } )`;
  1743. return builder.format( snippet, type, output );
  1744. }
  1745. }
  1746. const _stringVectorComponents = vectorComponents.join( '' );
  1747. /**
  1748. * This module is part of the TSL core and usually not used in app level code.
  1749. * `SplitNode` represents a property access operation which means it is
  1750. * used to implement any `.xyzw`, `.rgba` and `stpq` usage on node objects.
  1751. * For example:
  1752. * ```js
  1753. * const redValue = color.r;
  1754. * ```
  1755. *
  1756. * @augments Node
  1757. */
  1758. class SplitNode extends Node {
  1759. static get type() {
  1760. return 'SplitNode';
  1761. }
  1762. /**
  1763. * Constructs a new split node.
  1764. *
  1765. * @param {Node} node - The node that should be accessed.
  1766. * @param {string} [components='x'] - The components that should be accessed.
  1767. */
  1768. constructor( node, components = 'x' ) {
  1769. super();
  1770. /**
  1771. * The node that should be accessed.
  1772. *
  1773. * @type {Node}
  1774. */
  1775. this.node = node;
  1776. /**
  1777. * The components that should be accessed.
  1778. *
  1779. * @type {string}
  1780. */
  1781. this.components = components;
  1782. /**
  1783. * This flag can be used for type testing.
  1784. *
  1785. * @type {boolean}
  1786. * @readonly
  1787. * @default true
  1788. */
  1789. this.isSplitNode = true;
  1790. }
  1791. /**
  1792. * Returns the vector length which is computed based on the requested components.
  1793. *
  1794. * @return {number} The vector length.
  1795. */
  1796. getVectorLength() {
  1797. let vectorLength = this.components.length;
  1798. for ( const c of this.components ) {
  1799. vectorLength = Math.max( vectorComponents.indexOf( c ) + 1, vectorLength );
  1800. }
  1801. return vectorLength;
  1802. }
  1803. /**
  1804. * Returns the component type of the node's type.
  1805. *
  1806. * @param {NodeBuilder} builder - The current node builder.
  1807. * @return {string} The component type.
  1808. */
  1809. getComponentType( builder ) {
  1810. return builder.getComponentType( this.node.getNodeType( builder ) );
  1811. }
  1812. /**
  1813. * This method is overwritten since the node type is inferred from requested components.
  1814. *
  1815. * @param {NodeBuilder} builder - The current node builder.
  1816. * @return {string} The node type.
  1817. */
  1818. getNodeType( builder ) {
  1819. return builder.getTypeFromLength( this.components.length, this.getComponentType( builder ) );
  1820. }
  1821. /**
  1822. * Returns the scope of the node.
  1823. *
  1824. * @return {Node} The scope of the node.
  1825. */
  1826. getScope() {
  1827. return this.node.getScope();
  1828. }
  1829. generate( builder, output ) {
  1830. const node = this.node;
  1831. const nodeTypeLength = builder.getTypeLength( node.getNodeType( builder ) );
  1832. let snippet = null;
  1833. if ( nodeTypeLength > 1 ) {
  1834. let type = null;
  1835. const componentsLength = this.getVectorLength();
  1836. if ( componentsLength >= nodeTypeLength ) {
  1837. // needed expand the input node
  1838. type = builder.getTypeFromLength( this.getVectorLength(), this.getComponentType( builder ) );
  1839. }
  1840. const nodeSnippet = node.build( builder, type );
  1841. if ( this.components.length === nodeTypeLength && this.components === _stringVectorComponents.slice( 0, this.components.length ) ) {
  1842. // unnecessary swizzle
  1843. snippet = builder.format( nodeSnippet, type, output );
  1844. } else {
  1845. snippet = builder.format( `${nodeSnippet}.${this.components}`, this.getNodeType( builder ), output );
  1846. }
  1847. } else {
  1848. // ignore .components if .node returns float/integer
  1849. snippet = node.build( builder, output );
  1850. }
  1851. return snippet;
  1852. }
  1853. serialize( data ) {
  1854. super.serialize( data );
  1855. data.components = this.components;
  1856. }
  1857. deserialize( data ) {
  1858. super.deserialize( data );
  1859. this.components = data.components;
  1860. }
  1861. }
  1862. /**
  1863. * This module is part of the TSL core and usually not used in app level code.
  1864. * `SetNode` represents a set operation which means it is used to implement any
  1865. * `setXYZW()`, `setRGBA()` and `setSTPQ()` method invocations on node objects.
  1866. * For example:
  1867. * ```js
  1868. * materialLine.colorNode = color( 0, 0, 0 ).setR( float( 1 ) );
  1869. * ```
  1870. *
  1871. * @augments TempNode
  1872. */
  1873. class SetNode extends TempNode {
  1874. static get type() {
  1875. return 'SetNode';
  1876. }
  1877. /**
  1878. * Constructs a new set node.
  1879. *
  1880. * @param {Node} sourceNode - The node that should be updated.
  1881. * @param {string} components - The components that should be updated.
  1882. * @param {Node} targetNode - The value node.
  1883. */
  1884. constructor( sourceNode, components, targetNode ) {
  1885. super();
  1886. /**
  1887. * The node that should be updated.
  1888. *
  1889. * @type {Node}
  1890. */
  1891. this.sourceNode = sourceNode;
  1892. /**
  1893. * The components that should be updated.
  1894. *
  1895. * @type {string}
  1896. */
  1897. this.components = components;
  1898. /**
  1899. * The value node.
  1900. *
  1901. * @type {Node}
  1902. */
  1903. this.targetNode = targetNode;
  1904. }
  1905. /**
  1906. * This method is overwritten since the node type is inferred from {@link SetNode#sourceNode}.
  1907. *
  1908. * @param {NodeBuilder} builder - The current node builder.
  1909. * @return {string} The node type.
  1910. */
  1911. getNodeType( builder ) {
  1912. return this.sourceNode.getNodeType( builder );
  1913. }
  1914. generate( builder ) {
  1915. const { sourceNode, components, targetNode } = this;
  1916. const sourceType = this.getNodeType( builder );
  1917. const componentType = builder.getComponentType( targetNode.getNodeType( builder ) );
  1918. const targetType = builder.getTypeFromLength( components.length, componentType );
  1919. const targetSnippet = targetNode.build( builder, targetType );
  1920. const sourceSnippet = sourceNode.build( builder, sourceType );
  1921. const length = builder.getTypeLength( sourceType );
  1922. const snippetValues = [];
  1923. for ( let i = 0; i < length; i ++ ) {
  1924. const component = vectorComponents[ i ];
  1925. if ( component === components[ 0 ] ) {
  1926. snippetValues.push( targetSnippet );
  1927. i += components.length - 1;
  1928. } else {
  1929. snippetValues.push( sourceSnippet + '.' + component );
  1930. }
  1931. }
  1932. return `${ builder.getType( sourceType ) }( ${ snippetValues.join( ', ' ) } )`;
  1933. }
  1934. }
  1935. /**
  1936. * This module is part of the TSL core and usually not used in app level code.
  1937. * It represents a flip operation during the shader generation process
  1938. * meaning it flips normalized values with the following formula:
  1939. * ```
  1940. * x = 1 - x;
  1941. * ```
  1942. * `FlipNode` is internally used to implement any `flipXYZW()`, `flipRGBA()` and
  1943. * `flipSTPQ()` method invocations on node objects. For example:
  1944. * ```js
  1945. * uvNode = uvNode.flipY();
  1946. * ```
  1947. *
  1948. * @augments TempNode
  1949. */
  1950. class FlipNode extends TempNode {
  1951. static get type() {
  1952. return 'FlipNode';
  1953. }
  1954. /**
  1955. * Constructs a new flip node.
  1956. *
  1957. * @param {Node} sourceNode - The node which component(s) should be flipped.
  1958. * @param {string} components - The components that should be flipped e.g. `'x'` or `'xy'`.
  1959. */
  1960. constructor( sourceNode, components ) {
  1961. super();
  1962. /**
  1963. * The node which component(s) should be flipped.
  1964. *
  1965. * @type {Node}
  1966. */
  1967. this.sourceNode = sourceNode;
  1968. /**
  1969. * The components that should be flipped e.g. `'x'` or `'xy'`.
  1970. *
  1971. * @type {string}
  1972. */
  1973. this.components = components;
  1974. }
  1975. /**
  1976. * This method is overwritten since the node type is inferred from the source node.
  1977. *
  1978. * @param {NodeBuilder} builder - The current node builder.
  1979. * @return {string} The node type.
  1980. */
  1981. getNodeType( builder ) {
  1982. return this.sourceNode.getNodeType( builder );
  1983. }
  1984. generate( builder ) {
  1985. const { components, sourceNode } = this;
  1986. const sourceType = this.getNodeType( builder );
  1987. const sourceSnippet = sourceNode.build( builder );
  1988. const sourceCache = builder.getVarFromNode( this );
  1989. const sourceProperty = builder.getPropertyName( sourceCache );
  1990. builder.addLineFlowCode( sourceProperty + ' = ' + sourceSnippet, this );
  1991. const length = builder.getTypeLength( sourceType );
  1992. const snippetValues = [];
  1993. let componentIndex = 0;
  1994. for ( let i = 0; i < length; i ++ ) {
  1995. const component = vectorComponents[ i ];
  1996. if ( component === components[ componentIndex ] ) {
  1997. snippetValues.push( '1.0 - ' + ( sourceProperty + '.' + component ) );
  1998. componentIndex ++;
  1999. } else {
  2000. snippetValues.push( sourceProperty + '.' + component );
  2001. }
  2002. }
  2003. return `${ builder.getType( sourceType ) }( ${ snippetValues.join( ', ' ) } )`;
  2004. }
  2005. }
  2006. /**
  2007. * Base class for representing data input nodes.
  2008. *
  2009. * @augments Node
  2010. */
  2011. class InputNode extends Node {
  2012. static get type() {
  2013. return 'InputNode';
  2014. }
  2015. /**
  2016. * Constructs a new input node.
  2017. *
  2018. * @param {any} value - The value of this node. This can be any JS primitive, functions, array buffers or even three.js objects (vector, matrices, colors).
  2019. * @param {?string} nodeType - The node type. If no explicit type is defined, the node tries to derive the type from its value.
  2020. */
  2021. constructor( value, nodeType = null ) {
  2022. super( nodeType );
  2023. /**
  2024. * This flag can be used for type testing.
  2025. *
  2026. * @type {boolean}
  2027. * @readonly
  2028. * @default true
  2029. */
  2030. this.isInputNode = true;
  2031. /**
  2032. * The value of this node. This can be any JS primitive, functions, array buffers or even three.js objects (vector, matrices, colors).
  2033. *
  2034. * @type {any}
  2035. */
  2036. this.value = value;
  2037. /**
  2038. * The precision of the value in the shader.
  2039. *
  2040. * @type {?('low'|'medium'|'high')}
  2041. * @default null
  2042. */
  2043. this.precision = null;
  2044. }
  2045. getNodeType( /*builder*/ ) {
  2046. if ( this.nodeType === null ) {
  2047. return getValueType( this.value );
  2048. }
  2049. return this.nodeType;
  2050. }
  2051. /**
  2052. * Returns the input type of the node which is by default the node type. Derived modules
  2053. * might overwrite this method and use a fixed type or compute one analytically.
  2054. *
  2055. * A typical example for different input and node types are textures. The input type of a
  2056. * normal RGBA texture is `texture` whereas its node type is `vec4`.
  2057. *
  2058. * @param {NodeBuilder} builder - The current node builder.
  2059. * @return {string} The input type.
  2060. */
  2061. getInputType( builder ) {
  2062. return this.getNodeType( builder );
  2063. }
  2064. /**
  2065. * Sets the precision to the given value. The method can be
  2066. * overwritten in derived classes if the final precision must be computed
  2067. * analytically.
  2068. *
  2069. * @param {('low'|'medium'|'high')} precision - The precision of the input value in the shader.
  2070. * @return {InputNode} A reference to this node.
  2071. */
  2072. setPrecision( precision ) {
  2073. this.precision = precision;
  2074. return this;
  2075. }
  2076. serialize( data ) {
  2077. super.serialize( data );
  2078. data.value = this.value;
  2079. if ( this.value && this.value.toArray ) data.value = this.value.toArray();
  2080. data.valueType = getValueType( this.value );
  2081. data.nodeType = this.nodeType;
  2082. if ( data.valueType === 'ArrayBuffer' ) data.value = arrayBufferToBase64( data.value );
  2083. data.precision = this.precision;
  2084. }
  2085. deserialize( data ) {
  2086. super.deserialize( data );
  2087. this.nodeType = data.nodeType;
  2088. this.value = Array.isArray( data.value ) ? getValueFromType( data.valueType, ...data.value ) : data.value;
  2089. this.precision = data.precision || null;
  2090. if ( this.value && this.value.fromArray ) this.value = this.value.fromArray( data.value );
  2091. }
  2092. generate( /*builder, output*/ ) {
  2093. warn( 'Abstract function.' );
  2094. }
  2095. }
  2096. const _regNum = /float|u?int/;
  2097. /**
  2098. * Class for representing a constant value in the shader.
  2099. *
  2100. * @augments InputNode
  2101. */
  2102. class ConstNode extends InputNode {
  2103. static get type() {
  2104. return 'ConstNode';
  2105. }
  2106. /**
  2107. * Constructs a new input node.
  2108. *
  2109. * @param {any} value - The value of this node. Usually a JS primitive or three.js object (vector, matrix, color).
  2110. * @param {?string} nodeType - The node type. If no explicit type is defined, the node tries to derive the type from its value.
  2111. */
  2112. constructor( value, nodeType = null ) {
  2113. super( value, nodeType );
  2114. /**
  2115. * This flag can be used for type testing.
  2116. *
  2117. * @type {boolean}
  2118. * @readonly
  2119. * @default true
  2120. */
  2121. this.isConstNode = true;
  2122. }
  2123. /**
  2124. * Generates the shader string of the value with the current node builder.
  2125. *
  2126. * @param {NodeBuilder} builder - The current node builder.
  2127. * @return {string} The generated value as a shader string.
  2128. */
  2129. generateConst( builder ) {
  2130. return builder.generateConst( this.getNodeType( builder ), this.value );
  2131. }
  2132. generate( builder, output ) {
  2133. const type = this.getNodeType( builder );
  2134. if ( _regNum.test( type ) && _regNum.test( output ) ) {
  2135. return builder.generateConst( output, this.value );
  2136. }
  2137. return builder.format( this.generateConst( builder ), type, output );
  2138. }
  2139. }
  2140. /**
  2141. * Base class for representing member access on an object-like
  2142. * node data structures.
  2143. *
  2144. * @augments Node
  2145. */
  2146. class MemberNode extends Node {
  2147. static get type() {
  2148. return 'MemberNode';
  2149. }
  2150. /**
  2151. * Constructs a member node.
  2152. *
  2153. * @param {Node} structNode - The struct node.
  2154. * @param {string} property - The property name.
  2155. */
  2156. constructor( structNode, property ) {
  2157. super();
  2158. /**
  2159. * The struct node.
  2160. *
  2161. * @type {Node}
  2162. */
  2163. this.structNode = structNode;
  2164. /**
  2165. * The property name.
  2166. *
  2167. * @type {Node}
  2168. */
  2169. this.property = property;
  2170. /**
  2171. * This flag can be used for type testing.
  2172. *
  2173. * @type {boolean}
  2174. * @readonly
  2175. * @default true
  2176. */
  2177. this.isMemberNode = true;
  2178. }
  2179. hasMember( builder ) {
  2180. if ( this.structNode.isMemberNode ) {
  2181. if ( this.structNode.hasMember( builder ) === false ) {
  2182. return false;
  2183. }
  2184. }
  2185. return this.structNode.getMemberType( builder, this.property ) !== 'void';
  2186. }
  2187. getNodeType( builder ) {
  2188. if ( this.hasMember( builder ) === false ) {
  2189. // default type if member does not exist
  2190. return 'float';
  2191. }
  2192. return this.structNode.getMemberType( builder, this.property );
  2193. }
  2194. getMemberType( builder, name ) {
  2195. if ( this.hasMember( builder ) === false ) {
  2196. // default type if member does not exist
  2197. return 'float';
  2198. }
  2199. const type = this.getNodeType( builder );
  2200. const struct = builder.getStructTypeNode( type );
  2201. return struct.getMemberType( builder, name );
  2202. }
  2203. generate( builder ) {
  2204. if ( this.hasMember( builder ) === false ) {
  2205. warn( `TSL: Member "${ this.property }" does not exist in struct.` );
  2206. const type = this.getNodeType( builder );
  2207. return builder.generateConst( type );
  2208. }
  2209. const propertyName = this.structNode.build( builder );
  2210. return propertyName + '.' + this.property;
  2211. }
  2212. }
  2213. let currentStack = null;
  2214. const NodeElements = new Map();
  2215. // Extend Node Class for TSL using prototype
  2216. function addMethodChaining( name, nodeElement ) {
  2217. if ( NodeElements.has( name ) ) {
  2218. warn( `TSL: Redefinition of method chaining '${ name }'.` );
  2219. return;
  2220. }
  2221. if ( typeof nodeElement !== 'function' ) throw new Error( `THREE.TSL: Node element ${ name } is not a function` );
  2222. NodeElements.set( name, nodeElement );
  2223. if ( name !== 'assign' ) {
  2224. // Changing Node prototype to add method chaining
  2225. Node.prototype[ name ] = function ( ...params ) {
  2226. //if ( name === 'toVarIntent' ) return this;
  2227. return this.isStackNode ? this.addToStack( nodeElement( ...params ) ) : nodeElement( this, ...params );
  2228. };
  2229. // Adding assign method chaining
  2230. Node.prototype[ name + 'Assign' ] = function ( ...params ) {
  2231. return this.isStackNode ? this.assign( params[ 0 ], nodeElement( ...params ) ) : this.assign( nodeElement( this, ...params ) );
  2232. };
  2233. }
  2234. }
  2235. const parseSwizzle = ( props ) => props.replace( /r|s/g, 'x' ).replace( /g|t/g, 'y' ).replace( /b|p/g, 'z' ).replace( /a|q/g, 'w' );
  2236. const parseSwizzleAndSort = ( props ) => parseSwizzle( props ).split( '' ).sort().join( '' );
  2237. Node.prototype.assign = function ( ...params ) {
  2238. if ( this.isStackNode !== true ) {
  2239. if ( currentStack !== null ) {
  2240. currentStack.assign( this, ...params );
  2241. } else {
  2242. error( 'TSL: No stack defined for assign operation. Make sure the assign is inside a Fn().' );
  2243. }
  2244. return this;
  2245. } else {
  2246. const nodeElement = NodeElements.get( 'assign' );
  2247. return this.addToStack( nodeElement( ...params ) );
  2248. }
  2249. };
  2250. Node.prototype.toVarIntent = function () {
  2251. return this;
  2252. };
  2253. Node.prototype.get = function ( value ) {
  2254. return new MemberNode( this, value );
  2255. };
  2256. // Cache prototype for TSL
  2257. const proto = {};
  2258. // Set swizzle properties for xyzw, rgba, and stpq.
  2259. function setProtoSwizzle( property, altA, altB ) {
  2260. // swizzle properties
  2261. proto[ property ] = proto[ altA ] = proto[ altB ] = {
  2262. get() {
  2263. this._cache = this._cache || {};
  2264. //
  2265. let split = this._cache[ property ];
  2266. if ( split === undefined ) {
  2267. split = new SplitNode( this, property );
  2268. this._cache[ property ] = split;
  2269. }
  2270. return split;
  2271. },
  2272. set( value ) {
  2273. this[ property ].assign( nodeObject( value ) );
  2274. }
  2275. };
  2276. // set properties ( swizzle ) and sort to xyzw sequence
  2277. const propUpper = property.toUpperCase();
  2278. const altAUpper = altA.toUpperCase();
  2279. const altBUpper = altB.toUpperCase();
  2280. // Set methods for swizzle properties
  2281. Node.prototype[ 'set' + propUpper ] = Node.prototype[ 'set' + altAUpper ] = Node.prototype[ 'set' + altBUpper ] = function ( value ) {
  2282. const swizzle = parseSwizzleAndSort( property );
  2283. return new SetNode( this, swizzle, nodeObject( value ) );
  2284. };
  2285. // Set methods for flip properties
  2286. Node.prototype[ 'flip' + propUpper ] = Node.prototype[ 'flip' + altAUpper ] = Node.prototype[ 'flip' + altBUpper ] = function () {
  2287. const swizzle = parseSwizzleAndSort( property );
  2288. return new FlipNode( this, swizzle );
  2289. };
  2290. }
  2291. const swizzleA = [ 'x', 'y', 'z', 'w' ];
  2292. const swizzleB = [ 'r', 'g', 'b', 'a' ];
  2293. const swizzleC = [ 's', 't', 'p', 'q' ];
  2294. for ( let a = 0; a < 4; a ++ ) {
  2295. let prop = swizzleA[ a ];
  2296. let altA = swizzleB[ a ];
  2297. let altB = swizzleC[ a ];
  2298. setProtoSwizzle( prop, altA, altB );
  2299. for ( let b = 0; b < 4; b ++ ) {
  2300. prop = swizzleA[ a ] + swizzleA[ b ];
  2301. altA = swizzleB[ a ] + swizzleB[ b ];
  2302. altB = swizzleC[ a ] + swizzleC[ b ];
  2303. setProtoSwizzle( prop, altA, altB );
  2304. for ( let c = 0; c < 4; c ++ ) {
  2305. prop = swizzleA[ a ] + swizzleA[ b ] + swizzleA[ c ];
  2306. altA = swizzleB[ a ] + swizzleB[ b ] + swizzleB[ c ];
  2307. altB = swizzleC[ a ] + swizzleC[ b ] + swizzleC[ c ];
  2308. setProtoSwizzle( prop, altA, altB );
  2309. for ( let d = 0; d < 4; d ++ ) {
  2310. prop = swizzleA[ a ] + swizzleA[ b ] + swizzleA[ c ] + swizzleA[ d ];
  2311. altA = swizzleB[ a ] + swizzleB[ b ] + swizzleB[ c ] + swizzleB[ d ];
  2312. altB = swizzleC[ a ] + swizzleC[ b ] + swizzleC[ c ] + swizzleC[ d ];
  2313. setProtoSwizzle( prop, altA, altB );
  2314. }
  2315. }
  2316. }
  2317. }
  2318. // Set/get static properties for array elements (0-31).
  2319. for ( let i = 0; i < 32; i ++ ) {
  2320. proto[ i ] = {
  2321. get() {
  2322. this._cache = this._cache || {};
  2323. //
  2324. let element = this._cache[ i ];
  2325. if ( element === undefined ) {
  2326. element = new ArrayElementNode( this, new ConstNode( i, 'uint' ) );
  2327. this._cache[ i ] = element;
  2328. }
  2329. return element;
  2330. },
  2331. set( value ) {
  2332. this[ i ].assign( nodeObject( value ) );
  2333. }
  2334. };
  2335. }
  2336. /*
  2337. // Set properties for width, height, and depth.
  2338. function setProtoProperty( property, target ) {
  2339. proto[ property ] = {
  2340. get() {
  2341. this._cache = this._cache || {};
  2342. //
  2343. let split = this._cache[ target ];
  2344. if ( split === undefined ) {
  2345. split = new SplitNode( this, target );
  2346. this._cache[ target ] = split;
  2347. }
  2348. return split;
  2349. },
  2350. set( value ) {
  2351. this[ target ].assign( nodeObject( value ) );
  2352. }
  2353. };
  2354. }
  2355. setProtoProperty( 'width', 'x' );
  2356. setProtoProperty( 'height', 'y' );
  2357. setProtoProperty( 'depth', 'z' );
  2358. */
  2359. Object.defineProperties( Node.prototype, proto );
  2360. // --- FINISH ---
  2361. const nodeBuilderFunctionsCacheMap = new WeakMap();
  2362. const ShaderNodeObject = function ( obj, altType = null ) {
  2363. const type = getValueType( obj );
  2364. if ( type === 'node' ) {
  2365. return obj;
  2366. } else if ( ( altType === null && ( type === 'float' || type === 'boolean' ) ) || ( type && type !== 'shader' && type !== 'string' ) ) {
  2367. return nodeObject( getConstNode( obj, altType ) );
  2368. } else if ( type === 'shader' ) {
  2369. return obj.isFn ? obj : Fn( obj );
  2370. }
  2371. return obj;
  2372. };
  2373. const ShaderNodeObjects = function ( objects, altType = null ) {
  2374. for ( const name in objects ) {
  2375. objects[ name ] = nodeObject( objects[ name ], altType );
  2376. }
  2377. return objects;
  2378. };
  2379. const ShaderNodeArray = function ( array, altType = null ) {
  2380. const len = array.length;
  2381. for ( let i = 0; i < len; i ++ ) {
  2382. array[ i ] = nodeObject( array[ i ], altType );
  2383. }
  2384. return array;
  2385. };
  2386. const ShaderNodeProxy = function ( NodeClass, scope = null, factor = null, settings = null ) {
  2387. function assignNode( node ) {
  2388. if ( settings !== null ) {
  2389. node = nodeObject( Object.assign( node, settings ) );
  2390. if ( settings.intent === true ) {
  2391. node = node.toVarIntent();
  2392. }
  2393. } else {
  2394. node = nodeObject( node );
  2395. }
  2396. return node;
  2397. }
  2398. let fn, name = scope, minParams, maxParams;
  2399. function verifyParamsLimit( params ) {
  2400. let tslName;
  2401. if ( name ) tslName = /[a-z]/i.test( name ) ? name + '()' : name;
  2402. else tslName = NodeClass.type;
  2403. if ( minParams !== undefined && params.length < minParams ) {
  2404. error( `TSL: "${ tslName }" parameter length is less than minimum required.` );
  2405. return params.concat( new Array( minParams - params.length ).fill( 0 ) );
  2406. } else if ( maxParams !== undefined && params.length > maxParams ) {
  2407. error( `TSL: "${ tslName }" parameter length exceeds limit.` );
  2408. return params.slice( 0, maxParams );
  2409. }
  2410. return params;
  2411. }
  2412. if ( scope === null ) {
  2413. fn = ( ...params ) => {
  2414. return assignNode( new NodeClass( ...nodeArray( verifyParamsLimit( params ) ) ) );
  2415. };
  2416. } else if ( factor !== null ) {
  2417. factor = nodeObject( factor );
  2418. fn = ( ...params ) => {
  2419. return assignNode( new NodeClass( scope, ...nodeArray( verifyParamsLimit( params ) ), factor ) );
  2420. };
  2421. } else {
  2422. fn = ( ...params ) => {
  2423. return assignNode( new NodeClass( scope, ...nodeArray( verifyParamsLimit( params ) ) ) );
  2424. };
  2425. }
  2426. fn.setParameterLength = ( ...params ) => {
  2427. if ( params.length === 1 ) minParams = maxParams = params[ 0 ];
  2428. else if ( params.length === 2 ) [ minParams, maxParams ] = params;
  2429. return fn;
  2430. };
  2431. fn.setName = ( value ) => {
  2432. name = value;
  2433. return fn;
  2434. };
  2435. return fn;
  2436. };
  2437. const ShaderNodeImmutable = function ( NodeClass, ...params ) {
  2438. return nodeObject( new NodeClass( ...nodeArray( params ) ) );
  2439. };
  2440. class ShaderCallNodeInternal extends Node {
  2441. constructor( shaderNode, rawInputs ) {
  2442. super();
  2443. this.shaderNode = shaderNode;
  2444. this.rawInputs = rawInputs;
  2445. this.isShaderCallNodeInternal = true;
  2446. }
  2447. getNodeType( builder ) {
  2448. return this.shaderNode.nodeType || this.getOutputNode( builder ).getNodeType( builder );
  2449. }
  2450. getElementType( builder ) {
  2451. return this.getOutputNode( builder ).getElementType( builder );
  2452. }
  2453. getMemberType( builder, name ) {
  2454. return this.getOutputNode( builder ).getMemberType( builder, name );
  2455. }
  2456. call( builder ) {
  2457. const { shaderNode, rawInputs } = this;
  2458. const properties = builder.getNodeProperties( shaderNode );
  2459. const subBuild = builder.getClosestSubBuild( shaderNode.subBuilds ) || '';
  2460. const subBuildProperty = subBuild || 'default';
  2461. if ( properties[ subBuildProperty ] ) {
  2462. return properties[ subBuildProperty ];
  2463. }
  2464. //
  2465. const previousSubBuildFn = builder.subBuildFn;
  2466. const previousFnCall = builder.fnCall;
  2467. builder.subBuildFn = subBuild;
  2468. builder.fnCall = this;
  2469. let result = null;
  2470. if ( shaderNode.layout ) {
  2471. let functionNodesCacheMap = nodeBuilderFunctionsCacheMap.get( builder.constructor );
  2472. if ( functionNodesCacheMap === undefined ) {
  2473. functionNodesCacheMap = new WeakMap();
  2474. nodeBuilderFunctionsCacheMap.set( builder.constructor, functionNodesCacheMap );
  2475. }
  2476. let functionNode = functionNodesCacheMap.get( shaderNode );
  2477. if ( functionNode === undefined ) {
  2478. functionNode = nodeObject( builder.buildFunctionNode( shaderNode ) );
  2479. functionNodesCacheMap.set( shaderNode, functionNode );
  2480. }
  2481. builder.addInclude( functionNode );
  2482. //
  2483. const inputs = rawInputs ? getLayoutParameters( rawInputs ) : null;
  2484. result = nodeObject( functionNode.call( inputs ) );
  2485. } else {
  2486. const secureNodeBuilder = new Proxy( builder, {
  2487. get: ( target, property, receiver ) => {
  2488. let value;
  2489. if ( Symbol.iterator === property ) {
  2490. value = function* () {
  2491. yield undefined;
  2492. };
  2493. } else {
  2494. value = Reflect.get( target, property, receiver );
  2495. }
  2496. return value;
  2497. }
  2498. } );
  2499. //
  2500. const inputs = rawInputs ? getProxyParameters( rawInputs ) : null;
  2501. const hasParameters = Array.isArray( rawInputs ) ? rawInputs.length > 0 : rawInputs !== null;
  2502. const jsFunc = shaderNode.jsFunc;
  2503. const outputNode = hasParameters || jsFunc.length > 1 ? jsFunc( inputs, secureNodeBuilder ) : jsFunc( secureNodeBuilder );
  2504. result = nodeObject( outputNode );
  2505. }
  2506. builder.subBuildFn = previousSubBuildFn;
  2507. builder.fnCall = previousFnCall;
  2508. if ( shaderNode.once ) {
  2509. properties[ subBuildProperty ] = result;
  2510. }
  2511. return result;
  2512. }
  2513. setupOutput( builder ) {
  2514. builder.addStack();
  2515. builder.stack.outputNode = this.call( builder );
  2516. return builder.removeStack();
  2517. }
  2518. getOutputNode( builder ) {
  2519. const properties = builder.getNodeProperties( this );
  2520. const subBuildOutput = builder.getSubBuildOutput( this );
  2521. properties[ subBuildOutput ] = properties[ subBuildOutput ] || this.setupOutput( builder );
  2522. properties[ subBuildOutput ].subBuild = builder.getClosestSubBuild( this );
  2523. return properties[ subBuildOutput ];
  2524. }
  2525. build( builder, output = null ) {
  2526. let result = null;
  2527. const buildStage = builder.getBuildStage();
  2528. const properties = builder.getNodeProperties( this );
  2529. const subBuildOutput = builder.getSubBuildOutput( this );
  2530. const outputNode = this.getOutputNode( builder );
  2531. const previousFnCall = builder.fnCall;
  2532. builder.fnCall = this;
  2533. if ( buildStage === 'setup' ) {
  2534. const subBuildInitialized = builder.getSubBuildProperty( 'initialized', this );
  2535. if ( properties[ subBuildInitialized ] !== true ) {
  2536. properties[ subBuildInitialized ] = true;
  2537. properties[ subBuildOutput ] = this.getOutputNode( builder );
  2538. properties[ subBuildOutput ].build( builder );
  2539. // If the shaderNode has subBuilds, add them to the chaining nodes
  2540. // so they can be built later in the build process.
  2541. if ( this.shaderNode.subBuilds ) {
  2542. for ( const node of builder.chaining ) {
  2543. const nodeData = builder.getDataFromNode( node, 'any' );
  2544. nodeData.subBuilds = nodeData.subBuilds || new Set();
  2545. for ( const subBuild of this.shaderNode.subBuilds ) {
  2546. nodeData.subBuilds.add( subBuild );
  2547. }
  2548. //builder.getDataFromNode( node ).subBuilds = nodeData.subBuilds;
  2549. }
  2550. }
  2551. }
  2552. result = properties[ subBuildOutput ];
  2553. } else if ( buildStage === 'analyze' ) {
  2554. outputNode.build( builder, output );
  2555. } else if ( buildStage === 'generate' ) {
  2556. result = outputNode.build( builder, output ) || '';
  2557. }
  2558. builder.fnCall = previousFnCall;
  2559. return result;
  2560. }
  2561. }
  2562. function getLayoutParameters( params ) {
  2563. let output;
  2564. nodeObjects( params );
  2565. const isArrayAsParameter = params[ 0 ] && ( params[ 0 ].isNode || Object.getPrototypeOf( params[ 0 ] ) !== Object.prototype );
  2566. if ( isArrayAsParameter ) {
  2567. output = [ ...params ];
  2568. } else {
  2569. output = params[ 0 ];
  2570. }
  2571. return output;
  2572. }
  2573. function getProxyParameters( params ) {
  2574. let index = 0;
  2575. nodeObjects( params );
  2576. return new Proxy( params, {
  2577. get: ( target, property, receiver ) => {
  2578. let value;
  2579. if ( property === 'length' ) {
  2580. value = params.length;
  2581. return value;
  2582. }
  2583. if ( Symbol.iterator === property ) {
  2584. value = function* () {
  2585. for ( const inputNode of params ) {
  2586. yield nodeObject( inputNode );
  2587. }
  2588. };
  2589. } else {
  2590. if ( params.length > 0 ) {
  2591. if ( Object.getPrototypeOf( params[ 0 ] ) === Object.prototype ) {
  2592. const objectTarget = params[ 0 ];
  2593. if ( objectTarget[ property ] === undefined ) {
  2594. value = objectTarget[ index ++ ];
  2595. } else {
  2596. value = Reflect.get( objectTarget, property, receiver );
  2597. }
  2598. } else if ( params[ 0 ] instanceof Node ) {
  2599. if ( params[ property ] === undefined ) {
  2600. value = params[ index ++ ];
  2601. } else {
  2602. value = Reflect.get( params, property, receiver );
  2603. }
  2604. }
  2605. } else {
  2606. value = Reflect.get( target, property, receiver );
  2607. }
  2608. value = nodeObject( value );
  2609. }
  2610. return value;
  2611. }
  2612. } );
  2613. }
  2614. class ShaderNodeInternal extends Node {
  2615. constructor( jsFunc, nodeType ) {
  2616. super( nodeType );
  2617. this.jsFunc = jsFunc;
  2618. this.layout = null;
  2619. this.global = true;
  2620. this.once = false;
  2621. }
  2622. setLayout( layout ) {
  2623. this.layout = layout;
  2624. return this;
  2625. }
  2626. getLayout() {
  2627. return this.layout;
  2628. }
  2629. call( rawInputs = null ) {
  2630. return new ShaderCallNodeInternal( this, rawInputs );
  2631. }
  2632. setup() {
  2633. return this.call();
  2634. }
  2635. }
  2636. const bools = [ false, true ];
  2637. const uints = [ 0, 1, 2, 3 ];
  2638. const ints = [ -1, -2 ];
  2639. 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 ];
  2640. const boolsCacheMap = new Map();
  2641. for ( const bool of bools ) boolsCacheMap.set( bool, new ConstNode( bool ) );
  2642. const uintsCacheMap = new Map();
  2643. for ( const uint of uints ) uintsCacheMap.set( uint, new ConstNode( uint, 'uint' ) );
  2644. const intsCacheMap = new Map( [ ...uintsCacheMap ].map( el => new ConstNode( el.value, 'int' ) ) );
  2645. for ( const int of ints ) intsCacheMap.set( int, new ConstNode( int, 'int' ) );
  2646. const floatsCacheMap = new Map( [ ...intsCacheMap ].map( el => new ConstNode( el.value ) ) );
  2647. for ( const float of floats ) floatsCacheMap.set( float, new ConstNode( float ) );
  2648. for ( const float of floats ) floatsCacheMap.set( - float, new ConstNode( - float ) );
  2649. const cacheMaps = { bool: boolsCacheMap, uint: uintsCacheMap, ints: intsCacheMap, float: floatsCacheMap };
  2650. const constNodesCacheMap = new Map( [ ...boolsCacheMap, ...floatsCacheMap ] );
  2651. const getConstNode = ( value, type ) => {
  2652. if ( constNodesCacheMap.has( value ) ) {
  2653. return constNodesCacheMap.get( value );
  2654. } else if ( value.isNode === true ) {
  2655. return value;
  2656. } else {
  2657. return new ConstNode( value, type );
  2658. }
  2659. };
  2660. const ConvertType = function ( type, cacheMap = null ) {
  2661. return ( ...params ) => {
  2662. for ( const param of params ) {
  2663. if ( param === undefined ) {
  2664. error( `TSL: Invalid parameter for the type "${ type }".` );
  2665. return nodeObject( new ConstNode( 0, type ) );
  2666. }
  2667. }
  2668. if ( params.length === 0 || ( ! [ 'bool', 'float', 'int', 'uint' ].includes( type ) && params.every( param => {
  2669. const paramType = typeof param;
  2670. return paramType !== 'object' && paramType !== 'function';
  2671. } ) ) ) {
  2672. params = [ getValueFromType( type, ...params ) ];
  2673. }
  2674. if ( params.length === 1 && cacheMap !== null && cacheMap.has( params[ 0 ] ) ) {
  2675. return nodeObjectIntent( cacheMap.get( params[ 0 ] ) );
  2676. }
  2677. if ( params.length === 1 ) {
  2678. const node = getConstNode( params[ 0 ], type );
  2679. if ( node.nodeType === type ) return nodeObjectIntent( node );
  2680. return nodeObjectIntent( new ConvertNode( node, type ) );
  2681. }
  2682. const nodes = params.map( param => getConstNode( param ) );
  2683. return nodeObjectIntent( new JoinNode( nodes, type ) );
  2684. };
  2685. };
  2686. // exports
  2687. const defined = ( v ) => typeof v === 'object' && v !== null ? v.value : v; // TODO: remove boolean conversion and defined function
  2688. // utils
  2689. const getConstNodeType = ( value ) => ( value !== undefined && value !== null ) ? ( value.nodeType || value.convertTo || ( typeof value === 'string' ? value : null ) ) : null;
  2690. // shader node base
  2691. function ShaderNode( jsFunc, nodeType ) {
  2692. return new ShaderNodeInternal( jsFunc, nodeType );
  2693. }
  2694. const nodeObject = ( val, altType = null ) => /* new */ ShaderNodeObject( val, altType );
  2695. const nodeObjectIntent = ( val, altType = null ) => /* new */ nodeObject( val, altType ).toVarIntent();
  2696. const nodeObjects = ( val, altType = null ) => new ShaderNodeObjects( val, altType );
  2697. const nodeArray = ( val, altType = null ) => new ShaderNodeArray( val, altType );
  2698. const nodeProxy = ( NodeClass, scope = null, factor = null, settings = null ) => new ShaderNodeProxy( NodeClass, scope, factor, settings );
  2699. const nodeImmutable = ( NodeClass, ...params ) => new ShaderNodeImmutable( NodeClass, ...params );
  2700. const nodeProxyIntent = ( NodeClass, scope = null, factor = null, settings = {} ) => new ShaderNodeProxy( NodeClass, scope, factor, { ...settings, intent: true } );
  2701. let fnId = 0;
  2702. class FnNode extends Node {
  2703. constructor( jsFunc, layout = null ) {
  2704. super();
  2705. let nodeType = null;
  2706. if ( layout !== null ) {
  2707. if ( typeof layout === 'object' ) {
  2708. nodeType = layout.return;
  2709. } else {
  2710. if ( typeof layout === 'string' ) {
  2711. nodeType = layout;
  2712. } else {
  2713. error( 'TSL: Invalid layout type.' );
  2714. }
  2715. layout = null;
  2716. }
  2717. }
  2718. this.shaderNode = new ShaderNode( jsFunc, nodeType );
  2719. if ( layout !== null ) {
  2720. this.setLayout( layout );
  2721. }
  2722. this.isFn = true;
  2723. }
  2724. setLayout( layout ) {
  2725. const nodeType = this.shaderNode.nodeType;
  2726. if ( typeof layout.inputs !== 'object' ) {
  2727. const fullLayout = {
  2728. name: 'fn' + fnId ++,
  2729. type: nodeType,
  2730. inputs: []
  2731. };
  2732. for ( const name in layout ) {
  2733. if ( name === 'return' ) continue;
  2734. fullLayout.inputs.push( {
  2735. name: name,
  2736. type: layout[ name ]
  2737. } );
  2738. }
  2739. layout = fullLayout;
  2740. }
  2741. this.shaderNode.setLayout( layout );
  2742. return this;
  2743. }
  2744. getNodeType( builder ) {
  2745. return this.shaderNode.getNodeType( builder ) || 'float';
  2746. }
  2747. call( ...params ) {
  2748. const fnCall = this.shaderNode.call( params );
  2749. if ( this.shaderNode.nodeType === 'void' ) fnCall.toStack();
  2750. return fnCall.toVarIntent();
  2751. }
  2752. once( subBuilds = null ) {
  2753. this.shaderNode.once = true;
  2754. this.shaderNode.subBuilds = subBuilds;
  2755. return this;
  2756. }
  2757. generate( builder ) {
  2758. const type = this.getNodeType( builder );
  2759. error( 'TSL: "Fn()" was declared but not invoked. Try calling it like "Fn()( ...params )".' );
  2760. return builder.generateConst( type );
  2761. }
  2762. }
  2763. function Fn( jsFunc, layout = null ) {
  2764. const instance = new FnNode( jsFunc, layout );
  2765. return new Proxy( () => {}, {
  2766. apply( target, thisArg, params ) {
  2767. return instance.call( ...params );
  2768. },
  2769. get( target, prop, receiver ) {
  2770. return Reflect.get( instance, prop, receiver );
  2771. },
  2772. set( target, prop, value, receiver ) {
  2773. return Reflect.set( instance, prop, value, receiver );
  2774. }
  2775. } );
  2776. }
  2777. //
  2778. const setCurrentStack = ( stack ) => {
  2779. currentStack = stack;
  2780. };
  2781. const getCurrentStack = () => currentStack;
  2782. /**
  2783. * Represent a conditional node using if/else statements.
  2784. *
  2785. * ```js
  2786. * If( condition, function )
  2787. * .ElseIf( condition, function )
  2788. * .Else( function )
  2789. * ```
  2790. * @tsl
  2791. * @function
  2792. * @param {...any} params - The parameters for the conditional node.
  2793. * @returns {StackNode} The conditional node.
  2794. */
  2795. const If = ( ...params ) => currentStack.If( ...params );
  2796. /**
  2797. * Represent a conditional node using switch/case statements.
  2798. *
  2799. * ```js
  2800. * Switch( value )
  2801. * .Case( 1, function )
  2802. * .Case( 2, 3, 4, function )
  2803. * .Default( function )
  2804. * ```
  2805. * @tsl
  2806. * @function
  2807. * @param {...any} params - The parameters for the conditional node.
  2808. * @returns {StackNode} The conditional node.
  2809. */
  2810. const Switch = ( ...params ) => currentStack.Switch( ...params );
  2811. /**
  2812. * Add the given node to the current stack.
  2813. *
  2814. * @param {Node} node - The node to add.
  2815. * @returns {Node} The node that was added to the stack.
  2816. */
  2817. function Stack( node ) {
  2818. if ( currentStack ) currentStack.addToStack( node );
  2819. return node;
  2820. }
  2821. addMethodChaining( 'toStack', Stack );
  2822. // types
  2823. const color = new ConvertType( 'color' );
  2824. const float = new ConvertType( 'float', cacheMaps.float );
  2825. const int = new ConvertType( 'int', cacheMaps.ints );
  2826. const uint = new ConvertType( 'uint', cacheMaps.uint );
  2827. const bool = new ConvertType( 'bool', cacheMaps.bool );
  2828. const vec2 = new ConvertType( 'vec2' );
  2829. const ivec2 = new ConvertType( 'ivec2' );
  2830. const uvec2 = new ConvertType( 'uvec2' );
  2831. const bvec2 = new ConvertType( 'bvec2' );
  2832. const vec3 = new ConvertType( 'vec3' );
  2833. const ivec3 = new ConvertType( 'ivec3' );
  2834. const uvec3 = new ConvertType( 'uvec3' );
  2835. const bvec3 = new ConvertType( 'bvec3' );
  2836. const vec4 = new ConvertType( 'vec4' );
  2837. const ivec4 = new ConvertType( 'ivec4' );
  2838. const uvec4 = new ConvertType( 'uvec4' );
  2839. const bvec4 = new ConvertType( 'bvec4' );
  2840. const mat2 = new ConvertType( 'mat2' );
  2841. const mat3 = new ConvertType( 'mat3' );
  2842. const mat4 = new ConvertType( 'mat4' );
  2843. const string = ( value = '' ) => nodeObject( new ConstNode( value, 'string' ) );
  2844. const arrayBuffer = ( value ) => nodeObject( new ConstNode( value, 'ArrayBuffer' ) );
  2845. addMethodChaining( 'toColor', color );
  2846. addMethodChaining( 'toFloat', float );
  2847. addMethodChaining( 'toInt', int );
  2848. addMethodChaining( 'toUint', uint );
  2849. addMethodChaining( 'toBool', bool );
  2850. addMethodChaining( 'toVec2', vec2 );
  2851. addMethodChaining( 'toIVec2', ivec2 );
  2852. addMethodChaining( 'toUVec2', uvec2 );
  2853. addMethodChaining( 'toBVec2', bvec2 );
  2854. addMethodChaining( 'toVec3', vec3 );
  2855. addMethodChaining( 'toIVec3', ivec3 );
  2856. addMethodChaining( 'toUVec3', uvec3 );
  2857. addMethodChaining( 'toBVec3', bvec3 );
  2858. addMethodChaining( 'toVec4', vec4 );
  2859. addMethodChaining( 'toIVec4', ivec4 );
  2860. addMethodChaining( 'toUVec4', uvec4 );
  2861. addMethodChaining( 'toBVec4', bvec4 );
  2862. addMethodChaining( 'toMat2', mat2 );
  2863. addMethodChaining( 'toMat3', mat3 );
  2864. addMethodChaining( 'toMat4', mat4 );
  2865. // basic nodes
  2866. const element = /*@__PURE__*/ nodeProxy( ArrayElementNode ).setParameterLength( 2 );
  2867. const convert = ( node, types ) => nodeObject( new ConvertNode( nodeObject( node ), types ) );
  2868. const split = ( node, channels ) => nodeObject( new SplitNode( nodeObject( node ), channels ) );
  2869. addMethodChaining( 'element', element );
  2870. addMethodChaining( 'convert', convert );
  2871. // deprecated
  2872. /**
  2873. * @tsl
  2874. * @function
  2875. * @deprecated since r176. Use {@link Stack} instead.
  2876. *
  2877. * @param {Node} node - The node to add.
  2878. * @returns {Function}
  2879. */
  2880. const append = ( node ) => { // @deprecated, r176
  2881. warn( 'TSL: append() has been renamed to Stack().' );
  2882. return Stack( node );
  2883. };
  2884. addMethodChaining( 'append', ( node ) => { // @deprecated, r176
  2885. warn( 'TSL: .append() has been renamed to .toStack().' );
  2886. return Stack( node );
  2887. } );
  2888. /**
  2889. * This class represents a shader property. It can be used
  2890. * to explicitly define a property and assign a value to it.
  2891. *
  2892. * ```js
  2893. * const threshold = property( 'float', 'threshold' ).assign( THRESHOLD );
  2894. *```
  2895. * `PropertyNode` is used by the engine to predefined common material properties
  2896. * for TSL code.
  2897. *
  2898. * @augments Node
  2899. */
  2900. class PropertyNode extends Node {
  2901. static get type() {
  2902. return 'PropertyNode';
  2903. }
  2904. /**
  2905. * Constructs a new property node.
  2906. *
  2907. * @param {string} nodeType - The type of the node.
  2908. * @param {?string} [name=null] - The name of the property in the shader.
  2909. * @param {boolean} [varying=false] - Whether this property is a varying or not.
  2910. */
  2911. constructor( nodeType, name = null, varying = false ) {
  2912. super( nodeType );
  2913. /**
  2914. * The name of the property in the shader. If no name is defined,
  2915. * the node system auto-generates one.
  2916. *
  2917. * @type {?string}
  2918. * @default null
  2919. */
  2920. this.name = name;
  2921. /**
  2922. * Whether this property is a varying or not.
  2923. *
  2924. * @type {boolean}
  2925. * @default false
  2926. */
  2927. this.varying = varying;
  2928. /**
  2929. * This flag can be used for type testing.
  2930. *
  2931. * @type {boolean}
  2932. * @readonly
  2933. * @default true
  2934. */
  2935. this.isPropertyNode = true;
  2936. /**
  2937. * This flag is used for global cache.
  2938. *
  2939. * @type {boolean}
  2940. * @default true
  2941. */
  2942. this.global = true;
  2943. }
  2944. customCacheKey() {
  2945. return hashString( this.type + ':' + ( this.name || '' ) + ':' + ( this.varying ? '1' : '0' ) );
  2946. }
  2947. getHash( builder ) {
  2948. return this.name || super.getHash( builder );
  2949. }
  2950. generate( builder ) {
  2951. let nodeVar;
  2952. if ( this.varying === true ) {
  2953. nodeVar = builder.getVaryingFromNode( this, this.name );
  2954. nodeVar.needsInterpolation = true;
  2955. } else {
  2956. nodeVar = builder.getVarFromNode( this, this.name );
  2957. }
  2958. return builder.getPropertyName( nodeVar );
  2959. }
  2960. }
  2961. /**
  2962. * TSL function for creating a property node.
  2963. *
  2964. * @tsl
  2965. * @function
  2966. * @param {string} type - The type of the node.
  2967. * @param {?string} [name=null] - The name of the property in the shader.
  2968. * @returns {PropertyNode}
  2969. */
  2970. const property = ( type, name ) => nodeObject( new PropertyNode( type, name ) );
  2971. /**
  2972. * TSL function for creating a varying property node.
  2973. *
  2974. * @tsl
  2975. * @function
  2976. * @param {string} type - The type of the node.
  2977. * @param {?string} [name=null] - The name of the varying in the shader.
  2978. * @returns {PropertyNode}
  2979. */
  2980. const varyingProperty = ( type, name ) => nodeObject( new PropertyNode( type, name, true ) );
  2981. /**
  2982. * TSL object that represents the shader variable `DiffuseColor`.
  2983. *
  2984. * @tsl
  2985. * @type {PropertyNode<vec4>}
  2986. */
  2987. const diffuseColor = /*@__PURE__*/ nodeImmutable( PropertyNode, 'vec4', 'DiffuseColor' );
  2988. /**
  2989. * TSL object that represents the shader variable `DiffuseContribution`.
  2990. *
  2991. * @tsl
  2992. * @type {PropertyNode<vec3>}
  2993. */
  2994. const diffuseContribution = /*@__PURE__*/ nodeImmutable( PropertyNode, 'vec3', 'DiffuseContribution' );
  2995. /**
  2996. * TSL object that represents the shader variable `EmissiveColor`.
  2997. *
  2998. * @tsl
  2999. * @type {PropertyNode<vec3>}
  3000. */
  3001. const emissive = /*@__PURE__*/ nodeImmutable( PropertyNode, 'vec3', 'EmissiveColor' );
  3002. /**
  3003. * TSL object that represents the shader variable `Roughness`.
  3004. *
  3005. * @tsl
  3006. * @type {PropertyNode<float>}
  3007. */
  3008. const roughness = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Roughness' );
  3009. /**
  3010. * TSL object that represents the shader variable `Metalness`.
  3011. *
  3012. * @tsl
  3013. * @type {PropertyNode<float>}
  3014. */
  3015. const metalness = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Metalness' );
  3016. /**
  3017. * TSL object that represents the shader variable `Clearcoat`.
  3018. *
  3019. * @tsl
  3020. * @type {PropertyNode<float>}
  3021. */
  3022. const clearcoat = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Clearcoat' );
  3023. /**
  3024. * TSL object that represents the shader variable `ClearcoatRoughness`.
  3025. *
  3026. * @tsl
  3027. * @type {PropertyNode<float>}
  3028. */
  3029. const clearcoatRoughness = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'ClearcoatRoughness' );
  3030. /**
  3031. * TSL object that represents the shader variable `Sheen`.
  3032. *
  3033. * @tsl
  3034. * @type {PropertyNode<vec3>}
  3035. */
  3036. const sheen = /*@__PURE__*/ nodeImmutable( PropertyNode, 'vec3', 'Sheen' );
  3037. /**
  3038. * TSL object that represents the shader variable `SheenRoughness`.
  3039. *
  3040. * @tsl
  3041. * @type {PropertyNode<float>}
  3042. */
  3043. const sheenRoughness = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'SheenRoughness' );
  3044. /**
  3045. * TSL object that represents the shader variable `Iridescence`.
  3046. *
  3047. * @tsl
  3048. * @type {PropertyNode<float>}
  3049. */
  3050. const iridescence = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Iridescence' );
  3051. /**
  3052. * TSL object that represents the shader variable `IridescenceIOR`.
  3053. *
  3054. * @tsl
  3055. * @type {PropertyNode<float>}
  3056. */
  3057. const iridescenceIOR = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'IridescenceIOR' );
  3058. /**
  3059. * TSL object that represents the shader variable `IridescenceThickness`.
  3060. *
  3061. * @tsl
  3062. * @type {PropertyNode<float>}
  3063. */
  3064. const iridescenceThickness = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'IridescenceThickness' );
  3065. /**
  3066. * TSL object that represents the shader variable `AlphaT`.
  3067. *
  3068. * @tsl
  3069. * @type {PropertyNode<float>}
  3070. */
  3071. const alphaT = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'AlphaT' );
  3072. /**
  3073. * TSL object that represents the shader variable `Anisotropy`.
  3074. *
  3075. * @tsl
  3076. * @type {PropertyNode<float>}
  3077. */
  3078. const anisotropy = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Anisotropy' );
  3079. /**
  3080. * TSL object that represents the shader variable `AnisotropyT`.
  3081. *
  3082. * @tsl
  3083. * @type {PropertyNode<vec3>}
  3084. */
  3085. const anisotropyT = /*@__PURE__*/ nodeImmutable( PropertyNode, 'vec3', 'AnisotropyT' );
  3086. /**
  3087. * TSL object that represents the shader variable `AnisotropyB`.
  3088. *
  3089. * @tsl
  3090. * @type {PropertyNode<vec3>}
  3091. */
  3092. const anisotropyB = /*@__PURE__*/ nodeImmutable( PropertyNode, 'vec3', 'AnisotropyB' );
  3093. /**
  3094. * TSL object that represents the shader variable `SpecularColor`.
  3095. *
  3096. * @tsl
  3097. * @type {PropertyNode<color>}
  3098. */
  3099. const specularColor = /*@__PURE__*/ nodeImmutable( PropertyNode, 'color', 'SpecularColor' );
  3100. /**
  3101. * TSL object that represents the shader variable `SpecularColorBlended`.
  3102. *
  3103. * @tsl
  3104. * @type {PropertyNode<color>}
  3105. */
  3106. const specularColorBlended = /*@__PURE__*/ nodeImmutable( PropertyNode, 'color', 'SpecularColorBlended' );
  3107. /**
  3108. * TSL object that represents the shader variable `SpecularF90`.
  3109. *
  3110. * @tsl
  3111. * @type {PropertyNode<float>}
  3112. */
  3113. const specularF90 = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'SpecularF90' );
  3114. /**
  3115. * TSL object that represents the shader variable `Shininess`.
  3116. *
  3117. * @tsl
  3118. * @type {PropertyNode<float>}
  3119. */
  3120. const shininess = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Shininess' );
  3121. /**
  3122. * TSL object that represents the shader variable `Output`.
  3123. *
  3124. * @tsl
  3125. * @type {PropertyNode<vec4>}
  3126. */
  3127. const output = /*@__PURE__*/ nodeImmutable( PropertyNode, 'vec4', 'Output' );
  3128. /**
  3129. * TSL object that represents the shader variable `dashSize`.
  3130. *
  3131. * @tsl
  3132. * @type {PropertyNode<float>}
  3133. */
  3134. const dashSize = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'dashSize' );
  3135. /**
  3136. * TSL object that represents the shader variable `gapSize`.
  3137. *
  3138. * @tsl
  3139. * @type {PropertyNode<float>}
  3140. */
  3141. const gapSize = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'gapSize' );
  3142. /**
  3143. * TSL object that represents the shader variable `pointWidth`.
  3144. *
  3145. * @tsl
  3146. * @type {PropertyNode<float>}
  3147. */
  3148. const pointWidth = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'pointWidth' );
  3149. /**
  3150. * TSL object that represents the shader variable `IOR`.
  3151. *
  3152. * @tsl
  3153. * @type {PropertyNode<float>}
  3154. */
  3155. const ior = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'IOR' );
  3156. /**
  3157. * TSL object that represents the shader variable `Transmission`.
  3158. *
  3159. * @tsl
  3160. * @type {PropertyNode<float>}
  3161. */
  3162. const transmission = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Transmission' );
  3163. /**
  3164. * TSL object that represents the shader variable `Thickness`.
  3165. *
  3166. * @tsl
  3167. * @type {PropertyNode<float>}
  3168. */
  3169. const thickness = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Thickness' );
  3170. /**
  3171. * TSL object that represents the shader variable `AttenuationDistance`.
  3172. *
  3173. * @tsl
  3174. * @type {PropertyNode<float>}
  3175. */
  3176. const attenuationDistance = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'AttenuationDistance' );
  3177. /**
  3178. * TSL object that represents the shader variable `AttenuationColor`.
  3179. *
  3180. * @tsl
  3181. * @type {PropertyNode<color>}
  3182. */
  3183. const attenuationColor = /*@__PURE__*/ nodeImmutable( PropertyNode, 'color', 'AttenuationColor' );
  3184. /**
  3185. * TSL object that represents the shader variable `Dispersion`.
  3186. *
  3187. * @tsl
  3188. * @type {PropertyNode<float>}
  3189. */
  3190. const dispersion = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Dispersion' );
  3191. /**
  3192. * This node can be used to group single instances of {@link UniformNode}
  3193. * and manage them as a uniform buffer.
  3194. *
  3195. * In most cases, the predefined nodes `objectGroup`, `renderGroup` and `frameGroup`
  3196. * will be used when defining the {@link UniformNode#groupNode} property.
  3197. *
  3198. * - `objectGroup`: Uniform buffer per object.
  3199. * - `renderGroup`: Shared uniform buffer, updated once per render call.
  3200. * - `frameGroup`: Shared uniform buffer, updated once per frame.
  3201. *
  3202. * @augments Node
  3203. */
  3204. class UniformGroupNode extends Node {
  3205. static get type() {
  3206. return 'UniformGroupNode';
  3207. }
  3208. /**
  3209. * Constructs a new uniform group node.
  3210. *
  3211. * @param {string} name - The name of the uniform group node.
  3212. * @param {boolean} [shared=false] - Whether this uniform group node is shared or not.
  3213. * @param {number} [order=1] - Influences the internal sorting.
  3214. */
  3215. constructor( name, shared = false, order = 1 ) {
  3216. super( 'string' );
  3217. /**
  3218. * The name of the uniform group node.
  3219. *
  3220. * @type {string}
  3221. */
  3222. this.name = name;
  3223. /**
  3224. * Whether this uniform group node is shared or not.
  3225. *
  3226. * @type {boolean}
  3227. * @default false
  3228. */
  3229. this.shared = shared;
  3230. /**
  3231. * Influences the internal sorting.
  3232. * TODO: Add details when this property should be changed.
  3233. *
  3234. * @type {number}
  3235. * @default 1
  3236. */
  3237. this.order = order;
  3238. /**
  3239. * This flag can be used for type testing.
  3240. *
  3241. * @type {boolean}
  3242. * @readonly
  3243. * @default true
  3244. */
  3245. this.isUniformGroup = true;
  3246. }
  3247. serialize( data ) {
  3248. super.serialize( data );
  3249. data.name = this.name;
  3250. data.version = this.version;
  3251. data.shared = this.shared;
  3252. }
  3253. deserialize( data ) {
  3254. super.deserialize( data );
  3255. this.name = data.name;
  3256. this.version = data.version;
  3257. this.shared = data.shared;
  3258. }
  3259. }
  3260. /**
  3261. * TSL function for creating a uniform group node with the given name.
  3262. *
  3263. * @tsl
  3264. * @function
  3265. * @param {string} name - The name of the uniform group node.
  3266. * @returns {UniformGroupNode}
  3267. */
  3268. const uniformGroup = ( name ) => new UniformGroupNode( name );
  3269. /**
  3270. * TSL function for creating a shared uniform group node with the given name and order.
  3271. *
  3272. * @tsl
  3273. * @function
  3274. * @param {string} name - The name of the uniform group node.
  3275. * @param {number} [order=0] - Influences the internal sorting.
  3276. * @returns {UniformGroupNode}
  3277. */
  3278. const sharedUniformGroup = ( name, order = 0 ) => new UniformGroupNode( name, true, order );
  3279. /**
  3280. * TSL object that represents a shared uniform group node which is updated once per frame.
  3281. *
  3282. * @tsl
  3283. * @type {UniformGroupNode}
  3284. */
  3285. const frameGroup = /*@__PURE__*/ sharedUniformGroup( 'frame' );
  3286. /**
  3287. * TSL object that represents a shared uniform group node which is updated once per render.
  3288. *
  3289. * @tsl
  3290. * @type {UniformGroupNode}
  3291. */
  3292. const renderGroup = /*@__PURE__*/ sharedUniformGroup( 'render' );
  3293. /**
  3294. * TSL object that represents a uniform group node which is updated once per object.
  3295. *
  3296. * @tsl
  3297. * @type {UniformGroupNode}
  3298. */
  3299. const objectGroup = /*@__PURE__*/ uniformGroup( 'object' );
  3300. /**
  3301. * Class for representing a uniform.
  3302. *
  3303. * @augments InputNode
  3304. */
  3305. class UniformNode extends InputNode {
  3306. static get type() {
  3307. return 'UniformNode';
  3308. }
  3309. /**
  3310. * Constructs a new uniform node.
  3311. *
  3312. * @param {any} value - The value of this node. Usually a JS primitive or three.js object (vector, matrix, color, texture).
  3313. * @param {?string} nodeType - The node type. If no explicit type is defined, the node tries to derive the type from its value.
  3314. */
  3315. constructor( value, nodeType = null ) {
  3316. super( value, nodeType );
  3317. /**
  3318. * This flag can be used for type testing.
  3319. *
  3320. * @type {boolean}
  3321. * @readonly
  3322. * @default true
  3323. */
  3324. this.isUniformNode = true;
  3325. /**
  3326. * The name or label of the uniform.
  3327. *
  3328. * @type {string}
  3329. * @default ''
  3330. */
  3331. this.name = '';
  3332. /**
  3333. * The uniform group of this uniform. By default, uniforms are
  3334. * managed per object but they might belong to a shared group
  3335. * which is updated per frame or render call.
  3336. *
  3337. * @type {UniformGroupNode}
  3338. */
  3339. this.groupNode = objectGroup;
  3340. }
  3341. /**
  3342. * Sets the {@link UniformNode#name} property.
  3343. *
  3344. * @param {string} name - The name of the uniform.
  3345. * @return {UniformNode} A reference to this node.
  3346. */
  3347. setName( name ) {
  3348. this.name = name;
  3349. return this;
  3350. }
  3351. /**
  3352. * Sets the {@link UniformNode#name} property.
  3353. *
  3354. * @deprecated
  3355. * @param {string} name - The name of the uniform.
  3356. * @return {UniformNode} A reference to this node.
  3357. */
  3358. label( name ) {
  3359. warn( 'TSL: "label()" has been deprecated. Use "setName()" instead.' ); // @deprecated r179
  3360. return this.setName( name );
  3361. }
  3362. /**
  3363. * Sets the {@link UniformNode#groupNode} property.
  3364. *
  3365. * @param {UniformGroupNode} group - The uniform group.
  3366. * @return {UniformNode} A reference to this node.
  3367. */
  3368. setGroup( group ) {
  3369. this.groupNode = group;
  3370. return this;
  3371. }
  3372. /**
  3373. * Returns the {@link UniformNode#groupNode}.
  3374. *
  3375. * @return {UniformGroupNode} The uniform group.
  3376. */
  3377. getGroup() {
  3378. return this.groupNode;
  3379. }
  3380. /**
  3381. * By default, this method returns the result of {@link Node#getHash} but derived
  3382. * classes might overwrite this method with a different implementation.
  3383. *
  3384. * @param {NodeBuilder} builder - The current node builder.
  3385. * @return {string} The uniform hash.
  3386. */
  3387. getUniformHash( builder ) {
  3388. return this.getHash( builder );
  3389. }
  3390. onUpdate( callback, updateType ) {
  3391. callback = callback.bind( this );
  3392. return super.onUpdate( ( frame ) => {
  3393. const value = callback( frame, this );
  3394. if ( value !== undefined ) {
  3395. this.value = value;
  3396. }
  3397. }, updateType );
  3398. }
  3399. getInputType( builder ) {
  3400. let type = super.getInputType( builder );
  3401. if ( type === 'bool' ) {
  3402. type = 'uint';
  3403. }
  3404. return type;
  3405. }
  3406. generate( builder, output ) {
  3407. const type = this.getNodeType( builder );
  3408. const hash = this.getUniformHash( builder );
  3409. let sharedNode = builder.getNodeFromHash( hash );
  3410. if ( sharedNode === undefined ) {
  3411. builder.setHashNode( this, hash );
  3412. sharedNode = this;
  3413. }
  3414. const sharedNodeType = sharedNode.getInputType( builder );
  3415. const nodeUniform = builder.getUniformFromNode( sharedNode, sharedNodeType, builder.shaderStage, this.name || builder.context.nodeName );
  3416. const uniformName = builder.getPropertyName( nodeUniform );
  3417. if ( builder.context.nodeName !== undefined ) delete builder.context.nodeName;
  3418. //
  3419. let snippet = uniformName;
  3420. if ( type === 'bool' ) {
  3421. // cache to variable
  3422. const nodeData = builder.getDataFromNode( this );
  3423. let propertyName = nodeData.propertyName;
  3424. if ( propertyName === undefined ) {
  3425. const nodeVar = builder.getVarFromNode( this, null, 'bool' );
  3426. propertyName = builder.getPropertyName( nodeVar );
  3427. nodeData.propertyName = propertyName;
  3428. snippet = builder.format( uniformName, sharedNodeType, type );
  3429. builder.addLineFlowCode( `${ propertyName } = ${ snippet }`, this );
  3430. }
  3431. snippet = propertyName;
  3432. }
  3433. return builder.format( snippet, type, output );
  3434. }
  3435. }
  3436. /**
  3437. * TSL function for creating a uniform node.
  3438. *
  3439. * @tsl
  3440. * @function
  3441. * @param {any|string} value - The value of this uniform or your type. Usually a JS primitive or three.js object (vector, matrix, color, texture).
  3442. * @param {string} [type] - The node type. If no explicit type is defined, the node tries to derive the type from its value.
  3443. * @returns {UniformNode}
  3444. */
  3445. const uniform = ( value, type ) => {
  3446. const nodeType = getConstNodeType( type || value );
  3447. if ( nodeType === value ) {
  3448. // if the value is a type but no having a value
  3449. value = getValueFromType( nodeType );
  3450. }
  3451. if ( value && value.isNode === true ) {
  3452. let v = value.value;
  3453. value.traverse( n => {
  3454. if ( n.isConstNode === true ) {
  3455. v = n.value;
  3456. }
  3457. } );
  3458. value = v;
  3459. }
  3460. return nodeObject( new UniformNode( value, nodeType ) );
  3461. };
  3462. /**
  3463. * ArrayNode represents a collection of nodes, typically created using the {@link array} function.
  3464. * ```js
  3465. * const colors = array( [
  3466. * vec3( 1, 0, 0 ),
  3467. * vec3( 0, 1, 0 ),
  3468. * vec3( 0, 0, 1 )
  3469. * ] );
  3470. *
  3471. * const redColor = tintColors.element( 0 );
  3472. * ```
  3473. *
  3474. * @augments TempNode
  3475. */
  3476. class ArrayNode extends TempNode {
  3477. static get type() {
  3478. return 'ArrayNode';
  3479. }
  3480. /**
  3481. * Constructs a new array node.
  3482. *
  3483. * @param {?string} nodeType - The data type of the elements.
  3484. * @param {number} count - Size of the array.
  3485. * @param {?Array<Node>} [values=null] - Array default values.
  3486. */
  3487. constructor( nodeType, count, values = null ) {
  3488. super( nodeType );
  3489. /**
  3490. * Array size.
  3491. *
  3492. * @type {number}
  3493. */
  3494. this.count = count;
  3495. /**
  3496. * Array default values.
  3497. *
  3498. * @type {?Array<Node>}
  3499. */
  3500. this.values = values;
  3501. /**
  3502. * This flag can be used for type testing.
  3503. *
  3504. * @type {boolean}
  3505. * @readonly
  3506. * @default true
  3507. */
  3508. this.isArrayNode = true;
  3509. }
  3510. /**
  3511. * Returns the number of elements in the node array.
  3512. *
  3513. * @param {NodeBuilder} builder - The current node builder.
  3514. * @return {number} The number of elements in the node array.
  3515. */
  3516. getArrayCount( /*builder*/ ) {
  3517. return this.count;
  3518. }
  3519. /**
  3520. * Returns the node's type.
  3521. *
  3522. * @param {NodeBuilder} builder - The current node builder.
  3523. * @return {string} The type of the node.
  3524. */
  3525. getNodeType( builder ) {
  3526. if ( this.nodeType === null ) {
  3527. this.nodeType = this.values[ 0 ].getNodeType( builder );
  3528. }
  3529. return this.nodeType;
  3530. }
  3531. /**
  3532. * Returns the node's type.
  3533. *
  3534. * @param {NodeBuilder} builder - The current node builder.
  3535. * @return {string} The type of the node.
  3536. */
  3537. getElementType( builder ) {
  3538. return this.getNodeType( builder );
  3539. }
  3540. /**
  3541. * This method builds the output node and returns the resulting array as a shader string.
  3542. *
  3543. * @param {NodeBuilder} builder - The current node builder.
  3544. * @return {string} The generated shader string.
  3545. */
  3546. generate( builder ) {
  3547. const type = this.getNodeType( builder );
  3548. return builder.generateArray( type, this.count, this.values );
  3549. }
  3550. }
  3551. /**
  3552. * TSL function for creating an array node.
  3553. *
  3554. * @tsl
  3555. * @function
  3556. * @param {string|Array<Node>} nodeTypeOrValues - A string representing the element type (e.g., 'vec3')
  3557. * or an array containing the default values (e.g., [ vec3() ]).
  3558. * @param {?number} [count] - Size of the array.
  3559. * @returns {ArrayNode}
  3560. */
  3561. const array = ( ...params ) => {
  3562. let node;
  3563. if ( params.length === 1 ) {
  3564. const values = params[ 0 ];
  3565. node = new ArrayNode( null, values.length, values );
  3566. } else {
  3567. const nodeType = params[ 0 ];
  3568. const count = params[ 1 ];
  3569. node = new ArrayNode( nodeType, count );
  3570. }
  3571. return nodeObject( node );
  3572. };
  3573. addMethodChaining( 'toArray', ( node, count ) => array( Array( count ).fill( node ) ) );
  3574. /**
  3575. * These node represents an assign operation. Meaning a node is assigned
  3576. * to another node.
  3577. *
  3578. * @augments TempNode
  3579. */
  3580. class AssignNode extends TempNode {
  3581. static get type() {
  3582. return 'AssignNode';
  3583. }
  3584. /**
  3585. * Constructs a new assign node.
  3586. *
  3587. * @param {Node} targetNode - The target node.
  3588. * @param {Node} sourceNode - The source type.
  3589. */
  3590. constructor( targetNode, sourceNode ) {
  3591. super();
  3592. /**
  3593. * The target node.
  3594. *
  3595. * @type {Node}
  3596. */
  3597. this.targetNode = targetNode;
  3598. /**
  3599. * The source node.
  3600. *
  3601. * @type {Node}
  3602. */
  3603. this.sourceNode = sourceNode;
  3604. /**
  3605. * This flag can be used for type testing.
  3606. *
  3607. * @type {boolean}
  3608. * @readonly
  3609. * @default true
  3610. */
  3611. this.isAssignNode = true;
  3612. }
  3613. /**
  3614. * Whether this node is used more than once in context of other nodes. This method
  3615. * is overwritten since it always returns `false` (assigns are unique).
  3616. *
  3617. * @return {boolean} A flag that indicates if there is more than one dependency to other nodes. Always `false`.
  3618. */
  3619. hasDependencies() {
  3620. return false;
  3621. }
  3622. getNodeType( builder, output ) {
  3623. return output !== 'void' ? this.targetNode.getNodeType( builder ) : 'void';
  3624. }
  3625. /**
  3626. * Whether a split is required when assigning source to target. This can happen when the component length of
  3627. * target and source data type does not match.
  3628. *
  3629. * @param {NodeBuilder} builder - The current node builder.
  3630. * @return {boolean} Whether a split is required when assigning source to target.
  3631. */
  3632. needsSplitAssign( builder ) {
  3633. const { targetNode } = this;
  3634. if ( builder.isAvailable( 'swizzleAssign' ) === false && targetNode.isSplitNode && targetNode.components.length > 1 ) {
  3635. const targetLength = builder.getTypeLength( targetNode.node.getNodeType( builder ) );
  3636. const assignDifferentVector = vectorComponents.join( '' ).slice( 0, targetLength ) !== targetNode.components;
  3637. return assignDifferentVector;
  3638. }
  3639. return false;
  3640. }
  3641. setup( builder ) {
  3642. const { targetNode, sourceNode } = this;
  3643. const scope = targetNode.getScope();
  3644. const targetProperties = builder.getNodeProperties( scope );
  3645. targetProperties.assign = true;
  3646. const properties = builder.getNodeProperties( this );
  3647. properties.sourceNode = sourceNode;
  3648. properties.targetNode = targetNode.context( { assign: true } );
  3649. }
  3650. generate( builder, output ) {
  3651. const { targetNode, sourceNode } = builder.getNodeProperties( this );
  3652. const needsSplitAssign = this.needsSplitAssign( builder );
  3653. const target = targetNode.build( builder );
  3654. const targetType = targetNode.getNodeType( builder );
  3655. const source = sourceNode.build( builder, targetType );
  3656. const sourceType = sourceNode.getNodeType( builder );
  3657. const nodeData = builder.getDataFromNode( this );
  3658. //
  3659. let snippet;
  3660. if ( nodeData.initialized === true ) {
  3661. if ( output !== 'void' ) {
  3662. snippet = target;
  3663. }
  3664. } else if ( needsSplitAssign ) {
  3665. const sourceVar = builder.getVarFromNode( this, null, targetType );
  3666. const sourceProperty = builder.getPropertyName( sourceVar );
  3667. builder.addLineFlowCode( `${ sourceProperty } = ${ source }`, this );
  3668. const splitNode = targetNode.node;
  3669. const splitTargetNode = splitNode.node.context( { assign: true } );
  3670. const targetRoot = splitTargetNode.build( builder );
  3671. for ( let i = 0; i < splitNode.components.length; i ++ ) {
  3672. const component = splitNode.components[ i ];
  3673. builder.addLineFlowCode( `${ targetRoot }.${ component } = ${ sourceProperty }[ ${ i } ]`, this );
  3674. }
  3675. if ( output !== 'void' ) {
  3676. snippet = target;
  3677. }
  3678. } else {
  3679. snippet = `${ target } = ${ source }`;
  3680. if ( output === 'void' || sourceType === 'void' ) {
  3681. builder.addLineFlowCode( snippet, this );
  3682. if ( output !== 'void' ) {
  3683. snippet = target;
  3684. }
  3685. }
  3686. }
  3687. nodeData.initialized = true;
  3688. return builder.format( snippet, targetType, output );
  3689. }
  3690. }
  3691. /**
  3692. * TSL function for creating an assign node.
  3693. *
  3694. * @tsl
  3695. * @function
  3696. * @param {Node} targetNode - The target node.
  3697. * @param {Node} sourceNode - The source type.
  3698. * @returns {AssignNode}
  3699. */
  3700. const assign = /*@__PURE__*/ nodeProxy( AssignNode ).setParameterLength( 2 );
  3701. addMethodChaining( 'assign', assign );
  3702. /**
  3703. * This module represents the call of a {@link FunctionNode}. Developers are usually not confronted
  3704. * with this module since they use the predefined TSL syntax `wgslFn` and `glslFn` which encapsulate
  3705. * this logic.
  3706. *
  3707. * @augments TempNode
  3708. */
  3709. class FunctionCallNode extends TempNode {
  3710. static get type() {
  3711. return 'FunctionCallNode';
  3712. }
  3713. /**
  3714. * Constructs a new function call node.
  3715. *
  3716. * @param {?FunctionNode} functionNode - The function node.
  3717. * @param {Object<string, Node>} [parameters={}] - The parameters for the function call.
  3718. */
  3719. constructor( functionNode = null, parameters = {} ) {
  3720. super();
  3721. /**
  3722. * The function node.
  3723. *
  3724. * @type {?FunctionNode}
  3725. * @default null
  3726. */
  3727. this.functionNode = functionNode;
  3728. /**
  3729. * The parameters of the function call.
  3730. *
  3731. * @type {Object<string, Node>}
  3732. * @default {}
  3733. */
  3734. this.parameters = parameters;
  3735. }
  3736. /**
  3737. * Sets the parameters of the function call node.
  3738. *
  3739. * @param {Object<string, Node>} parameters - The parameters to set.
  3740. * @return {FunctionCallNode} A reference to this node.
  3741. */
  3742. setParameters( parameters ) {
  3743. this.parameters = parameters;
  3744. return this;
  3745. }
  3746. /**
  3747. * Returns the parameters of the function call node.
  3748. *
  3749. * @return {Object<string, Node>} The parameters of this node.
  3750. */
  3751. getParameters() {
  3752. return this.parameters;
  3753. }
  3754. /**
  3755. * Returns the type of this function call node.
  3756. *
  3757. * @param {NodeBuilder} builder - The current node builder.
  3758. * @returns {string} The type of this node.
  3759. */
  3760. getNodeType( builder ) {
  3761. return this.functionNode.getNodeType( builder );
  3762. }
  3763. /**
  3764. * Returns the function node of this function call node.
  3765. *
  3766. * @param {NodeBuilder} builder - The current node builder.
  3767. * @param {string} [name] - The name of the member.
  3768. * @returns {string} The type of the member.
  3769. */
  3770. getMemberType( builder, name ) {
  3771. return this.functionNode.getMemberType( builder, name );
  3772. }
  3773. generate( builder ) {
  3774. const params = [];
  3775. const functionNode = this.functionNode;
  3776. const inputs = functionNode.getInputs( builder );
  3777. const parameters = this.parameters;
  3778. const generateInput = ( node, inputNode ) => {
  3779. const type = inputNode.type;
  3780. const pointer = type === 'pointer';
  3781. let output;
  3782. if ( pointer ) output = '&' + node.build( builder );
  3783. else output = node.build( builder, type );
  3784. return output;
  3785. };
  3786. if ( Array.isArray( parameters ) ) {
  3787. if ( parameters.length > inputs.length ) {
  3788. error( 'TSL: The number of provided parameters exceeds the expected number of inputs in \'Fn()\'.' );
  3789. parameters.length = inputs.length;
  3790. } else if ( parameters.length < inputs.length ) {
  3791. error( 'TSL: The number of provided parameters is less than the expected number of inputs in \'Fn()\'.' );
  3792. while ( parameters.length < inputs.length ) {
  3793. parameters.push( float( 0 ) );
  3794. }
  3795. }
  3796. for ( let i = 0; i < parameters.length; i ++ ) {
  3797. params.push( generateInput( parameters[ i ], inputs[ i ] ) );
  3798. }
  3799. } else {
  3800. for ( const inputNode of inputs ) {
  3801. const node = parameters[ inputNode.name ];
  3802. if ( node !== undefined ) {
  3803. params.push( generateInput( node, inputNode ) );
  3804. } else {
  3805. error( `TSL: Input '${ inputNode.name }' not found in \'Fn()\'.` );
  3806. params.push( generateInput( float( 0 ), inputNode ) );
  3807. }
  3808. }
  3809. }
  3810. const functionName = functionNode.build( builder, 'property' );
  3811. return `${ functionName }( ${ params.join( ', ' ) } )`;
  3812. }
  3813. }
  3814. const call = ( func, ...params ) => {
  3815. params = params.length > 1 || ( params[ 0 ] && params[ 0 ].isNode === true ) ? nodeArray( params ) : nodeObjects( params[ 0 ] );
  3816. return new FunctionCallNode( nodeObject( func ), params );
  3817. };
  3818. addMethodChaining( 'call', call );
  3819. const _vectorOperators = {
  3820. '==': 'equal',
  3821. '!=': 'notEqual',
  3822. '<': 'lessThan',
  3823. '>': 'greaterThan',
  3824. '<=': 'lessThanEqual',
  3825. '>=': 'greaterThanEqual',
  3826. '%': 'mod'
  3827. };
  3828. /**
  3829. * This node represents basic mathematical and logical operations like addition,
  3830. * subtraction or comparisons (e.g. `equal()`).
  3831. *
  3832. * @augments TempNode
  3833. */
  3834. class OperatorNode extends TempNode {
  3835. static get type() {
  3836. return 'OperatorNode';
  3837. }
  3838. /**
  3839. * Constructs a new operator node.
  3840. *
  3841. * @param {string} op - The operator.
  3842. * @param {Node} aNode - The first input.
  3843. * @param {Node} bNode - The second input.
  3844. * @param {...Node} params - Additional input parameters.
  3845. */
  3846. constructor( op, aNode, bNode, ...params ) {
  3847. super();
  3848. if ( params.length > 0 ) {
  3849. let finalOp = new OperatorNode( op, aNode, bNode );
  3850. for ( let i = 0; i < params.length - 1; i ++ ) {
  3851. finalOp = new OperatorNode( op, finalOp, params[ i ] );
  3852. }
  3853. aNode = finalOp;
  3854. bNode = params[ params.length - 1 ];
  3855. }
  3856. /**
  3857. * The operator.
  3858. *
  3859. * @type {string}
  3860. */
  3861. this.op = op;
  3862. /**
  3863. * The first input.
  3864. *
  3865. * @type {Node}
  3866. */
  3867. this.aNode = aNode;
  3868. /**
  3869. * The second input.
  3870. *
  3871. * @type {Node}
  3872. */
  3873. this.bNode = bNode;
  3874. /**
  3875. * This flag can be used for type testing.
  3876. *
  3877. * @type {boolean}
  3878. * @readonly
  3879. * @default true
  3880. */
  3881. this.isOperatorNode = true;
  3882. }
  3883. /**
  3884. * Returns the operator method name.
  3885. *
  3886. * @param {NodeBuilder} builder - The current node builder.
  3887. * @param {string} output - The output type.
  3888. * @returns {string} The operator method name.
  3889. */
  3890. getOperatorMethod( builder, output ) {
  3891. return builder.getMethod( _vectorOperators[ this.op ], output );
  3892. }
  3893. /**
  3894. * This method is overwritten since the node type is inferred from the operator
  3895. * and the input node types.
  3896. *
  3897. * @param {NodeBuilder} builder - The current node builder.
  3898. * @param {?string} [output=null] - The output type.
  3899. * @return {string} The node type.
  3900. */
  3901. getNodeType( builder, output = null ) {
  3902. const op = this.op;
  3903. const aNode = this.aNode;
  3904. const bNode = this.bNode;
  3905. const typeA = aNode.getNodeType( builder );
  3906. const typeB = bNode ? bNode.getNodeType( builder ) : null;
  3907. if ( typeA === 'void' || typeB === 'void' ) {
  3908. return output || 'void';
  3909. } else if ( op === '%' ) {
  3910. return typeA;
  3911. } else if ( op === '~' || op === '&' || op === '|' || op === '^' || op === '>>' || op === '<<' ) {
  3912. return builder.getIntegerType( typeA );
  3913. } else if ( op === '!' || op === '&&' || op === '||' || op === '^^' ) {
  3914. return 'bool';
  3915. } else if ( op === '==' || op === '!=' || op === '<' || op === '>' || op === '<=' || op === '>=' ) {
  3916. const typeLength = Math.max( builder.getTypeLength( typeA ), builder.getTypeLength( typeB ) );
  3917. return typeLength > 1 ? `bvec${ typeLength }` : 'bool';
  3918. } else {
  3919. // Handle matrix operations
  3920. if ( builder.isMatrix( typeA ) ) {
  3921. if ( typeB === 'float' ) {
  3922. return typeA; // matrix * scalar = matrix
  3923. } else if ( builder.isVector( typeB ) ) {
  3924. return builder.getVectorFromMatrix( typeA ); // matrix * vector
  3925. } else if ( builder.isMatrix( typeB ) ) {
  3926. return typeA; // matrix * matrix
  3927. }
  3928. } else if ( builder.isMatrix( typeB ) ) {
  3929. if ( typeA === 'float' ) {
  3930. return typeB; // scalar * matrix = matrix
  3931. } else if ( builder.isVector( typeA ) ) {
  3932. return builder.getVectorFromMatrix( typeB ); // vector * matrix
  3933. }
  3934. }
  3935. // Handle non-matrix cases
  3936. if ( builder.getTypeLength( typeB ) > builder.getTypeLength( typeA ) ) {
  3937. // anytype x anytype: use the greater length vector
  3938. return typeB;
  3939. }
  3940. return typeA;
  3941. }
  3942. }
  3943. generate( builder, output ) {
  3944. const op = this.op;
  3945. const { aNode, bNode } = this;
  3946. const type = this.getNodeType( builder, output );
  3947. let typeA = null;
  3948. let typeB = null;
  3949. if ( type !== 'void' ) {
  3950. typeA = aNode.getNodeType( builder );
  3951. typeB = bNode ? bNode.getNodeType( builder ) : null;
  3952. if ( op === '<' || op === '>' || op === '<=' || op === '>=' || op === '==' || op === '!=' ) {
  3953. if ( builder.isVector( typeA ) ) {
  3954. typeB = typeA;
  3955. } else if ( builder.isVector( typeB ) ) {
  3956. typeA = typeB;
  3957. } else if ( typeA !== typeB ) {
  3958. typeA = typeB = 'float';
  3959. }
  3960. } else if ( op === '>>' || op === '<<' ) {
  3961. typeA = type;
  3962. typeB = builder.changeComponentType( typeB, 'uint' );
  3963. } else if ( op === '%' ) {
  3964. typeA = type;
  3965. typeB = builder.isInteger( typeA ) && builder.isInteger( typeB ) ? typeB : typeA;
  3966. } else if ( builder.isMatrix( typeA ) ) {
  3967. if ( typeB === 'float' ) {
  3968. // Keep matrix type for typeA, but ensure typeB stays float
  3969. typeB = 'float';
  3970. } else if ( builder.isVector( typeB ) ) {
  3971. // matrix x vector
  3972. typeB = builder.getVectorFromMatrix( typeA );
  3973. } else if ( builder.isMatrix( typeB ) ) ; else {
  3974. typeA = typeB = type;
  3975. }
  3976. } else if ( builder.isMatrix( typeB ) ) {
  3977. if ( typeA === 'float' ) {
  3978. // Keep matrix type for typeB, but ensure typeA stays float
  3979. typeA = 'float';
  3980. } else if ( builder.isVector( typeA ) ) {
  3981. // vector x matrix
  3982. typeA = builder.getVectorFromMatrix( typeB );
  3983. } else {
  3984. typeA = typeB = type;
  3985. }
  3986. } else {
  3987. // anytype x anytype
  3988. typeA = typeB = type;
  3989. }
  3990. } else {
  3991. typeA = typeB = type;
  3992. }
  3993. const a = aNode.build( builder, typeA );
  3994. const b = bNode ? bNode.build( builder, typeB ) : null;
  3995. const fnOpSnippet = builder.getFunctionOperator( op );
  3996. if ( output !== 'void' ) {
  3997. const isGLSL = builder.renderer.coordinateSystem === WebGLCoordinateSystem;
  3998. if ( op === '==' || op === '!=' || op === '<' || op === '>' || op === '<=' || op === '>=' ) {
  3999. if ( isGLSL ) {
  4000. if ( builder.isVector( typeA ) ) {
  4001. return builder.format( `${ this.getOperatorMethod( builder, output ) }( ${ a }, ${ b } )`, type, output );
  4002. } else {
  4003. return builder.format( `( ${ a } ${ op } ${ b } )`, type, output );
  4004. }
  4005. } else {
  4006. // WGSL
  4007. return builder.format( `( ${ a } ${ op } ${ b } )`, type, output );
  4008. }
  4009. } else if ( op === '%' ) {
  4010. if ( builder.isInteger( typeB ) ) {
  4011. return builder.format( `( ${ a } % ${ b } )`, type, output );
  4012. } else {
  4013. return builder.format( `${ this.getOperatorMethod( builder, type ) }( ${ a }, ${ b } )`, type, output );
  4014. }
  4015. } else if ( op === '!' || op === '~' ) {
  4016. return builder.format( `(${op}${a})`, typeA, output );
  4017. } else if ( fnOpSnippet ) {
  4018. return builder.format( `${ fnOpSnippet }( ${ a }, ${ b } )`, type, output );
  4019. } else {
  4020. // Handle matrix operations
  4021. if ( builder.isMatrix( typeA ) && typeB === 'float' ) {
  4022. return builder.format( `( ${ b } ${ op } ${ a } )`, type, output );
  4023. } else if ( typeA === 'float' && builder.isMatrix( typeB ) ) {
  4024. return builder.format( `${ a } ${ op } ${ b }`, type, output );
  4025. } else {
  4026. let snippet = `( ${ a } ${ op } ${ b } )`;
  4027. if ( ! isGLSL && type === 'bool' && builder.isVector( typeA ) && builder.isVector( typeB ) ) {
  4028. snippet = `all${ snippet }`;
  4029. }
  4030. return builder.format( snippet, type, output );
  4031. }
  4032. }
  4033. } else if ( typeA !== 'void' ) {
  4034. if ( fnOpSnippet ) {
  4035. return builder.format( `${ fnOpSnippet }( ${ a }, ${ b } )`, type, output );
  4036. } else {
  4037. if ( builder.isMatrix( typeA ) && typeB === 'float' ) {
  4038. return builder.format( `${ b } ${ op } ${ a }`, type, output );
  4039. } else {
  4040. return builder.format( `${ a } ${ op } ${ b }`, type, output );
  4041. }
  4042. }
  4043. }
  4044. }
  4045. serialize( data ) {
  4046. super.serialize( data );
  4047. data.op = this.op;
  4048. }
  4049. deserialize( data ) {
  4050. super.deserialize( data );
  4051. this.op = data.op;
  4052. }
  4053. }
  4054. /**
  4055. * Returns the addition of two or more value.
  4056. *
  4057. * @tsl
  4058. * @function
  4059. * @param {Node} a - The first input.
  4060. * @param {Node} b - The second input.
  4061. * @param {...Node} params - Additional input parameters.
  4062. * @returns {OperatorNode}
  4063. */
  4064. const add = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '+' ).setParameterLength( 2, Infinity ).setName( 'add' );
  4065. /**
  4066. * Returns the subtraction of two or more value.
  4067. *
  4068. * @tsl
  4069. * @function
  4070. * @param {Node} a - The first input.
  4071. * @param {Node} b - The second input.
  4072. * @param {...Node} params - Additional input parameters.
  4073. * @returns {OperatorNode}
  4074. */
  4075. const sub = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '-' ).setParameterLength( 2, Infinity ).setName( 'sub' );
  4076. /**
  4077. * Returns the multiplication of two or more value.
  4078. *
  4079. * @tsl
  4080. * @function
  4081. * @param {Node} a - The first input.
  4082. * @param {Node} b - The second input.
  4083. * @param {...Node} params - Additional input parameters.
  4084. * @returns {OperatorNode}
  4085. */
  4086. const mul = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '*' ).setParameterLength( 2, Infinity ).setName( 'mul' );
  4087. /**
  4088. * Returns the division of two or more value.
  4089. *
  4090. * @tsl
  4091. * @function
  4092. * @param {Node} a - The first input.
  4093. * @param {Node} b - The second input.
  4094. * @param {...Node} params - Additional input parameters.
  4095. * @returns {OperatorNode}
  4096. */
  4097. const div = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '/' ).setParameterLength( 2, Infinity ).setName( 'div' );
  4098. /**
  4099. * Computes the remainder of dividing the first node by the second one.
  4100. *
  4101. * @tsl
  4102. * @function
  4103. * @param {Node} a - The first input.
  4104. * @param {Node} b - The second input.
  4105. * @returns {OperatorNode}
  4106. */
  4107. const mod = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '%' ).setParameterLength( 2 ).setName( 'mod' );
  4108. /**
  4109. * Checks if two nodes are equal.
  4110. *
  4111. * @tsl
  4112. * @function
  4113. * @param {Node} a - The first input.
  4114. * @param {Node} b - The second input.
  4115. * @returns {OperatorNode}
  4116. */
  4117. const equal = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '==' ).setParameterLength( 2 ).setName( 'equal' );
  4118. /**
  4119. * Checks if two nodes are not equal.
  4120. *
  4121. * @tsl
  4122. * @function
  4123. * @param {Node} a - The first input.
  4124. * @param {Node} b - The second input.
  4125. * @returns {OperatorNode}
  4126. */
  4127. const notEqual = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '!=' ).setParameterLength( 2 ).setName( 'notEqual' );
  4128. /**
  4129. * Checks if the first node is less than the second.
  4130. *
  4131. * @tsl
  4132. * @function
  4133. * @param {Node} a - The first input.
  4134. * @param {Node} b - The second input.
  4135. * @returns {OperatorNode}
  4136. */
  4137. const lessThan = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '<' ).setParameterLength( 2 ).setName( 'lessThan' );
  4138. /**
  4139. * Checks if the first node is greater than the second.
  4140. *
  4141. * @tsl
  4142. * @function
  4143. * @param {Node} a - The first input.
  4144. * @param {Node} b - The second input.
  4145. * @returns {OperatorNode}
  4146. */
  4147. const greaterThan = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '>' ).setParameterLength( 2 ).setName( 'greaterThan' );
  4148. /**
  4149. * Checks if the first node is less than or equal to the second.
  4150. *
  4151. * @tsl
  4152. * @function
  4153. * @param {Node} a - The first input.
  4154. * @param {Node} b - The second input.
  4155. * @returns {OperatorNode}
  4156. */
  4157. const lessThanEqual = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '<=' ).setParameterLength( 2 ).setName( 'lessThanEqual' );
  4158. /**
  4159. * Checks if the first node is greater than or equal to the second.
  4160. *
  4161. * @tsl
  4162. * @function
  4163. * @param {Node} a - The first input.
  4164. * @param {Node} b - The second input.
  4165. * @returns {OperatorNode}
  4166. */
  4167. const greaterThanEqual = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '>=' ).setParameterLength( 2 ).setName( 'greaterThanEqual' );
  4168. /**
  4169. * Performs a logical AND operation on multiple nodes.
  4170. *
  4171. * @tsl
  4172. * @function
  4173. * @param {...Node} nodes - The input nodes to be combined using AND.
  4174. * @returns {OperatorNode}
  4175. */
  4176. const and = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '&&' ).setParameterLength( 2, Infinity ).setName( 'and' );
  4177. /**
  4178. * Performs a logical OR operation on multiple nodes.
  4179. *
  4180. * @tsl
  4181. * @function
  4182. * @param {...Node} nodes - The input nodes to be combined using OR.
  4183. * @returns {OperatorNode}
  4184. */
  4185. const or = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '||' ).setParameterLength( 2, Infinity ).setName( 'or' );
  4186. /**
  4187. * Performs logical NOT on a node.
  4188. *
  4189. * @tsl
  4190. * @function
  4191. * @param {Node} value - The value.
  4192. * @returns {OperatorNode}
  4193. */
  4194. const not = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '!' ).setParameterLength( 1 ).setName( 'not' );
  4195. /**
  4196. * Performs logical XOR on two nodes.
  4197. *
  4198. * @tsl
  4199. * @function
  4200. * @param {Node} a - The first input.
  4201. * @param {Node} b - The second input.
  4202. * @returns {OperatorNode}
  4203. */
  4204. const xor = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '^^' ).setParameterLength( 2 ).setName( 'xor' );
  4205. /**
  4206. * Performs bitwise AND on two nodes.
  4207. *
  4208. * @tsl
  4209. * @function
  4210. * @param {Node} a - The first input.
  4211. * @param {Node} b - The second input.
  4212. * @returns {OperatorNode}
  4213. */
  4214. const bitAnd = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '&' ).setParameterLength( 2 ).setName( 'bitAnd' );
  4215. /**
  4216. * Performs bitwise NOT on a node.
  4217. *
  4218. * @tsl
  4219. * @function
  4220. * @param {Node} a - The first input.
  4221. * @param {Node} b - The second input.
  4222. * @returns {OperatorNode}
  4223. */
  4224. const bitNot = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '~' ).setParameterLength( 1 ).setName( 'bitNot' );
  4225. /**
  4226. * Performs bitwise OR on two nodes.
  4227. *
  4228. * @tsl
  4229. * @function
  4230. * @param {Node} a - The first input.
  4231. * @param {Node} b - The second input.
  4232. * @returns {OperatorNode}
  4233. */
  4234. const bitOr = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '|' ).setParameterLength( 2 ).setName( 'bitOr' );
  4235. /**
  4236. * Performs bitwise XOR on two nodes.
  4237. *
  4238. * @tsl
  4239. * @function
  4240. * @param {Node} a - The first input.
  4241. * @param {Node} b - The second input.
  4242. * @returns {OperatorNode}
  4243. */
  4244. const bitXor = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '^' ).setParameterLength( 2 ).setName( 'bitXor' );
  4245. /**
  4246. * Shifts a node to the left.
  4247. *
  4248. * @tsl
  4249. * @function
  4250. * @param {Node} a - The node to shift.
  4251. * @param {Node} b - The value to shift.
  4252. * @returns {OperatorNode}
  4253. */
  4254. const shiftLeft = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '<<' ).setParameterLength( 2 ).setName( 'shiftLeft' );
  4255. /**
  4256. * Shifts a node to the right.
  4257. *
  4258. * @tsl
  4259. * @function
  4260. * @param {Node} a - The node to shift.
  4261. * @param {Node} b - The value to shift.
  4262. * @returns {OperatorNode}
  4263. */
  4264. const shiftRight = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '>>' ).setParameterLength( 2 ).setName( 'shiftRight' );
  4265. /**
  4266. * Increments a node by 1.
  4267. *
  4268. * @tsl
  4269. * @function
  4270. * @param {Node} a - The node to increment.
  4271. * @returns {OperatorNode}
  4272. */
  4273. const incrementBefore = Fn( ( [ a ] ) => {
  4274. a.addAssign( 1 );
  4275. return a;
  4276. } );
  4277. /**
  4278. * Decrements a node by 1.
  4279. *
  4280. * @tsl
  4281. * @function
  4282. * @param {Node} a - The node to decrement.
  4283. * @returns {OperatorNode}
  4284. */
  4285. const decrementBefore = Fn( ( [ a ] ) => {
  4286. a.subAssign( 1 );
  4287. return a;
  4288. } );
  4289. /**
  4290. * Increments a node by 1 and returns the previous value.
  4291. *
  4292. * @tsl
  4293. * @function
  4294. * @param {Node} a - The node to increment.
  4295. * @returns {OperatorNode}
  4296. */
  4297. const increment = /*@__PURE__*/ Fn( ( [ a ] ) => {
  4298. const temp = int( a ).toConst();
  4299. a.addAssign( 1 );
  4300. return temp;
  4301. } );
  4302. /**
  4303. * Decrements a node by 1 and returns the previous value.
  4304. *
  4305. * @tsl
  4306. * @function
  4307. * @param {Node} a - The node to decrement.
  4308. * @returns {OperatorNode}
  4309. */
  4310. const decrement = /*@__PURE__*/ Fn( ( [ a ] ) => {
  4311. const temp = int( a ).toConst();
  4312. a.subAssign( 1 );
  4313. return temp;
  4314. } );
  4315. addMethodChaining( 'add', add );
  4316. addMethodChaining( 'sub', sub );
  4317. addMethodChaining( 'mul', mul );
  4318. addMethodChaining( 'div', div );
  4319. addMethodChaining( 'mod', mod );
  4320. addMethodChaining( 'equal', equal );
  4321. addMethodChaining( 'notEqual', notEqual );
  4322. addMethodChaining( 'lessThan', lessThan );
  4323. addMethodChaining( 'greaterThan', greaterThan );
  4324. addMethodChaining( 'lessThanEqual', lessThanEqual );
  4325. addMethodChaining( 'greaterThanEqual', greaterThanEqual );
  4326. addMethodChaining( 'and', and );
  4327. addMethodChaining( 'or', or );
  4328. addMethodChaining( 'not', not );
  4329. addMethodChaining( 'xor', xor );
  4330. addMethodChaining( 'bitAnd', bitAnd );
  4331. addMethodChaining( 'bitNot', bitNot );
  4332. addMethodChaining( 'bitOr', bitOr );
  4333. addMethodChaining( 'bitXor', bitXor );
  4334. addMethodChaining( 'shiftLeft', shiftLeft );
  4335. addMethodChaining( 'shiftRight', shiftRight );
  4336. addMethodChaining( 'incrementBefore', incrementBefore );
  4337. addMethodChaining( 'decrementBefore', decrementBefore );
  4338. addMethodChaining( 'increment', increment );
  4339. addMethodChaining( 'decrement', decrement );
  4340. /**
  4341. * @tsl
  4342. * @function
  4343. * @deprecated since r175. Use {@link mod} instead.
  4344. *
  4345. * @param {Node} a - The first input.
  4346. * @param {Node} b - The second input.
  4347. * @returns {OperatorNode}
  4348. */
  4349. const modInt = ( a, b ) => { // @deprecated, r175
  4350. warn( 'TSL: "modInt()" is deprecated. Use "mod( int( ... ) )" instead.' );
  4351. return mod( int( a ), int( b ) );
  4352. };
  4353. addMethodChaining( 'modInt', modInt );
  4354. /**
  4355. * This node represents a variety of mathematical methods available in shaders.
  4356. * They are divided into three categories:
  4357. *
  4358. * - Methods with one input like `sin`, `cos` or `normalize`.
  4359. * - Methods with two inputs like `dot`, `cross` or `pow`.
  4360. * - Methods with three inputs like `mix`, `clamp` or `smoothstep`.
  4361. *
  4362. * @augments TempNode
  4363. */
  4364. class MathNode extends TempNode {
  4365. static get type() {
  4366. return 'MathNode';
  4367. }
  4368. /**
  4369. * Constructs a new math node.
  4370. *
  4371. * @param {string} method - The method name.
  4372. * @param {Node} aNode - The first input.
  4373. * @param {?Node} [bNode=null] - The second input.
  4374. * @param {?Node} [cNode=null] - The third input.
  4375. */
  4376. constructor( method, aNode, bNode = null, cNode = null ) {
  4377. super();
  4378. // Allow the max() and min() functions to take an arbitrary number of arguments.
  4379. if ( ( method === MathNode.MAX || method === MathNode.MIN ) && arguments.length > 3 ) {
  4380. let finalOp = new MathNode( method, aNode, bNode );
  4381. for ( let i = 2; i < arguments.length - 1; i ++ ) {
  4382. finalOp = new MathNode( method, finalOp, arguments[ i ] );
  4383. }
  4384. aNode = finalOp;
  4385. bNode = arguments[ arguments.length - 1 ];
  4386. cNode = null;
  4387. }
  4388. /**
  4389. * The method name.
  4390. *
  4391. * @type {string}
  4392. */
  4393. this.method = method;
  4394. /**
  4395. * The first input.
  4396. *
  4397. * @type {Node}
  4398. */
  4399. this.aNode = aNode;
  4400. /**
  4401. * The second input.
  4402. *
  4403. * @type {?Node}
  4404. * @default null
  4405. */
  4406. this.bNode = bNode;
  4407. /**
  4408. * The third input.
  4409. *
  4410. * @type {?Node}
  4411. * @default null
  4412. */
  4413. this.cNode = cNode;
  4414. /**
  4415. * This flag can be used for type testing.
  4416. *
  4417. * @type {boolean}
  4418. * @readonly
  4419. * @default true
  4420. */
  4421. this.isMathNode = true;
  4422. }
  4423. /**
  4424. * The input type is inferred from the node types of the input nodes.
  4425. *
  4426. * @param {NodeBuilder} builder - The current node builder.
  4427. * @return {string} The input type.
  4428. */
  4429. getInputType( builder ) {
  4430. const aType = this.aNode.getNodeType( builder );
  4431. const bType = this.bNode ? this.bNode.getNodeType( builder ) : null;
  4432. const cType = this.cNode ? this.cNode.getNodeType( builder ) : null;
  4433. const aLen = builder.isMatrix( aType ) ? 0 : builder.getTypeLength( aType );
  4434. const bLen = builder.isMatrix( bType ) ? 0 : builder.getTypeLength( bType );
  4435. const cLen = builder.isMatrix( cType ) ? 0 : builder.getTypeLength( cType );
  4436. if ( aLen > bLen && aLen > cLen ) {
  4437. return aType;
  4438. } else if ( bLen > cLen ) {
  4439. return bType;
  4440. } else if ( cLen > aLen ) {
  4441. return cType;
  4442. }
  4443. return aType;
  4444. }
  4445. /**
  4446. * The selected method as well as the input type determine the node type of this node.
  4447. *
  4448. * @param {NodeBuilder} builder - The current node builder.
  4449. * @return {string} The node type.
  4450. */
  4451. getNodeType( builder ) {
  4452. const method = this.method;
  4453. if ( method === MathNode.LENGTH || method === MathNode.DISTANCE || method === MathNode.DOT ) {
  4454. return 'float';
  4455. } else if ( method === MathNode.CROSS ) {
  4456. return 'vec3';
  4457. } else if ( method === MathNode.ALL || method === MathNode.ANY ) {
  4458. return 'bool';
  4459. } else if ( method === MathNode.EQUALS ) {
  4460. return builder.changeComponentType( this.aNode.getNodeType( builder ), 'bool' );
  4461. } else {
  4462. return this.getInputType( builder );
  4463. }
  4464. }
  4465. setup( builder ) {
  4466. const { aNode, bNode, method } = this;
  4467. let outputNode = null;
  4468. if ( method === MathNode.ONE_MINUS ) {
  4469. outputNode = sub( 1.0, aNode );
  4470. } else if ( method === MathNode.RECIPROCAL ) {
  4471. outputNode = div( 1.0, aNode );
  4472. } else if ( method === MathNode.DIFFERENCE ) {
  4473. outputNode = abs( sub( aNode, bNode ) );
  4474. } else if ( method === MathNode.TRANSFORM_DIRECTION ) {
  4475. // dir can be either a direction vector or a normal vector
  4476. // upper-left 3x3 of matrix is assumed to be orthogonal
  4477. let tA = aNode;
  4478. let tB = bNode;
  4479. if ( builder.isMatrix( tA.getNodeType( builder ) ) ) {
  4480. tB = vec4( vec3( tB ), 0.0 );
  4481. } else {
  4482. tA = vec4( vec3( tA ), 0.0 );
  4483. }
  4484. const mulNode = mul( tA, tB ).xyz;
  4485. outputNode = normalize( mulNode );
  4486. }
  4487. if ( outputNode !== null ) {
  4488. return outputNode;
  4489. } else {
  4490. return super.setup( builder );
  4491. }
  4492. }
  4493. generate( builder, output ) {
  4494. const properties = builder.getNodeProperties( this );
  4495. if ( properties.outputNode ) {
  4496. return super.generate( builder, output );
  4497. }
  4498. let method = this.method;
  4499. const type = this.getNodeType( builder );
  4500. const inputType = this.getInputType( builder );
  4501. const a = this.aNode;
  4502. const b = this.bNode;
  4503. const c = this.cNode;
  4504. const coordinateSystem = builder.renderer.coordinateSystem;
  4505. if ( method === MathNode.NEGATE ) {
  4506. return builder.format( '( - ' + a.build( builder, inputType ) + ' )', type, output );
  4507. } else {
  4508. const params = [];
  4509. if ( method === MathNode.CROSS ) {
  4510. params.push(
  4511. a.build( builder, type ),
  4512. b.build( builder, type )
  4513. );
  4514. } else if ( coordinateSystem === WebGLCoordinateSystem && method === MathNode.STEP ) {
  4515. params.push(
  4516. a.build( builder, builder.getTypeLength( a.getNodeType( builder ) ) === 1 ? 'float' : inputType ),
  4517. b.build( builder, inputType )
  4518. );
  4519. } else if ( coordinateSystem === WebGLCoordinateSystem && ( method === MathNode.MIN || method === MathNode.MAX ) ) {
  4520. params.push(
  4521. a.build( builder, inputType ),
  4522. b.build( builder, builder.getTypeLength( b.getNodeType( builder ) ) === 1 ? 'float' : inputType )
  4523. );
  4524. } else if ( method === MathNode.REFRACT ) {
  4525. params.push(
  4526. a.build( builder, inputType ),
  4527. b.build( builder, inputType ),
  4528. c.build( builder, 'float' )
  4529. );
  4530. } else if ( method === MathNode.MIX ) {
  4531. params.push(
  4532. a.build( builder, inputType ),
  4533. b.build( builder, inputType ),
  4534. c.build( builder, builder.getTypeLength( c.getNodeType( builder ) ) === 1 ? 'float' : inputType )
  4535. );
  4536. } else {
  4537. if ( coordinateSystem === WebGPUCoordinateSystem && method === MathNode.ATAN && b !== null ) {
  4538. method = 'atan2';
  4539. }
  4540. if ( builder.shaderStage !== 'fragment' && ( method === MathNode.DFDX || method === MathNode.DFDY ) ) {
  4541. warn( `TSL: '${ method }' is not supported in the ${ builder.shaderStage } stage.` );
  4542. method = '/*' + method + '*/';
  4543. }
  4544. params.push( a.build( builder, inputType ) );
  4545. if ( b !== null ) params.push( b.build( builder, inputType ) );
  4546. if ( c !== null ) params.push( c.build( builder, inputType ) );
  4547. }
  4548. return builder.format( `${ builder.getMethod( method, type ) }( ${params.join( ', ' )} )`, type, output );
  4549. }
  4550. }
  4551. serialize( data ) {
  4552. super.serialize( data );
  4553. data.method = this.method;
  4554. }
  4555. deserialize( data ) {
  4556. super.deserialize( data );
  4557. this.method = data.method;
  4558. }
  4559. }
  4560. // 1 input
  4561. MathNode.ALL = 'all';
  4562. MathNode.ANY = 'any';
  4563. MathNode.RADIANS = 'radians';
  4564. MathNode.DEGREES = 'degrees';
  4565. MathNode.EXP = 'exp';
  4566. MathNode.EXP2 = 'exp2';
  4567. MathNode.LOG = 'log';
  4568. MathNode.LOG2 = 'log2';
  4569. MathNode.SQRT = 'sqrt';
  4570. MathNode.INVERSE_SQRT = 'inversesqrt';
  4571. MathNode.FLOOR = 'floor';
  4572. MathNode.CEIL = 'ceil';
  4573. MathNode.NORMALIZE = 'normalize';
  4574. MathNode.FRACT = 'fract';
  4575. MathNode.SIN = 'sin';
  4576. MathNode.COS = 'cos';
  4577. MathNode.TAN = 'tan';
  4578. MathNode.ASIN = 'asin';
  4579. MathNode.ACOS = 'acos';
  4580. MathNode.ATAN = 'atan';
  4581. MathNode.ABS = 'abs';
  4582. MathNode.SIGN = 'sign';
  4583. MathNode.LENGTH = 'length';
  4584. MathNode.NEGATE = 'negate';
  4585. MathNode.ONE_MINUS = 'oneMinus';
  4586. MathNode.DFDX = 'dFdx';
  4587. MathNode.DFDY = 'dFdy';
  4588. MathNode.ROUND = 'round';
  4589. MathNode.RECIPROCAL = 'reciprocal';
  4590. MathNode.TRUNC = 'trunc';
  4591. MathNode.FWIDTH = 'fwidth';
  4592. MathNode.TRANSPOSE = 'transpose';
  4593. MathNode.DETERMINANT = 'determinant';
  4594. MathNode.INVERSE = 'inverse';
  4595. // 2 inputs
  4596. MathNode.EQUALS = 'equals';
  4597. MathNode.MIN = 'min';
  4598. MathNode.MAX = 'max';
  4599. MathNode.STEP = 'step';
  4600. MathNode.REFLECT = 'reflect';
  4601. MathNode.DISTANCE = 'distance';
  4602. MathNode.DIFFERENCE = 'difference';
  4603. MathNode.DOT = 'dot';
  4604. MathNode.CROSS = 'cross';
  4605. MathNode.POW = 'pow';
  4606. MathNode.TRANSFORM_DIRECTION = 'transformDirection';
  4607. // 3 inputs
  4608. MathNode.MIX = 'mix';
  4609. MathNode.CLAMP = 'clamp';
  4610. MathNode.REFRACT = 'refract';
  4611. MathNode.SMOOTHSTEP = 'smoothstep';
  4612. MathNode.FACEFORWARD = 'faceforward';
  4613. // 1 inputs
  4614. /**
  4615. * A small value used to handle floating-point precision errors.
  4616. *
  4617. * @tsl
  4618. * @type {Node<float>}
  4619. */
  4620. const EPSILON = /*@__PURE__*/ float( 1e-6 );
  4621. /**
  4622. * Represents infinity.
  4623. *
  4624. * @tsl
  4625. * @type {Node<float>}
  4626. */
  4627. const INFINITY = /*@__PURE__*/ float( 1e6 );
  4628. /**
  4629. * Represents PI.
  4630. *
  4631. * @tsl
  4632. * @type {Node<float>}
  4633. */
  4634. const PI = /*@__PURE__*/ float( Math.PI );
  4635. /**
  4636. * Represents PI * 2. Please use the non-deprecated version `TWO_PI`.
  4637. *
  4638. * @tsl
  4639. * @deprecated
  4640. * @type {Node<float>}
  4641. */
  4642. const PI2 = /*@__PURE__*/ float( Math.PI * 2 ); // @deprecated r181
  4643. /**
  4644. * Represents PI * 2.
  4645. *
  4646. * @tsl
  4647. * @type {Node<float>}
  4648. */
  4649. const TWO_PI = /*@__PURE__*/ float( Math.PI * 2 );
  4650. /**
  4651. * Represents PI / 2.
  4652. *
  4653. * @tsl
  4654. * @type {Node<float>}
  4655. */
  4656. const HALF_PI = /*@__PURE__*/ float( Math.PI * 0.5 );
  4657. /**
  4658. * Returns `true` if all components of `x` are `true`.
  4659. *
  4660. * @tsl
  4661. * @function
  4662. * @param {Node | number} x - The parameter.
  4663. * @returns {Node<bool>}
  4664. */
  4665. const all = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.ALL ).setParameterLength( 1 );
  4666. /**
  4667. * Returns `true` if any components of `x` are `true`.
  4668. *
  4669. * @tsl
  4670. * @function
  4671. * @param {Node | number} x - The parameter.
  4672. * @returns {Node<bool>}
  4673. */
  4674. const any = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.ANY ).setParameterLength( 1 );
  4675. /**
  4676. * Converts a quantity in degrees to radians.
  4677. *
  4678. * @tsl
  4679. * @function
  4680. * @param {Node | number} x - The input in degrees.
  4681. * @returns {Node}
  4682. */
  4683. const radians = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.RADIANS ).setParameterLength( 1 );
  4684. /**
  4685. * Convert a quantity in radians to degrees.
  4686. *
  4687. * @tsl
  4688. * @function
  4689. * @param {Node | number} x - The input in radians.
  4690. * @returns {Node}
  4691. */
  4692. const degrees = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.DEGREES ).setParameterLength( 1 );
  4693. /**
  4694. * Returns the natural exponentiation of the parameter.
  4695. *
  4696. * @tsl
  4697. * @function
  4698. * @param {Node | number} x - The parameter.
  4699. * @returns {Node}
  4700. */
  4701. const exp = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.EXP ).setParameterLength( 1 );
  4702. /**
  4703. * Returns 2 raised to the power of the parameter.
  4704. *
  4705. * @tsl
  4706. * @function
  4707. * @param {Node | number} x - The parameter.
  4708. * @returns {Node}
  4709. */
  4710. const exp2 = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.EXP2 ).setParameterLength( 1 );
  4711. /**
  4712. * Returns the natural logarithm of the parameter.
  4713. *
  4714. * @tsl
  4715. * @function
  4716. * @param {Node | number} x - The parameter.
  4717. * @returns {Node}
  4718. */
  4719. const log = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.LOG ).setParameterLength( 1 );
  4720. /**
  4721. * Returns the base 2 logarithm of the parameter.
  4722. *
  4723. * @tsl
  4724. * @function
  4725. * @param {Node | number} x - The parameter.
  4726. * @returns {Node}
  4727. */
  4728. const log2 = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.LOG2 ).setParameterLength( 1 );
  4729. /**
  4730. * Returns the square root of the parameter.
  4731. *
  4732. * @tsl
  4733. * @function
  4734. * @param {Node | number} x - The parameter.
  4735. * @returns {Node}
  4736. */
  4737. const sqrt = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.SQRT ).setParameterLength( 1 );
  4738. /**
  4739. * Returns the inverse of the square root of the parameter.
  4740. *
  4741. * @tsl
  4742. * @function
  4743. * @param {Node | number} x - The parameter.
  4744. * @returns {Node}
  4745. */
  4746. const inverseSqrt = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.INVERSE_SQRT ).setParameterLength( 1 );
  4747. /**
  4748. * Finds the nearest integer less than or equal to the parameter.
  4749. *
  4750. * @tsl
  4751. * @function
  4752. * @param {Node | number} x - The parameter.
  4753. * @returns {Node}
  4754. */
  4755. const floor = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.FLOOR ).setParameterLength( 1 );
  4756. /**
  4757. * Finds the nearest integer that is greater than or equal to the parameter.
  4758. *
  4759. * @tsl
  4760. * @function
  4761. * @param {Node | number} x - The parameter.
  4762. * @returns {Node}
  4763. */
  4764. const ceil = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.CEIL ).setParameterLength( 1 );
  4765. /**
  4766. * Calculates the unit vector in the same direction as the original vector.
  4767. *
  4768. * @tsl
  4769. * @function
  4770. * @param {Node} x - The input vector.
  4771. * @returns {Node}
  4772. */
  4773. const normalize = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.NORMALIZE ).setParameterLength( 1 );
  4774. /**
  4775. * Computes the fractional part of the parameter.
  4776. *
  4777. * @tsl
  4778. * @function
  4779. * @param {Node | number} x - The parameter.
  4780. * @returns {Node}
  4781. */
  4782. const fract = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.FRACT ).setParameterLength( 1 );
  4783. /**
  4784. * Returns the sine of the parameter.
  4785. *
  4786. * @tsl
  4787. * @function
  4788. * @param {Node | number} x - The parameter.
  4789. * @returns {Node}
  4790. */
  4791. const sin = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.SIN ).setParameterLength( 1 );
  4792. /**
  4793. * Returns the cosine of the parameter.
  4794. *
  4795. * @tsl
  4796. * @function
  4797. * @param {Node | number} x - The parameter.
  4798. * @returns {Node}
  4799. */
  4800. const cos = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.COS ).setParameterLength( 1 );
  4801. /**
  4802. * Returns the tangent of the parameter.
  4803. *
  4804. * @tsl
  4805. * @function
  4806. * @param {Node | number} x - The parameter.
  4807. * @returns {Node}
  4808. */
  4809. const tan = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.TAN ).setParameterLength( 1 );
  4810. /**
  4811. * Returns the arcsine of the parameter.
  4812. *
  4813. * @tsl
  4814. * @function
  4815. * @param {Node | number} x - The parameter.
  4816. * @returns {Node}
  4817. */
  4818. const asin = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.ASIN ).setParameterLength( 1 );
  4819. /**
  4820. * Returns the arccosine of the parameter.
  4821. *
  4822. * @tsl
  4823. * @function
  4824. * @param {Node | number} x - The parameter.
  4825. * @returns {Node}
  4826. */
  4827. const acos = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.ACOS ).setParameterLength( 1 );
  4828. /**
  4829. * Returns the arc-tangent of the parameter.
  4830. * If two parameters are provided, the result is `atan2(y/x)`.
  4831. *
  4832. * @tsl
  4833. * @function
  4834. * @param {Node | number} y - The y parameter.
  4835. * @param {?(Node | number)} x - The x parameter.
  4836. * @returns {Node}
  4837. */
  4838. const atan = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.ATAN ).setParameterLength( 1, 2 );
  4839. /**
  4840. * Returns the absolute value of the parameter.
  4841. *
  4842. * @tsl
  4843. * @function
  4844. * @param {Node | number} x - The parameter.
  4845. * @returns {Node}
  4846. */
  4847. const abs = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.ABS ).setParameterLength( 1 );
  4848. /**
  4849. * Extracts the sign of the parameter.
  4850. *
  4851. * @tsl
  4852. * @function
  4853. * @param {Node | number} x - The parameter.
  4854. * @returns {Node}
  4855. */
  4856. const sign = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.SIGN ).setParameterLength( 1 );
  4857. /**
  4858. * Calculates the length of a vector.
  4859. *
  4860. * @tsl
  4861. * @function
  4862. * @param {Node} x - The parameter.
  4863. * @returns {Node<float>}
  4864. */
  4865. const length = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.LENGTH ).setParameterLength( 1 );
  4866. /**
  4867. * Negates the value of the parameter (-x).
  4868. *
  4869. * @tsl
  4870. * @function
  4871. * @param {Node | number} x - The parameter.
  4872. * @returns {Node}
  4873. */
  4874. const negate = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.NEGATE ).setParameterLength( 1 );
  4875. /**
  4876. * Return `1` minus the parameter.
  4877. *
  4878. * @tsl
  4879. * @function
  4880. * @param {Node | number} x - The parameter.
  4881. * @returns {Node}
  4882. */
  4883. const oneMinus = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.ONE_MINUS ).setParameterLength( 1 );
  4884. /**
  4885. * Returns the partial derivative of the parameter with respect to x.
  4886. *
  4887. * @tsl
  4888. * @function
  4889. * @param {Node | number} x - The parameter.
  4890. * @returns {Node}
  4891. */
  4892. const dFdx = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.DFDX ).setParameterLength( 1 );
  4893. /**
  4894. * Returns the partial derivative of the parameter with respect to y.
  4895. *
  4896. * @tsl
  4897. * @function
  4898. * @param {Node | number} x - The parameter.
  4899. * @returns {Node}
  4900. */
  4901. const dFdy = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.DFDY ).setParameterLength( 1 );
  4902. /**
  4903. * Rounds the parameter to the nearest integer.
  4904. *
  4905. * @tsl
  4906. * @function
  4907. * @param {Node | number} x - The parameter.
  4908. * @returns {Node}
  4909. */
  4910. const round = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.ROUND ).setParameterLength( 1 );
  4911. /**
  4912. * Returns the reciprocal of the parameter `(1/x)`.
  4913. *
  4914. * @tsl
  4915. * @function
  4916. * @param {Node | number} x - The parameter.
  4917. * @returns {Node}
  4918. */
  4919. const reciprocal = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.RECIPROCAL ).setParameterLength( 1 );
  4920. /**
  4921. * Truncates the parameter, removing the fractional part.
  4922. *
  4923. * @tsl
  4924. * @function
  4925. * @param {Node | number} x - The parameter.
  4926. * @returns {Node}
  4927. */
  4928. const trunc = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.TRUNC ).setParameterLength( 1 );
  4929. /**
  4930. * Returns the sum of the absolute derivatives in x and y.
  4931. *
  4932. * @tsl
  4933. * @function
  4934. * @param {Node | number} x - The parameter.
  4935. * @returns {Node}
  4936. */
  4937. const fwidth = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.FWIDTH ).setParameterLength( 1 );
  4938. /**
  4939. * Returns the transpose of a matrix.
  4940. *
  4941. * @tsl
  4942. * @function
  4943. * @param {Node<mat2|mat3|mat4>} x - The parameter.
  4944. * @returns {Node}
  4945. */
  4946. const transpose = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.TRANSPOSE ).setParameterLength( 1 );
  4947. /**
  4948. * Returns the determinant of a matrix.
  4949. *
  4950. * @tsl
  4951. * @function
  4952. * @param {Node<mat2|mat3|mat4>} x - The parameter.
  4953. * @returns {Node<float>}
  4954. */
  4955. const determinant = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.DETERMINANT ).setParameterLength( 1 );
  4956. /**
  4957. * Returns the inverse of a matrix.
  4958. *
  4959. * @tsl
  4960. * @function
  4961. * @param {Node<mat2|mat3|mat4>} x - The parameter.
  4962. * @returns {Node<mat2|mat3|mat4>}
  4963. */
  4964. const inverse = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.INVERSE ).setParameterLength( 1 );
  4965. // 2 inputs
  4966. /**
  4967. * Returns `true` if `x` equals `y`.
  4968. *
  4969. * @tsl
  4970. * @function
  4971. * @param {Node | number} x - The first parameter.
  4972. * @param {Node | number} y - The second parameter.
  4973. * @deprecated since r175. Use {@link equal} instead.
  4974. * @returns {Node<bool>}
  4975. */
  4976. const equals = ( x, y ) => { // @deprecated, r172
  4977. warn( 'TSL: "equals" is deprecated. Use "equal" inside a vector instead, like: "bvec*( equal( ... ) )"' );
  4978. return equal( x, y );
  4979. };
  4980. /**
  4981. * Returns the least of the given values.
  4982. *
  4983. * @tsl
  4984. * @function
  4985. * @param {...(Node | number)} values - The values to compare.
  4986. * @returns {Node}
  4987. */
  4988. const min$1 = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.MIN ).setParameterLength( 2, Infinity );
  4989. /**
  4990. * Returns the greatest of the given values.
  4991. *
  4992. * @tsl
  4993. * @function
  4994. * @param {...(Node | number)} values - The values to compare.
  4995. * @returns {Node}
  4996. */
  4997. const max$1 = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.MAX ).setParameterLength( 2, Infinity );
  4998. /**
  4999. * Generate a step function by comparing two values.
  5000. *
  5001. * @tsl
  5002. * @function
  5003. * @param {Node | number} x - The y parameter.
  5004. * @param {Node | number} y - The x parameter.
  5005. * @returns {Node}
  5006. */
  5007. const step = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.STEP ).setParameterLength( 2 );
  5008. /**
  5009. * Calculates the reflection direction for an incident vector.
  5010. *
  5011. * @tsl
  5012. * @function
  5013. * @param {Node<vec2|vec3|vec4>} I - The incident vector.
  5014. * @param {Node<vec2|vec3|vec4>} N - The normal vector.
  5015. * @returns {Node<vec2|vec3|vec4>}
  5016. */
  5017. const reflect = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.REFLECT ).setParameterLength( 2 );
  5018. /**
  5019. * Calculates the distance between two points.
  5020. *
  5021. * @tsl
  5022. * @function
  5023. * @param {Node<vec2|vec3|vec4>} x - The first point.
  5024. * @param {Node<vec2|vec3|vec4>} y - The second point.
  5025. * @returns {Node<float>}
  5026. */
  5027. const distance = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.DISTANCE ).setParameterLength( 2 );
  5028. /**
  5029. * Calculates the absolute difference between two values.
  5030. *
  5031. * @tsl
  5032. * @function
  5033. * @param {Node | number} x - The first parameter.
  5034. * @param {Node | number} y - The second parameter.
  5035. * @returns {Node}
  5036. */
  5037. const difference = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.DIFFERENCE ).setParameterLength( 2 );
  5038. /**
  5039. * Calculates the dot product of two vectors.
  5040. *
  5041. * @tsl
  5042. * @function
  5043. * @param {Node<vec2|vec3|vec4>} x - The first vector.
  5044. * @param {Node<vec2|vec3|vec4>} y - The second vector.
  5045. * @returns {Node<float>}
  5046. */
  5047. const dot = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.DOT ).setParameterLength( 2 );
  5048. /**
  5049. * Calculates the cross product of two vectors.
  5050. *
  5051. * @tsl
  5052. * @function
  5053. * @param {Node<vec2|vec3>} x - The first vector.
  5054. * @param {Node<vec2|vec3>} y - The second vector.
  5055. * @returns {Node<float|vec3>}
  5056. */
  5057. const cross = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.CROSS ).setParameterLength( 2 );
  5058. /**
  5059. * Return the value of the first parameter raised to the power of the second one.
  5060. *
  5061. * @tsl
  5062. * @function
  5063. * @param {Node | number} x - The first parameter.
  5064. * @param {Node | number} y - The second parameter.
  5065. * @returns {Node}
  5066. */
  5067. const pow = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.POW ).setParameterLength( 2 );
  5068. /**
  5069. * Returns the square of the parameter.
  5070. *
  5071. * @tsl
  5072. * @function
  5073. * @param {Node | number} x - The first parameter.
  5074. * @returns {Node}
  5075. */
  5076. const pow2 = ( x ) => mul( x, x );
  5077. /**
  5078. * Returns the cube of the parameter.
  5079. *
  5080. * @tsl
  5081. * @function
  5082. * @param {Node | number} x - The first parameter.
  5083. * @returns {Node}
  5084. */
  5085. const pow3 = ( x ) => mul( x, x, x );
  5086. /**
  5087. * Returns the fourth power of the parameter.
  5088. *
  5089. * @tsl
  5090. * @function
  5091. * @param {Node | number} x - The first parameter.
  5092. * @returns {Node}
  5093. */
  5094. const pow4 = ( x ) => mul( x, x, x, x );
  5095. /**
  5096. * Transforms the direction of a vector by a matrix and then normalizes the result.
  5097. *
  5098. * @tsl
  5099. * @function
  5100. * @param {Node<vec2|vec3|vec4>} direction - The direction vector.
  5101. * @param {Node<mat2|mat3|mat4>} matrix - The transformation matrix.
  5102. * @returns {Node}
  5103. */
  5104. const transformDirection = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.TRANSFORM_DIRECTION ).setParameterLength( 2 );
  5105. /**
  5106. * Returns the cube root of a number.
  5107. *
  5108. * @tsl
  5109. * @function
  5110. * @param {Node | number} a - The first parameter.
  5111. * @returns {Node}
  5112. */
  5113. const cbrt = ( a ) => mul( sign( a ), pow( abs( a ), 1.0 / 3.0 ) );
  5114. /**
  5115. * Calculate the squared length of a vector.
  5116. *
  5117. * @tsl
  5118. * @function
  5119. * @param {Node<vec2|vec3|vec4>} a - The vector.
  5120. * @returns {Node<float>}
  5121. */
  5122. const lengthSq = ( a ) => dot( a, a );
  5123. /**
  5124. * Linearly interpolates between two values.
  5125. *
  5126. * @tsl
  5127. * @function
  5128. * @param {Node | number} a - The first parameter.
  5129. * @param {Node | number} b - The second parameter.
  5130. * @param {Node | number} t - The interpolation value.
  5131. * @returns {Node}
  5132. */
  5133. const mix = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.MIX ).setParameterLength( 3 );
  5134. /**
  5135. * Constrains a value to lie between two further values.
  5136. *
  5137. * @tsl
  5138. * @function
  5139. * @param {Node | number} value - The value to constrain.
  5140. * @param {Node | number} [low=0] - The lower bound.
  5141. * @param {Node | number} [high=1] - The upper bound.
  5142. * @returns {Node}
  5143. */
  5144. const clamp = ( value, low = 0, high = 1 ) => nodeObject( new MathNode( MathNode.CLAMP, nodeObject( value ), nodeObject( low ), nodeObject( high ) ) );
  5145. /**
  5146. * Constrains a value between `0` and `1`.
  5147. *
  5148. * @tsl
  5149. * @function
  5150. * @param {Node | number} value - The value to constrain.
  5151. * @returns {Node}
  5152. */
  5153. const saturate = ( value ) => clamp( value );
  5154. /**
  5155. * Calculates the refraction direction for an incident vector.
  5156. *
  5157. * @tsl
  5158. * @function
  5159. * @param {Node<vec2|vec3|vec4>} I - The incident vector.
  5160. * @param {Node<vec2|vec3|vec4>} N - The normal vector.
  5161. * @param {Node<float>} eta - The ratio of indices of refraction.
  5162. * @returns {Node<vec2|vec3|vec4>}
  5163. */
  5164. const refract = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.REFRACT ).setParameterLength( 3 );
  5165. /**
  5166. * Performs a Hermite interpolation between two values.
  5167. *
  5168. * @tsl
  5169. * @function
  5170. * @param {Node | number} low - The value of the lower edge of the Hermite function.
  5171. * @param {Node | number} high - The value of the upper edge of the Hermite function.
  5172. * @param {Node | number} x - The source value for interpolation.
  5173. * @returns {Node}
  5174. */
  5175. const smoothstep = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.SMOOTHSTEP ).setParameterLength( 3 );
  5176. /**
  5177. * Returns a vector pointing in the same direction as another.
  5178. *
  5179. * @tsl
  5180. * @function
  5181. * @param {Node<vec2|vec3|vec4>} N - The vector to orient.
  5182. * @param {Node<vec2|vec3|vec4>} I - The incident vector.
  5183. * @param {Node<vec2|vec3|vec4>} Nref - The reference vector.
  5184. * @returns {Node<vec2|vec3|vec4>}
  5185. */
  5186. const faceForward = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.FACEFORWARD ).setParameterLength( 3 );
  5187. /**
  5188. * Returns a random value for the given uv.
  5189. *
  5190. * @tsl
  5191. * @function
  5192. * @param {Node<vec2>} uv - The uv node.
  5193. * @returns {Node<float>}
  5194. */
  5195. const rand = /*@__PURE__*/ Fn( ( [ uv ] ) => {
  5196. const a = 12.9898, b = 78.233, c = 43758.5453;
  5197. const dt = dot( uv.xy, vec2( a, b ) ), sn = mod( dt, PI );
  5198. return fract( sin( sn ).mul( c ) );
  5199. } );
  5200. /**
  5201. * Alias for `mix()` with a different parameter order.
  5202. *
  5203. * @tsl
  5204. * @function
  5205. * @param {Node | number} t - The interpolation value.
  5206. * @param {Node | number} e1 - The first parameter.
  5207. * @param {Node | number} e2 - The second parameter.
  5208. * @returns {Node}
  5209. */
  5210. const mixElement = ( t, e1, e2 ) => mix( e1, e2, t );
  5211. /**
  5212. * Alias for `smoothstep()` with a different parameter order.
  5213. *
  5214. * @tsl
  5215. * @function
  5216. * @param {Node | number} x - The source value for interpolation.
  5217. * @param {Node | number} low - The value of the lower edge of the Hermite function.
  5218. * @param {Node | number} high - The value of the upper edge of the Hermite function.
  5219. * @returns {Node}
  5220. */
  5221. const smoothstepElement = ( x, low, high ) => smoothstep( low, high, x );
  5222. /**
  5223. * Alias for `step()` with a different parameter order.
  5224. *
  5225. * @tsl
  5226. * @function
  5227. * @param {Node | number} x - The source value for interpolation.
  5228. * @param {Node | number} edge - The edge value.
  5229. * @returns {Node}
  5230. */
  5231. const stepElement = ( x, edge ) => step( edge, x );
  5232. /**
  5233. * Returns the arc-tangent of the quotient of its parameters.
  5234. *
  5235. * @tsl
  5236. * @function
  5237. * @deprecated since r172. Use {@link atan} instead.
  5238. *
  5239. * @param {Node | number} y - The y parameter.
  5240. * @param {Node | number} x - The x parameter.
  5241. * @returns {Node}
  5242. */
  5243. const atan2 = ( y, x ) => { // @deprecated, r172
  5244. warn( 'TSL: "atan2" is overloaded. Use "atan" instead.' );
  5245. return atan( y, x );
  5246. };
  5247. // GLSL alias function
  5248. const faceforward = faceForward;
  5249. const inversesqrt = inverseSqrt;
  5250. // Method chaining
  5251. addMethodChaining( 'all', all );
  5252. addMethodChaining( 'any', any );
  5253. addMethodChaining( 'equals', equals );
  5254. addMethodChaining( 'radians', radians );
  5255. addMethodChaining( 'degrees', degrees );
  5256. addMethodChaining( 'exp', exp );
  5257. addMethodChaining( 'exp2', exp2 );
  5258. addMethodChaining( 'log', log );
  5259. addMethodChaining( 'log2', log2 );
  5260. addMethodChaining( 'sqrt', sqrt );
  5261. addMethodChaining( 'inverseSqrt', inverseSqrt );
  5262. addMethodChaining( 'floor', floor );
  5263. addMethodChaining( 'ceil', ceil );
  5264. addMethodChaining( 'normalize', normalize );
  5265. addMethodChaining( 'fract', fract );
  5266. addMethodChaining( 'sin', sin );
  5267. addMethodChaining( 'cos', cos );
  5268. addMethodChaining( 'tan', tan );
  5269. addMethodChaining( 'asin', asin );
  5270. addMethodChaining( 'acos', acos );
  5271. addMethodChaining( 'atan', atan );
  5272. addMethodChaining( 'abs', abs );
  5273. addMethodChaining( 'sign', sign );
  5274. addMethodChaining( 'length', length );
  5275. addMethodChaining( 'lengthSq', lengthSq );
  5276. addMethodChaining( 'negate', negate );
  5277. addMethodChaining( 'oneMinus', oneMinus );
  5278. addMethodChaining( 'dFdx', dFdx );
  5279. addMethodChaining( 'dFdy', dFdy );
  5280. addMethodChaining( 'round', round );
  5281. addMethodChaining( 'reciprocal', reciprocal );
  5282. addMethodChaining( 'trunc', trunc );
  5283. addMethodChaining( 'fwidth', fwidth );
  5284. addMethodChaining( 'atan2', atan2 );
  5285. addMethodChaining( 'min', min$1 );
  5286. addMethodChaining( 'max', max$1 );
  5287. addMethodChaining( 'step', stepElement );
  5288. addMethodChaining( 'reflect', reflect );
  5289. addMethodChaining( 'distance', distance );
  5290. addMethodChaining( 'dot', dot );
  5291. addMethodChaining( 'cross', cross );
  5292. addMethodChaining( 'pow', pow );
  5293. addMethodChaining( 'pow2', pow2 );
  5294. addMethodChaining( 'pow3', pow3 );
  5295. addMethodChaining( 'pow4', pow4 );
  5296. addMethodChaining( 'transformDirection', transformDirection );
  5297. addMethodChaining( 'mix', mixElement );
  5298. addMethodChaining( 'clamp', clamp );
  5299. addMethodChaining( 'refract', refract );
  5300. addMethodChaining( 'smoothstep', smoothstepElement );
  5301. addMethodChaining( 'faceForward', faceForward );
  5302. addMethodChaining( 'difference', difference );
  5303. addMethodChaining( 'saturate', saturate );
  5304. addMethodChaining( 'cbrt', cbrt );
  5305. addMethodChaining( 'transpose', transpose );
  5306. addMethodChaining( 'determinant', determinant );
  5307. addMethodChaining( 'inverse', inverse );
  5308. addMethodChaining( 'rand', rand );
  5309. /**
  5310. * Represents a logical `if/else` statement. Can be used as an alternative
  5311. * to the `If()`/`Else()` syntax.
  5312. *
  5313. * The corresponding TSL `select()` looks like so:
  5314. * ```js
  5315. * velocity = position.greaterThanEqual( limit ).select( velocity.negate(), velocity );
  5316. * ```
  5317. * The `select()` method is called in a chaining fashion on a condition. The parameter nodes of `select()`
  5318. * determine the outcome of the entire statement.
  5319. *
  5320. * @augments Node
  5321. */
  5322. class ConditionalNode extends Node {
  5323. static get type() {
  5324. return 'ConditionalNode';
  5325. }
  5326. /**
  5327. * Constructs a new conditional node.
  5328. *
  5329. * @param {Node} condNode - The node that defines the condition.
  5330. * @param {Node} ifNode - The node that is evaluate when the condition ends up `true`.
  5331. * @param {?Node} [elseNode=null] - The node that is evaluate when the condition ends up `false`.
  5332. */
  5333. constructor( condNode, ifNode, elseNode = null ) {
  5334. super();
  5335. /**
  5336. * The node that defines the condition.
  5337. *
  5338. * @type {Node}
  5339. */
  5340. this.condNode = condNode;
  5341. /**
  5342. * The node that is evaluate when the condition ends up `true`.
  5343. *
  5344. * @type {Node}
  5345. */
  5346. this.ifNode = ifNode;
  5347. /**
  5348. * The node that is evaluate when the condition ends up `false`.
  5349. *
  5350. * @type {?Node}
  5351. * @default null
  5352. */
  5353. this.elseNode = elseNode;
  5354. }
  5355. /**
  5356. * This method is overwritten since the node type is inferred from the if/else
  5357. * nodes.
  5358. *
  5359. * @param {NodeBuilder} builder - The current node builder.
  5360. * @return {string} The node type.
  5361. */
  5362. getNodeType( builder ) {
  5363. const { ifNode, elseNode } = builder.getNodeProperties( this );
  5364. if ( ifNode === undefined ) {
  5365. // fallback setup
  5366. builder.flowBuildStage( this, 'setup' );
  5367. return this.getNodeType( builder );
  5368. }
  5369. const ifType = ifNode.getNodeType( builder );
  5370. if ( elseNode !== null ) {
  5371. const elseType = elseNode.getNodeType( builder );
  5372. if ( builder.getTypeLength( elseType ) > builder.getTypeLength( ifType ) ) {
  5373. return elseType;
  5374. }
  5375. }
  5376. return ifType;
  5377. }
  5378. setup( builder ) {
  5379. const condNode = this.condNode;
  5380. const ifNode = this.ifNode.isolate();
  5381. const elseNode = this.elseNode ? this.elseNode.isolate() : null;
  5382. //
  5383. const currentNodeBlock = builder.context.nodeBlock;
  5384. builder.getDataFromNode( ifNode ).parentNodeBlock = currentNodeBlock;
  5385. if ( elseNode !== null ) builder.getDataFromNode( elseNode ).parentNodeBlock = currentNodeBlock;
  5386. //
  5387. const isUniformFlow = builder.context.uniformFlow;
  5388. const properties = builder.getNodeProperties( this );
  5389. properties.condNode = condNode;
  5390. properties.ifNode = isUniformFlow ? ifNode : ifNode.context( { nodeBlock: ifNode } );
  5391. properties.elseNode = elseNode ? ( isUniformFlow ? elseNode : elseNode.context( { nodeBlock: elseNode } ) ) : null;
  5392. }
  5393. generate( builder, output ) {
  5394. const type = this.getNodeType( builder );
  5395. const nodeData = builder.getDataFromNode( this );
  5396. if ( nodeData.nodeProperty !== undefined ) {
  5397. return nodeData.nodeProperty;
  5398. }
  5399. const { condNode, ifNode, elseNode } = builder.getNodeProperties( this );
  5400. const functionNode = builder.currentFunctionNode;
  5401. const needsOutput = output !== 'void';
  5402. const nodeProperty = needsOutput ? property( type ).build( builder ) : '';
  5403. nodeData.nodeProperty = nodeProperty;
  5404. const nodeSnippet = condNode.build( builder, 'bool' );
  5405. const isUniformFlow = builder.context.uniformFlow;
  5406. if ( isUniformFlow && elseNode !== null ) {
  5407. const ifSnippet = ifNode.build( builder, type );
  5408. const elseSnippet = elseNode.build( builder, type );
  5409. const mathSnippet = builder.getTernary( nodeSnippet, ifSnippet, elseSnippet );
  5410. // TODO: If node property already exists return something else
  5411. return builder.format( mathSnippet, type, output );
  5412. }
  5413. builder.addFlowCode( `\n${ builder.tab }if ( ${ nodeSnippet } ) {\n\n` ).addFlowTab();
  5414. let ifSnippet = ifNode.build( builder, type );
  5415. if ( ifSnippet ) {
  5416. if ( needsOutput ) {
  5417. ifSnippet = nodeProperty + ' = ' + ifSnippet + ';';
  5418. } else {
  5419. ifSnippet = 'return ' + ifSnippet + ';';
  5420. if ( functionNode === null ) {
  5421. warn( 'TSL: Return statement used in an inline \'Fn()\'. Define a layout struct to allow return values.' );
  5422. ifSnippet = '// ' + ifSnippet;
  5423. }
  5424. }
  5425. }
  5426. builder.removeFlowTab().addFlowCode( builder.tab + '\t' + ifSnippet + '\n\n' + builder.tab + '}' );
  5427. if ( elseNode !== null ) {
  5428. builder.addFlowCode( ' else {\n\n' ).addFlowTab();
  5429. let elseSnippet = elseNode.build( builder, type );
  5430. if ( elseSnippet ) {
  5431. if ( needsOutput ) {
  5432. elseSnippet = nodeProperty + ' = ' + elseSnippet + ';';
  5433. } else {
  5434. elseSnippet = 'return ' + elseSnippet + ';';
  5435. if ( functionNode === null ) {
  5436. warn( 'TSL: Return statement used in an inline \'Fn()\'. Define a layout struct to allow return values.' );
  5437. elseSnippet = '// ' + elseSnippet;
  5438. }
  5439. }
  5440. }
  5441. builder.removeFlowTab().addFlowCode( builder.tab + '\t' + elseSnippet + '\n\n' + builder.tab + '}\n\n' );
  5442. } else {
  5443. builder.addFlowCode( '\n\n' );
  5444. }
  5445. return builder.format( nodeProperty, type, output );
  5446. }
  5447. }
  5448. /**
  5449. * TSL function for creating a conditional node.
  5450. *
  5451. * @tsl
  5452. * @function
  5453. * @param {Node} condNode - The node that defines the condition.
  5454. * @param {Node} ifNode - The node that is evaluate when the condition ends up `true`.
  5455. * @param {?Node} [elseNode=null] - The node that is evaluate when the condition ends up `false`.
  5456. * @returns {ConditionalNode}
  5457. */
  5458. const select = /*@__PURE__*/ nodeProxy( ConditionalNode ).setParameterLength( 2, 3 );
  5459. addMethodChaining( 'select', select );
  5460. /**
  5461. * This node can be used as a context management component for another node.
  5462. * {@link NodeBuilder} performs its node building process in a specific context and
  5463. * this node allows the modify the context. A typical use case is to overwrite `getUV()` e.g.:
  5464. *
  5465. * ```js
  5466. *node.context( { getUV: () => customCoord } );
  5467. *```
  5468. * @augments Node
  5469. */
  5470. class ContextNode extends Node {
  5471. static get type() {
  5472. return 'ContextNode';
  5473. }
  5474. /**
  5475. * Constructs a new context node.
  5476. *
  5477. * @param {Node} node - The node whose context should be modified.
  5478. * @param {Object} [value={}] - The modified context data.
  5479. */
  5480. constructor( node, value = {} ) {
  5481. super();
  5482. /**
  5483. * This flag can be used for type testing.
  5484. *
  5485. * @type {boolean}
  5486. * @readonly
  5487. * @default true
  5488. */
  5489. this.isContextNode = true;
  5490. /**
  5491. * The node whose context should be modified.
  5492. *
  5493. * @type {Node}
  5494. */
  5495. this.node = node;
  5496. /**
  5497. * The modified context data.
  5498. *
  5499. * @type {Object}
  5500. * @default {}
  5501. */
  5502. this.value = value;
  5503. }
  5504. /**
  5505. * This method is overwritten to ensure it returns the reference to {@link ContextNode#node}.
  5506. *
  5507. * @return {Node} A reference to {@link ContextNode#node}.
  5508. */
  5509. getScope() {
  5510. return this.node.getScope();
  5511. }
  5512. /**
  5513. * This method is overwritten to ensure it returns the type of {@link ContextNode#node}.
  5514. *
  5515. * @param {NodeBuilder} builder - The current node builder.
  5516. * @return {string} The node type.
  5517. */
  5518. getNodeType( builder ) {
  5519. return this.node.getNodeType( builder );
  5520. }
  5521. /**
  5522. * This method is overwritten to ensure it returns the member type of {@link ContextNode#node}.
  5523. *
  5524. * @param {NodeBuilder} builder - The current node builder.
  5525. * @param {string} name - The member name.
  5526. * @returns {string} The member type.
  5527. */
  5528. getMemberType( builder, name ) {
  5529. return this.node.getMemberType( builder, name );
  5530. }
  5531. analyze( builder ) {
  5532. const previousContext = builder.addContext( this.value );
  5533. this.node.build( builder );
  5534. builder.setContext( previousContext );
  5535. }
  5536. setup( builder ) {
  5537. const previousContext = builder.addContext( this.value );
  5538. this.node.build( builder );
  5539. builder.setContext( previousContext );
  5540. }
  5541. generate( builder, output ) {
  5542. const previousContext = builder.addContext( this.value );
  5543. const snippet = this.node.build( builder, output );
  5544. builder.setContext( previousContext );
  5545. return snippet;
  5546. }
  5547. }
  5548. /**
  5549. * TSL function for creating a context node.
  5550. *
  5551. * @tsl
  5552. * @function
  5553. * @param {Node} node - The node whose context should be modified.
  5554. * @param {Object} [value={}] - The modified context data.
  5555. * @returns {ContextNode}
  5556. */
  5557. const context = /*@__PURE__*/ nodeProxy( ContextNode ).setParameterLength( 1, 2 );
  5558. /**
  5559. * TSL function for defining a uniformFlow context value for a given node.
  5560. *
  5561. * @tsl
  5562. * @function
  5563. * @param {Node} node - The node whose dependencies should all execute within a uniform control-flow path.
  5564. * @returns {ContextNode}
  5565. */
  5566. const uniformFlow = ( node ) => context( node, { uniformFlow: true } );
  5567. /**
  5568. * TSL function for defining a name for the context value for a given node.
  5569. *
  5570. * @tsl
  5571. * @function
  5572. * @param {Node} node - The node whose context should be modified.
  5573. * @param {string} name - The name to set.
  5574. * @returns {ContextNode}
  5575. */
  5576. const setName = ( node, name ) => context( node, { nodeName: name } );
  5577. /**
  5578. * TSL function for defining a label context value for a given node.
  5579. *
  5580. * @tsl
  5581. * @function
  5582. * @deprecated
  5583. * @param {Node} node - The node whose context should be modified.
  5584. * @param {string} name - The name/label to set.
  5585. * @returns {ContextNode}
  5586. */
  5587. function label( node, name ) {
  5588. warn( 'TSL: "label()" has been deprecated. Use "setName()" instead.' ); // @deprecated r179
  5589. return setName( node, name );
  5590. }
  5591. addMethodChaining( 'context', context );
  5592. addMethodChaining( 'label', label );
  5593. addMethodChaining( 'uniformFlow', uniformFlow );
  5594. addMethodChaining( 'setName', setName );
  5595. /**
  5596. * Class for representing shader variables as nodes. Variables are created from
  5597. * existing nodes like the following:
  5598. *
  5599. * ```js
  5600. * const depth = sampleDepth( uvNode ).toVar( 'depth' );
  5601. * ```
  5602. *
  5603. * @augments Node
  5604. */
  5605. class VarNode extends Node {
  5606. static get type() {
  5607. return 'VarNode';
  5608. }
  5609. /**
  5610. * Constructs a new variable node.
  5611. *
  5612. * @param {Node} node - The node for which a variable should be created.
  5613. * @param {?string} [name=null] - The name of the variable in the shader.
  5614. * @param {boolean} [readOnly=false] - The read-only flag.
  5615. */
  5616. constructor( node, name = null, readOnly = false ) {
  5617. super();
  5618. /**
  5619. * The node for which a variable should be created.
  5620. *
  5621. * @type {Node}
  5622. */
  5623. this.node = node;
  5624. /**
  5625. * The name of the variable in the shader. If no name is defined,
  5626. * the node system auto-generates one.
  5627. *
  5628. * @type {?string}
  5629. * @default null
  5630. */
  5631. this.name = name;
  5632. /**
  5633. * `VarNode` sets this property to `true` by default.
  5634. *
  5635. * @type {boolean}
  5636. * @default true
  5637. */
  5638. this.global = true;
  5639. /**
  5640. * This flag can be used for type testing.
  5641. *
  5642. * @type {boolean}
  5643. * @readonly
  5644. * @default true
  5645. */
  5646. this.isVarNode = true;
  5647. /**
  5648. *
  5649. * The read-only flag.
  5650. *
  5651. * @type {boolean}
  5652. * @default false
  5653. */
  5654. this.readOnly = readOnly;
  5655. /**
  5656. *
  5657. * Add this flag to the node system to indicate that this node require parents.
  5658. *
  5659. * @type {boolean}
  5660. * @default true
  5661. */
  5662. this.parents = true;
  5663. /**
  5664. * This flag is used to indicate that this node is used for intent.
  5665. *
  5666. * @type {boolean}
  5667. * @default false
  5668. */
  5669. this.intent = false;
  5670. }
  5671. /**
  5672. * Sets the intent flag for this node.
  5673. *
  5674. * This flag is used to indicate that this node is used for intent
  5675. * and should not be built directly. Instead, it is used to indicate that
  5676. * the node should be treated as a variable intent.
  5677. *
  5678. * It's useful for assigning variables without needing creating a new variable node.
  5679. *
  5680. * @param {boolean} value - The value to set for the intent flag.
  5681. * @returns {VarNode} This node.
  5682. */
  5683. setIntent( value ) {
  5684. this.intent = value;
  5685. return this;
  5686. }
  5687. /**
  5688. * Returns the intent flag of this node.
  5689. *
  5690. * @return {boolean} The intent flag.
  5691. */
  5692. getIntent() {
  5693. return this.intent;
  5694. }
  5695. getMemberType( builder, name ) {
  5696. return this.node.getMemberType( builder, name );
  5697. }
  5698. getElementType( builder ) {
  5699. return this.node.getElementType( builder );
  5700. }
  5701. getNodeType( builder ) {
  5702. return this.node.getNodeType( builder );
  5703. }
  5704. getArrayCount( builder ) {
  5705. return this.node.getArrayCount( builder );
  5706. }
  5707. isAssign( builder ) {
  5708. const properties = builder.getNodeProperties( this );
  5709. let assign = properties.assign;
  5710. if ( assign !== true ) {
  5711. if ( this.node.isShaderCallNodeInternal && this.node.shaderNode.getLayout() === null ) {
  5712. if ( builder.fnCall && builder.fnCall.shaderNode ) {
  5713. const shaderNodeData = builder.getDataFromNode( this.node.shaderNode );
  5714. if ( shaderNodeData.hasLoop ) {
  5715. assign = true;
  5716. }
  5717. }
  5718. }
  5719. }
  5720. return assign;
  5721. }
  5722. build( ...params ) {
  5723. const builder = params[ 0 ];
  5724. if ( this._hasStack( builder ) === false && builder.buildStage === 'setup' ) {
  5725. if ( builder.context.nodeLoop || builder.context.nodeBlock ) {
  5726. builder.getBaseStack().addToStack( this );
  5727. }
  5728. }
  5729. if ( this.intent === true ) {
  5730. if ( this.isAssign( builder ) !== true ) {
  5731. return this.node.build( ...params );
  5732. }
  5733. }
  5734. return super.build( ...params );
  5735. }
  5736. generate( builder ) {
  5737. const { node, name, readOnly } = this;
  5738. const { renderer } = builder;
  5739. const isWebGPUBackend = renderer.backend.isWebGPUBackend === true;
  5740. let isDeterministic = false;
  5741. let shouldTreatAsReadOnly = false;
  5742. if ( readOnly ) {
  5743. isDeterministic = builder.isDeterministic( node );
  5744. shouldTreatAsReadOnly = isWebGPUBackend ? readOnly : isDeterministic;
  5745. }
  5746. const nodeType = this.getNodeType( builder );
  5747. if ( nodeType == 'void' ) {
  5748. if ( this.intent !== true ) {
  5749. error( 'TSL: ".toVar()" can not be used with void type.' );
  5750. }
  5751. const snippet = node.build( builder );
  5752. return snippet;
  5753. }
  5754. const vectorType = builder.getVectorType( nodeType );
  5755. const snippet = node.build( builder, vectorType );
  5756. const nodeVar = builder.getVarFromNode( this, name, vectorType, undefined, shouldTreatAsReadOnly );
  5757. const propertyName = builder.getPropertyName( nodeVar );
  5758. let declarationPrefix = propertyName;
  5759. if ( shouldTreatAsReadOnly ) {
  5760. if ( isWebGPUBackend ) {
  5761. declarationPrefix = isDeterministic
  5762. ? `const ${ propertyName }`
  5763. : `let ${ propertyName }`;
  5764. } else {
  5765. const count = node.getArrayCount( builder );
  5766. declarationPrefix = `const ${ builder.getVar( nodeVar.type, propertyName, count ) }`;
  5767. }
  5768. }
  5769. builder.addLineFlowCode( `${ declarationPrefix } = ${ snippet }`, this );
  5770. return propertyName;
  5771. }
  5772. _hasStack( builder ) {
  5773. const nodeData = builder.getDataFromNode( this );
  5774. return nodeData.stack !== undefined;
  5775. }
  5776. }
  5777. /**
  5778. * TSL function for creating a var node.
  5779. *
  5780. * @tsl
  5781. * @function
  5782. * @param {Node} node - The node for which a variable should be created.
  5783. * @param {?string} name - The name of the variable in the shader.
  5784. * @returns {VarNode}
  5785. */
  5786. const createVar = /*@__PURE__*/ nodeProxy( VarNode );
  5787. /**
  5788. * TSL function for creating a var node.
  5789. *
  5790. * @tsl
  5791. * @function
  5792. * @param {Node} node - The node for which a variable should be created.
  5793. * @param {?string} name - The name of the variable in the shader.
  5794. * @returns {VarNode}
  5795. */
  5796. const Var = ( node, name = null ) => createVar( node, name ).toStack();
  5797. /**
  5798. * TSL function for creating a const node.
  5799. *
  5800. * @tsl
  5801. * @function
  5802. * @param {Node} node - The node for which a constant should be created.
  5803. * @param {?string} name - The name of the constant in the shader.
  5804. * @returns {VarNode}
  5805. */
  5806. const Const = ( node, name = null ) => createVar( node, name, true ).toStack();
  5807. //
  5808. //
  5809. /**
  5810. * TSL function for creating a var intent node.
  5811. *
  5812. * @tsl
  5813. * @function
  5814. * @param {Node} node - The node for which a variable should be created.
  5815. * @param {?string} name - The name of the variable in the shader.
  5816. * @returns {VarNode}
  5817. */
  5818. const VarIntent = ( node ) => {
  5819. return createVar( node ).setIntent( true ).toStack();
  5820. };
  5821. // Method chaining
  5822. addMethodChaining( 'toVar', Var );
  5823. addMethodChaining( 'toConst', Const );
  5824. addMethodChaining( 'toVarIntent', VarIntent );
  5825. /**
  5826. * This node is used to build a sub-build in the node system.
  5827. *
  5828. * @augments Node
  5829. * @param {Node} node - The node to be built in the sub-build.
  5830. * @param {string} name - The name of the sub-build.
  5831. * @param {?string} [nodeType=null] - The type of the node, if known.
  5832. */
  5833. class SubBuildNode extends Node {
  5834. static get type() {
  5835. return 'SubBuild';
  5836. }
  5837. constructor( node, name, nodeType = null ) {
  5838. super( nodeType );
  5839. /**
  5840. * The node to be built in the sub-build.
  5841. *
  5842. * @type {Node}
  5843. */
  5844. this.node = node;
  5845. /**
  5846. * The name of the sub-build.
  5847. *
  5848. * @type {string}
  5849. */
  5850. this.name = name;
  5851. /**
  5852. * This flag can be used for type testing.
  5853. *
  5854. * @type {boolean}
  5855. * @readonly
  5856. * @default true
  5857. */
  5858. this.isSubBuildNode = true;
  5859. }
  5860. getNodeType( builder ) {
  5861. if ( this.nodeType !== null ) return this.nodeType;
  5862. builder.addSubBuild( this.name );
  5863. const nodeType = this.node.getNodeType( builder );
  5864. builder.removeSubBuild();
  5865. return nodeType;
  5866. }
  5867. build( builder, ...params ) {
  5868. builder.addSubBuild( this.name );
  5869. const data = this.node.build( builder, ...params );
  5870. builder.removeSubBuild();
  5871. return data;
  5872. }
  5873. }
  5874. /**
  5875. * Creates a new sub-build node.
  5876. *
  5877. * @tsl
  5878. * @function
  5879. * @param {Node} node - The node to be built in the sub-build.
  5880. * @param {string} name - The name of the sub-build.
  5881. * @param {?string} [type=null] - The type of the node, if known.
  5882. * @returns {Node} A node object wrapping the SubBuildNode instance.
  5883. */
  5884. const subBuild = ( node, name, type = null ) => nodeObject( new SubBuildNode( nodeObject( node ), name, type ) );
  5885. /**
  5886. * Class for representing shader varyings as nodes. Varyings are create from
  5887. * existing nodes like the following:
  5888. *
  5889. * ```js
  5890. * const positionLocal = positionGeometry.toVarying( 'vPositionLocal' );
  5891. * ```
  5892. *
  5893. * @augments Node
  5894. */
  5895. class VaryingNode extends Node {
  5896. static get type() {
  5897. return 'VaryingNode';
  5898. }
  5899. /**
  5900. * Constructs a new varying node.
  5901. *
  5902. * @param {Node} node - The node for which a varying should be created.
  5903. * @param {?string} name - The name of the varying in the shader.
  5904. */
  5905. constructor( node, name = null ) {
  5906. super();
  5907. /**
  5908. * The node for which a varying should be created.
  5909. *
  5910. * @type {Node}
  5911. */
  5912. this.node = node;
  5913. /**
  5914. * The name of the varying in the shader. If no name is defined,
  5915. * the node system auto-generates one.
  5916. *
  5917. * @type {?string}
  5918. * @default null
  5919. */
  5920. this.name = name;
  5921. /**
  5922. * This flag can be used for type testing.
  5923. *
  5924. * @type {boolean}
  5925. * @readonly
  5926. * @default true
  5927. */
  5928. this.isVaryingNode = true;
  5929. /**
  5930. * The interpolation type of the varying data.
  5931. *
  5932. * @type {?string}
  5933. * @default null
  5934. */
  5935. this.interpolationType = null;
  5936. /**
  5937. * The interpolation sampling type of varying data.
  5938. *
  5939. * @type {?string}
  5940. * @default null
  5941. */
  5942. this.interpolationSampling = null;
  5943. /**
  5944. * This flag is used for global cache.
  5945. *
  5946. * @type {boolean}
  5947. * @default true
  5948. */
  5949. this.global = true;
  5950. }
  5951. /**
  5952. * Defines the interpolation type of the varying.
  5953. *
  5954. * @param {string} type - The interpolation type.
  5955. * @param {?string} sampling - The interpolation sampling type
  5956. * @return {VaryingNode} A reference to this node.
  5957. */
  5958. setInterpolation( type, sampling = null ) {
  5959. this.interpolationType = type;
  5960. this.interpolationSampling = sampling;
  5961. return this;
  5962. }
  5963. getHash( builder ) {
  5964. return this.name || super.getHash( builder );
  5965. }
  5966. getNodeType( builder ) {
  5967. // VaryingNode is auto type
  5968. return this.node.getNodeType( builder );
  5969. }
  5970. /**
  5971. * This method performs the setup of a varying node with the current node builder.
  5972. *
  5973. * @param {NodeBuilder} builder - The current node builder.
  5974. * @return {NodeVarying} The node varying from the node builder.
  5975. */
  5976. setupVarying( builder ) {
  5977. const properties = builder.getNodeProperties( this );
  5978. let varying = properties.varying;
  5979. if ( varying === undefined ) {
  5980. const name = this.name;
  5981. const type = this.getNodeType( builder );
  5982. const interpolationType = this.interpolationType;
  5983. const interpolationSampling = this.interpolationSampling;
  5984. properties.varying = varying = builder.getVaryingFromNode( this, name, type, interpolationType, interpolationSampling );
  5985. properties.node = subBuild( this.node, 'VERTEX' );
  5986. }
  5987. // this property can be used to check if the varying can be optimized for a variable
  5988. varying.needsInterpolation || ( varying.needsInterpolation = ( builder.shaderStage === 'fragment' ) );
  5989. return varying;
  5990. }
  5991. setup( builder ) {
  5992. this.setupVarying( builder );
  5993. builder.flowNodeFromShaderStage( NodeShaderStage.VERTEX, this.node );
  5994. }
  5995. analyze( builder ) {
  5996. this.setupVarying( builder );
  5997. builder.flowNodeFromShaderStage( NodeShaderStage.VERTEX, this.node );
  5998. }
  5999. generate( builder ) {
  6000. const propertyKey = builder.getSubBuildProperty( 'property', builder.currentStack );
  6001. const properties = builder.getNodeProperties( this );
  6002. const varying = this.setupVarying( builder );
  6003. if ( properties[ propertyKey ] === undefined ) {
  6004. const type = this.getNodeType( builder );
  6005. const propertyName = builder.getPropertyName( varying, NodeShaderStage.VERTEX );
  6006. // force node run in vertex stage
  6007. builder.flowNodeFromShaderStage( NodeShaderStage.VERTEX, properties.node, type, propertyName );
  6008. properties[ propertyKey ] = propertyName;
  6009. }
  6010. return builder.getPropertyName( varying );
  6011. }
  6012. }
  6013. /**
  6014. * TSL function for creating a varying node.
  6015. *
  6016. * @tsl
  6017. * @function
  6018. * @param {Node} node - The node for which a varying should be created.
  6019. * @param {?string} name - The name of the varying in the shader.
  6020. * @returns {VaryingNode}
  6021. */
  6022. const varying = /*@__PURE__*/ nodeProxy( VaryingNode ).setParameterLength( 1, 2 );
  6023. /**
  6024. * Computes a node in the vertex stage.
  6025. *
  6026. * @tsl
  6027. * @function
  6028. * @param {Node} node - The node which should be executed in the vertex stage.
  6029. * @returns {VaryingNode}
  6030. */
  6031. const vertexStage = ( node ) => varying( node );
  6032. addMethodChaining( 'toVarying', varying );
  6033. addMethodChaining( 'toVertexStage', vertexStage );
  6034. // Deprecated
  6035. addMethodChaining( 'varying', ( ...params ) => { // @deprecated, r173
  6036. warn( 'TSL: .varying() has been renamed to .toVarying().' );
  6037. return varying( ...params );
  6038. } );
  6039. addMethodChaining( 'vertexStage', ( ...params ) => { // @deprecated, r173
  6040. warn( 'TSL: .vertexStage() has been renamed to .toVertexStage().' );
  6041. return varying( ...params );
  6042. } );
  6043. /**
  6044. * Converts the given color value from sRGB to linear-sRGB color space.
  6045. *
  6046. * @tsl
  6047. * @function
  6048. * @param {Node<vec3>} color - The sRGB color.
  6049. * @return {Node<vec3>} The linear-sRGB color.
  6050. */
  6051. const sRGBTransferEOTF = /*@__PURE__*/ Fn( ( [ color ] ) => {
  6052. const a = color.mul( 0.9478672986 ).add( 0.0521327014 ).pow( 2.4 );
  6053. const b = color.mul( 0.0773993808 );
  6054. const factor = color.lessThanEqual( 0.04045 );
  6055. const rgbResult = mix( a, b, factor );
  6056. return rgbResult;
  6057. } ).setLayout( {
  6058. name: 'sRGBTransferEOTF',
  6059. type: 'vec3',
  6060. inputs: [
  6061. { name: 'color', type: 'vec3' }
  6062. ]
  6063. } );
  6064. /**
  6065. * Converts the given color value from linear-sRGB to sRGB color space.
  6066. *
  6067. * @tsl
  6068. * @function
  6069. * @param {Node<vec3>} color - The linear-sRGB color.
  6070. * @return {Node<vec3>} The sRGB color.
  6071. */
  6072. const sRGBTransferOETF = /*@__PURE__*/ Fn( ( [ color ] ) => {
  6073. const a = color.pow( 0.41666 ).mul( 1.055 ).sub( 0.055 );
  6074. const b = color.mul( 12.92 );
  6075. const factor = color.lessThanEqual( 0.0031308 );
  6076. const rgbResult = mix( a, b, factor );
  6077. return rgbResult;
  6078. } ).setLayout( {
  6079. name: 'sRGBTransferOETF',
  6080. type: 'vec3',
  6081. inputs: [
  6082. { name: 'color', type: 'vec3' }
  6083. ]
  6084. } );
  6085. const WORKING_COLOR_SPACE = 'WorkingColorSpace';
  6086. const OUTPUT_COLOR_SPACE = 'OutputColorSpace';
  6087. /**
  6088. * This node represents a color space conversion. Meaning it converts
  6089. * a color value from a source to a target color space.
  6090. *
  6091. * @augments TempNode
  6092. */
  6093. class ColorSpaceNode extends TempNode {
  6094. static get type() {
  6095. return 'ColorSpaceNode';
  6096. }
  6097. /**
  6098. * Constructs a new color space node.
  6099. *
  6100. * @param {Node} colorNode - Represents the color to convert.
  6101. * @param {string} source - The source color space.
  6102. * @param {string} target - The target color space.
  6103. */
  6104. constructor( colorNode, source, target ) {
  6105. super( 'vec4' );
  6106. /**
  6107. * Represents the color to convert.
  6108. *
  6109. * @type {Node}
  6110. */
  6111. this.colorNode = colorNode;
  6112. /**
  6113. * The source color space.
  6114. *
  6115. * @type {string}
  6116. */
  6117. this.source = source;
  6118. /**
  6119. * The target color space.
  6120. *
  6121. * @type {string}
  6122. */
  6123. this.target = target;
  6124. }
  6125. /**
  6126. * This method resolves the constants `WORKING_COLOR_SPACE` and
  6127. * `OUTPUT_COLOR_SPACE` based on the current configuration of the
  6128. * color management and renderer.
  6129. *
  6130. * @param {NodeBuilder} builder - The current node builder.
  6131. * @param {string} colorSpace - The color space to resolve.
  6132. * @return {string} The resolved color space.
  6133. */
  6134. resolveColorSpace( builder, colorSpace ) {
  6135. if ( colorSpace === WORKING_COLOR_SPACE ) {
  6136. return ColorManagement.workingColorSpace;
  6137. } else if ( colorSpace === OUTPUT_COLOR_SPACE ) {
  6138. return builder.context.outputColorSpace || builder.renderer.outputColorSpace;
  6139. }
  6140. return colorSpace;
  6141. }
  6142. setup( builder ) {
  6143. const { colorNode } = this;
  6144. const source = this.resolveColorSpace( builder, this.source );
  6145. const target = this.resolveColorSpace( builder, this.target );
  6146. let outputNode = colorNode;
  6147. if ( ColorManagement.enabled === false || source === target || ! source || ! target ) {
  6148. return outputNode;
  6149. }
  6150. if ( ColorManagement.getTransfer( source ) === SRGBTransfer ) {
  6151. outputNode = vec4( sRGBTransferEOTF( outputNode.rgb ), outputNode.a );
  6152. }
  6153. if ( ColorManagement.getPrimaries( source ) !== ColorManagement.getPrimaries( target ) ) {
  6154. outputNode = vec4(
  6155. mat3( ColorManagement._getMatrix( new Matrix3(), source, target ) ).mul( outputNode.rgb ),
  6156. outputNode.a
  6157. );
  6158. }
  6159. if ( ColorManagement.getTransfer( target ) === SRGBTransfer ) {
  6160. outputNode = vec4( sRGBTransferOETF( outputNode.rgb ), outputNode.a );
  6161. }
  6162. return outputNode;
  6163. }
  6164. }
  6165. /**
  6166. * TSL function for converting a given color node from the current working color space to the given color space.
  6167. *
  6168. * @tsl
  6169. * @function
  6170. * @param {Node} node - Represents the node to convert.
  6171. * @param {string} targetColorSpace - The target color space.
  6172. * @returns {ColorSpaceNode}
  6173. */
  6174. const workingToColorSpace = ( node, targetColorSpace ) => nodeObject( new ColorSpaceNode( nodeObject( node ), WORKING_COLOR_SPACE, targetColorSpace ) );
  6175. /**
  6176. * TSL function for converting a given color node from the given color space to the current working color space.
  6177. *
  6178. * @tsl
  6179. * @function
  6180. * @param {Node} node - Represents the node to convert.
  6181. * @param {string} sourceColorSpace - The source color space.
  6182. * @returns {ColorSpaceNode}
  6183. */
  6184. const colorSpaceToWorking = ( node, sourceColorSpace ) => nodeObject( new ColorSpaceNode( nodeObject( node ), sourceColorSpace, WORKING_COLOR_SPACE ) );
  6185. /**
  6186. * TSL function for converting a given color node from one color space to another one.
  6187. *
  6188. * @tsl
  6189. * @function
  6190. * @param {Node} node - Represents the node to convert.
  6191. * @param {string} sourceColorSpace - The source color space.
  6192. * @param {string} targetColorSpace - The target color space.
  6193. * @returns {ColorSpaceNode}
  6194. */
  6195. const convertColorSpace = ( node, sourceColorSpace, targetColorSpace ) => nodeObject( new ColorSpaceNode( nodeObject( node ), sourceColorSpace, targetColorSpace ) );
  6196. addMethodChaining( 'workingToColorSpace', workingToColorSpace );
  6197. addMethodChaining( 'colorSpaceToWorking', colorSpaceToWorking );
  6198. // TODO: Avoid duplicated code and ues only ReferenceBaseNode or ReferenceNode
  6199. /**
  6200. * This class is only relevant if the referenced property is array-like.
  6201. * In this case, `ReferenceElementNode` allows to refer to a specific
  6202. * element inside the data structure via an index.
  6203. *
  6204. * @augments ArrayElementNode
  6205. */
  6206. let ReferenceElementNode$1 = class ReferenceElementNode extends ArrayElementNode {
  6207. static get type() {
  6208. return 'ReferenceElementNode';
  6209. }
  6210. /**
  6211. * Constructs a new reference element node.
  6212. *
  6213. * @param {ReferenceBaseNode} referenceNode - The reference node.
  6214. * @param {Node} indexNode - The index node that defines the element access.
  6215. */
  6216. constructor( referenceNode, indexNode ) {
  6217. super( referenceNode, indexNode );
  6218. /**
  6219. * Similar to {@link ReferenceBaseNode#reference}, an additional
  6220. * property references to the current node.
  6221. *
  6222. * @type {?ReferenceBaseNode}
  6223. * @default null
  6224. */
  6225. this.referenceNode = referenceNode;
  6226. /**
  6227. * This flag can be used for type testing.
  6228. *
  6229. * @type {boolean}
  6230. * @readonly
  6231. * @default true
  6232. */
  6233. this.isReferenceElementNode = true;
  6234. }
  6235. /**
  6236. * This method is overwritten since the node type is inferred from
  6237. * the uniform type of the reference node.
  6238. *
  6239. * @return {string} The node type.
  6240. */
  6241. getNodeType() {
  6242. return this.referenceNode.uniformType;
  6243. }
  6244. generate( builder ) {
  6245. const snippet = super.generate( builder );
  6246. const arrayType = this.referenceNode.getNodeType();
  6247. const elementType = this.getNodeType();
  6248. return builder.format( snippet, arrayType, elementType );
  6249. }
  6250. };
  6251. /**
  6252. * Base class for nodes which establishes a reference to a property of another object.
  6253. * In this way, the value of the node is automatically linked to the value of
  6254. * referenced object. Reference nodes internally represent the linked value
  6255. * as a uniform.
  6256. *
  6257. * @augments Node
  6258. */
  6259. class ReferenceBaseNode extends Node {
  6260. static get type() {
  6261. return 'ReferenceBaseNode';
  6262. }
  6263. /**
  6264. * Constructs a new reference base node.
  6265. *
  6266. * @param {string} property - The name of the property the node refers to.
  6267. * @param {string} uniformType - The uniform type that should be used to represent the property value.
  6268. * @param {?Object} [object=null] - The object the property belongs to.
  6269. * @param {?number} [count=null] - When the linked property is an array-like, this parameter defines its length.
  6270. */
  6271. constructor( property, uniformType, object = null, count = null ) {
  6272. super();
  6273. /**
  6274. * The name of the property the node refers to.
  6275. *
  6276. * @type {string}
  6277. */
  6278. this.property = property;
  6279. /**
  6280. * The uniform type that should be used to represent the property value.
  6281. *
  6282. * @type {string}
  6283. */
  6284. this.uniformType = uniformType;
  6285. /**
  6286. * The object the property belongs to.
  6287. *
  6288. * @type {?Object}
  6289. * @default null
  6290. */
  6291. this.object = object;
  6292. /**
  6293. * When the linked property is an array, this parameter defines its length.
  6294. *
  6295. * @type {?number}
  6296. * @default null
  6297. */
  6298. this.count = count;
  6299. /**
  6300. * The property name might have dots so nested properties can be referred.
  6301. * The hierarchy of the names is stored inside this array.
  6302. *
  6303. * @type {Array<string>}
  6304. */
  6305. this.properties = property.split( '.' );
  6306. /**
  6307. * Points to the current referred object. This property exists next to {@link ReferenceNode#object}
  6308. * since the final reference might be updated from calling code.
  6309. *
  6310. * @type {?Object}
  6311. * @default null
  6312. */
  6313. this.reference = object;
  6314. /**
  6315. * The uniform node that holds the value of the reference node.
  6316. *
  6317. * @type {UniformNode}
  6318. * @default null
  6319. */
  6320. this.node = null;
  6321. /**
  6322. * The uniform group of the internal uniform.
  6323. *
  6324. * @type {UniformGroupNode}
  6325. * @default null
  6326. */
  6327. this.group = null;
  6328. /**
  6329. * Overwritten since reference nodes are updated per object.
  6330. *
  6331. * @type {string}
  6332. * @default 'object'
  6333. */
  6334. this.updateType = NodeUpdateType.OBJECT;
  6335. }
  6336. /**
  6337. * Sets the uniform group for this reference node.
  6338. *
  6339. * @param {UniformGroupNode} group - The uniform group to set.
  6340. * @return {ReferenceBaseNode} A reference to this node.
  6341. */
  6342. setGroup( group ) {
  6343. this.group = group;
  6344. return this;
  6345. }
  6346. /**
  6347. * When the referred property is array-like, this method can be used
  6348. * to access elements via an index node.
  6349. *
  6350. * @param {IndexNode} indexNode - indexNode.
  6351. * @return {ReferenceElementNode} A reference to an element.
  6352. */
  6353. element( indexNode ) {
  6354. return nodeObject( new ReferenceElementNode$1( this, nodeObject( indexNode ) ) );
  6355. }
  6356. /**
  6357. * Sets the node type which automatically defines the internal
  6358. * uniform type.
  6359. *
  6360. * @param {string} uniformType - The type to set.
  6361. */
  6362. setNodeType( uniformType ) {
  6363. const node = uniform( null, uniformType );
  6364. if ( this.group !== null ) {
  6365. node.setGroup( this.group );
  6366. }
  6367. this.node = node;
  6368. }
  6369. /**
  6370. * This method is overwritten since the node type is inferred from
  6371. * the type of the reference node.
  6372. *
  6373. * @param {NodeBuilder} builder - The current node builder.
  6374. * @return {string} The node type.
  6375. */
  6376. getNodeType( builder ) {
  6377. if ( this.node === null ) {
  6378. this.updateReference( builder );
  6379. this.updateValue();
  6380. }
  6381. return this.node.getNodeType( builder );
  6382. }
  6383. /**
  6384. * Returns the property value from the given referred object.
  6385. *
  6386. * @param {Object} [object=this.reference] - The object to retrieve the property value from.
  6387. * @return {any} The value.
  6388. */
  6389. getValueFromReference( object = this.reference ) {
  6390. const { properties } = this;
  6391. let value = object[ properties[ 0 ] ];
  6392. for ( let i = 1; i < properties.length; i ++ ) {
  6393. value = value[ properties[ i ] ];
  6394. }
  6395. return value;
  6396. }
  6397. /**
  6398. * Allows to update the reference based on the given state. The state is only
  6399. * evaluated {@link ReferenceBaseNode#object} is not set.
  6400. *
  6401. * @param {(NodeFrame|NodeBuilder)} state - The current state.
  6402. * @return {Object} The updated reference.
  6403. */
  6404. updateReference( state ) {
  6405. this.reference = this.object !== null ? this.object : state.object;
  6406. return this.reference;
  6407. }
  6408. /**
  6409. * The output of the reference node is the internal uniform node.
  6410. *
  6411. * @return {UniformNode} The output node.
  6412. */
  6413. setup() {
  6414. this.updateValue();
  6415. return this.node;
  6416. }
  6417. /**
  6418. * Overwritten to update the internal uniform value.
  6419. *
  6420. * @param {NodeFrame} frame - A reference to the current node frame.
  6421. */
  6422. update( /*frame*/ ) {
  6423. this.updateValue();
  6424. }
  6425. /**
  6426. * Retrieves the value from the referred object property and uses it
  6427. * to updated the internal uniform.
  6428. */
  6429. updateValue() {
  6430. if ( this.node === null ) this.setNodeType( this.uniformType );
  6431. const value = this.getValueFromReference();
  6432. if ( Array.isArray( value ) ) {
  6433. this.node.array = value;
  6434. } else {
  6435. this.node.value = value;
  6436. }
  6437. }
  6438. }
  6439. /**
  6440. * TSL function for creating a reference base node.
  6441. *
  6442. * @tsl
  6443. * @function
  6444. * @param {string} name - The name of the property the node refers to.
  6445. * @param {string} type - The uniform type that should be used to represent the property value.
  6446. * @param {Object} object - The object the property belongs to.
  6447. * @returns {ReferenceBaseNode}
  6448. */
  6449. const reference$1 = ( name, type, object ) => nodeObject( new ReferenceBaseNode( name, type, object ) );
  6450. /**
  6451. * This node is a special type of reference node which is intended
  6452. * for linking renderer properties with node values.
  6453. * ```js
  6454. * const exposureNode = rendererReference( 'toneMappingExposure', 'float', renderer );
  6455. * ```
  6456. * When changing `renderer.toneMappingExposure`, the node value of `exposureNode` will
  6457. * automatically be updated.
  6458. *
  6459. * @augments ReferenceBaseNode
  6460. */
  6461. class RendererReferenceNode extends ReferenceBaseNode {
  6462. static get type() {
  6463. return 'RendererReferenceNode';
  6464. }
  6465. /**
  6466. * Constructs a new renderer reference node.
  6467. *
  6468. * @param {string} property - The name of the property the node refers to.
  6469. * @param {string} inputType - The uniform type that should be used to represent the property value.
  6470. * @param {?Renderer} [renderer=null] - The renderer the property belongs to. When no renderer is set,
  6471. * the node refers to the renderer of the current state.
  6472. */
  6473. constructor( property, inputType, renderer = null ) {
  6474. super( property, inputType, renderer );
  6475. /**
  6476. * The renderer the property belongs to. When no renderer is set,
  6477. * the node refers to the renderer of the current state.
  6478. *
  6479. * @type {?Renderer}
  6480. * @default null
  6481. */
  6482. this.renderer = renderer;
  6483. this.setGroup( renderGroup );
  6484. }
  6485. /**
  6486. * Updates the reference based on the given state. The state is only evaluated
  6487. * {@link RendererReferenceNode#renderer} is not set.
  6488. *
  6489. * @param {(NodeFrame|NodeBuilder)} state - The current state.
  6490. * @return {Object} The updated reference.
  6491. */
  6492. updateReference( state ) {
  6493. this.reference = this.renderer !== null ? this.renderer : state.renderer;
  6494. return this.reference;
  6495. }
  6496. }
  6497. /**
  6498. * TSL function for creating a renderer reference node.
  6499. *
  6500. * @tsl
  6501. * @function
  6502. * @param {string} name - The name of the property the node refers to.
  6503. * @param {string} type - The uniform type that should be used to represent the property value.
  6504. * @param {?Renderer} [renderer=null] - The renderer the property belongs to. When no renderer is set,
  6505. * the node refers to the renderer of the current state.
  6506. * @returns {RendererReferenceNode}
  6507. */
  6508. const rendererReference = ( name, type, renderer = null ) => nodeObject( new RendererReferenceNode( name, type, renderer ) );
  6509. /**
  6510. * This node represents a tone mapping operation.
  6511. *
  6512. * @augments TempNode
  6513. */
  6514. class ToneMappingNode extends TempNode {
  6515. static get type() {
  6516. return 'ToneMappingNode';
  6517. }
  6518. /**
  6519. * Constructs a new tone mapping node.
  6520. *
  6521. * @param {number} toneMapping - The tone mapping type.
  6522. * @param {Node} exposureNode - The tone mapping exposure.
  6523. * @param {Node} [colorNode=null] - The color node to process.
  6524. */
  6525. constructor( toneMapping, exposureNode = toneMappingExposure, colorNode = null ) {
  6526. super( 'vec3' );
  6527. /**
  6528. * The tone mapping type.
  6529. *
  6530. * @private
  6531. * @type {number}
  6532. */
  6533. this._toneMapping = toneMapping;
  6534. /**
  6535. * The tone mapping exposure.
  6536. *
  6537. * @type {Node}
  6538. * @default null
  6539. */
  6540. this.exposureNode = exposureNode;
  6541. /**
  6542. * Represents the color to process.
  6543. *
  6544. * @type {?Node}
  6545. * @default null
  6546. */
  6547. this.colorNode = colorNode;
  6548. }
  6549. /**
  6550. * Overwrites the default `customCacheKey()` implementation by including the tone
  6551. * mapping type into the cache key.
  6552. *
  6553. * @return {number} The hash.
  6554. */
  6555. customCacheKey() {
  6556. return hash$1( this._toneMapping );
  6557. }
  6558. /**
  6559. * Sets the tone mapping type.
  6560. *
  6561. * @param {number} value - The tone mapping type.
  6562. * @return {ToneMappingNode} A reference to this node.
  6563. */
  6564. setToneMapping( value ) {
  6565. this._toneMapping = value;
  6566. return this;
  6567. }
  6568. /**
  6569. * Gets the tone mapping type.
  6570. *
  6571. * @returns {number} The tone mapping type.
  6572. */
  6573. getToneMapping() {
  6574. return this._toneMapping;
  6575. }
  6576. setup( builder ) {
  6577. const colorNode = this.colorNode || builder.context.color;
  6578. const toneMapping = this._toneMapping;
  6579. if ( toneMapping === NoToneMapping ) return colorNode;
  6580. let outputNode = null;
  6581. const toneMappingFn = builder.renderer.library.getToneMappingFunction( toneMapping );
  6582. if ( toneMappingFn !== null ) {
  6583. outputNode = vec4( toneMappingFn( colorNode.rgb, this.exposureNode ), colorNode.a );
  6584. } else {
  6585. error( 'ToneMappingNode: Unsupported Tone Mapping configuration.', toneMapping );
  6586. outputNode = colorNode;
  6587. }
  6588. return outputNode;
  6589. }
  6590. }
  6591. /**
  6592. * TSL function for creating a tone mapping node.
  6593. *
  6594. * @tsl
  6595. * @function
  6596. * @param {number} mapping - The tone mapping type.
  6597. * @param {Node<float> | number} exposure - The tone mapping exposure.
  6598. * @param {Node<vec3> | Color} color - The color node to process.
  6599. * @returns {ToneMappingNode<vec3>}
  6600. */
  6601. const toneMapping = ( mapping, exposure, color ) => nodeObject( new ToneMappingNode( mapping, nodeObject( exposure ), nodeObject( color ) ) );
  6602. /**
  6603. * TSL object that represents the global tone mapping exposure of the renderer.
  6604. *
  6605. * @tsl
  6606. * @type {RendererReferenceNode<vec3>}
  6607. */
  6608. const toneMappingExposure = /*@__PURE__*/ rendererReference( 'toneMappingExposure', 'float' );
  6609. addMethodChaining( 'toneMapping', ( color, mapping, exposure ) => toneMapping( mapping, exposure, color ) );
  6610. /**
  6611. * Internal buffer attribute library.
  6612. *
  6613. * @private
  6614. * @type {WeakMap<TypedArray, InterleavedBuffer>}
  6615. */
  6616. const _bufferLib = new WeakMap();
  6617. /**
  6618. * Internal method for retrieving or creating interleaved buffers.
  6619. *
  6620. * @private
  6621. * @param {TypedArray} value - The attribute data.
  6622. * @param {number} itemSize - The attribute item size.
  6623. * @returns {InterleavedBuffer} The interleaved buffer.
  6624. */
  6625. function _getBufferAttribute( value, itemSize ) {
  6626. let buffer = _bufferLib.get( value );
  6627. if ( buffer === undefined ) {
  6628. buffer = new InterleavedBuffer( value, itemSize );
  6629. _bufferLib.set( value, buffer );
  6630. }
  6631. return buffer;
  6632. }
  6633. /**
  6634. * In earlier `three.js` versions it was only possible to define attribute data
  6635. * on geometry level. With `BufferAttributeNode`, it is also possible to do this
  6636. * on the node level.
  6637. * ```js
  6638. * const geometry = new THREE.PlaneGeometry();
  6639. * const positionAttribute = geometry.getAttribute( 'position' );
  6640. *
  6641. * const colors = [];
  6642. * for ( let i = 0; i < position.count; i ++ ) {
  6643. * colors.push( 1, 0, 0 );
  6644. * }
  6645. *
  6646. * material.colorNode = bufferAttribute( new THREE.Float32BufferAttribute( colors, 3 ) );
  6647. * ```
  6648. * This new approach is especially interesting when geometry data are generated via
  6649. * compute shaders. The below line converts a storage buffer into an attribute node.
  6650. * ```js
  6651. * material.positionNode = positionBuffer.toAttribute();
  6652. * ```
  6653. * @augments InputNode
  6654. */
  6655. class BufferAttributeNode extends InputNode {
  6656. static get type() {
  6657. return 'BufferAttributeNode';
  6658. }
  6659. /**
  6660. * Constructs a new buffer attribute node.
  6661. *
  6662. * @param {BufferAttribute|InterleavedBuffer|TypedArray} value - The attribute data.
  6663. * @param {?string} [bufferType=null] - The buffer type (e.g. `'vec3'`).
  6664. * @param {number} [bufferStride=0] - The buffer stride.
  6665. * @param {number} [bufferOffset=0] - The buffer offset.
  6666. */
  6667. constructor( value, bufferType = null, bufferStride = 0, bufferOffset = 0 ) {
  6668. super( value, bufferType );
  6669. /**
  6670. * This flag can be used for type testing.
  6671. *
  6672. * @type {boolean}
  6673. * @readonly
  6674. * @default true
  6675. */
  6676. this.isBufferNode = true;
  6677. /**
  6678. * The buffer type (e.g. `'vec3'`).
  6679. *
  6680. * @type {?string}
  6681. * @default null
  6682. */
  6683. this.bufferType = bufferType;
  6684. /**
  6685. * The buffer stride.
  6686. *
  6687. * @type {number}
  6688. * @default 0
  6689. */
  6690. this.bufferStride = bufferStride;
  6691. /**
  6692. * The buffer offset.
  6693. *
  6694. * @type {number}
  6695. * @default 0
  6696. */
  6697. this.bufferOffset = bufferOffset;
  6698. /**
  6699. * The usage property. Set this to `THREE.DynamicDrawUsage` via `.setUsage()`,
  6700. * if you are planning to update the attribute data per frame.
  6701. *
  6702. * @type {number}
  6703. * @default StaticDrawUsage
  6704. */
  6705. this.usage = StaticDrawUsage;
  6706. /**
  6707. * Whether the attribute is instanced or not.
  6708. *
  6709. * @type {boolean}
  6710. * @default false
  6711. */
  6712. this.instanced = false;
  6713. /**
  6714. * A reference to the buffer attribute.
  6715. *
  6716. * @type {?BufferAttribute}
  6717. * @default null
  6718. */
  6719. this.attribute = null;
  6720. /**
  6721. * `BufferAttributeNode` sets this property to `true` by default.
  6722. *
  6723. * @type {boolean}
  6724. * @default true
  6725. */
  6726. this.global = true;
  6727. if ( value && value.isBufferAttribute === true && value.itemSize <= 4 ) {
  6728. this.attribute = value;
  6729. this.usage = value.usage;
  6730. this.instanced = value.isInstancedBufferAttribute;
  6731. }
  6732. }
  6733. /**
  6734. * This method is overwritten since the attribute data might be shared
  6735. * and thus the hash should be shared as well.
  6736. *
  6737. * @param {NodeBuilder} builder - The current node builder.
  6738. * @return {string} The hash.
  6739. */
  6740. getHash( builder ) {
  6741. if ( this.bufferStride === 0 && this.bufferOffset === 0 ) {
  6742. let bufferData = builder.globalCache.getData( this.value );
  6743. if ( bufferData === undefined ) {
  6744. bufferData = {
  6745. node: this
  6746. };
  6747. builder.globalCache.setData( this.value, bufferData );
  6748. }
  6749. return bufferData.node.uuid;
  6750. }
  6751. return this.uuid;
  6752. }
  6753. /**
  6754. * This method is overwritten since the node type is inferred from
  6755. * the buffer attribute.
  6756. *
  6757. * @param {NodeBuilder} builder - The current node builder.
  6758. * @return {string} The node type.
  6759. */
  6760. getNodeType( builder ) {
  6761. if ( this.bufferType === null ) {
  6762. this.bufferType = builder.getTypeFromAttribute( this.attribute );
  6763. }
  6764. return this.bufferType;
  6765. }
  6766. /**
  6767. * Depending on which value was passed to the node, `setup()` behaves
  6768. * differently. If no instance of `BufferAttribute` was passed, the method
  6769. * creates an internal attribute and configures it respectively.
  6770. *
  6771. * @param {NodeBuilder} builder - The current node builder.
  6772. */
  6773. setup( builder ) {
  6774. if ( this.attribute !== null ) return;
  6775. //
  6776. const type = this.getNodeType( builder );
  6777. const itemSize = builder.getTypeLength( type );
  6778. const value = this.value;
  6779. const stride = this.bufferStride || itemSize;
  6780. const offset = this.bufferOffset;
  6781. let buffer;
  6782. if ( value.isInterleavedBuffer === true ) {
  6783. buffer = value;
  6784. } else if ( value.isBufferAttribute === true ) {
  6785. buffer = _getBufferAttribute( value.array, stride );
  6786. } else {
  6787. buffer = _getBufferAttribute( value, stride );
  6788. }
  6789. const bufferAttribute = new InterleavedBufferAttribute( buffer, itemSize, offset );
  6790. buffer.setUsage( this.usage );
  6791. this.attribute = bufferAttribute;
  6792. this.attribute.isInstancedBufferAttribute = this.instanced; // @TODO: Add a possible: InstancedInterleavedBufferAttribute
  6793. }
  6794. /**
  6795. * Generates the code snippet of the buffer attribute node.
  6796. *
  6797. * @param {NodeBuilder} builder - The current node builder.
  6798. * @return {string} The generated code snippet.
  6799. */
  6800. generate( builder ) {
  6801. const nodeType = this.getNodeType( builder );
  6802. const nodeAttribute = builder.getBufferAttributeFromNode( this, nodeType );
  6803. const propertyName = builder.getPropertyName( nodeAttribute );
  6804. let output = null;
  6805. if ( builder.shaderStage === 'vertex' || builder.shaderStage === 'compute' ) {
  6806. this.name = propertyName;
  6807. output = propertyName;
  6808. } else {
  6809. const nodeVarying = varying( this );
  6810. output = nodeVarying.build( builder, nodeType );
  6811. }
  6812. return output;
  6813. }
  6814. /**
  6815. * Overwrites the default implementation to return a fixed value `'bufferAttribute'`.
  6816. *
  6817. * @param {NodeBuilder} builder - The current node builder.
  6818. * @return {string} The input type.
  6819. */
  6820. getInputType( /*builder*/ ) {
  6821. return 'bufferAttribute';
  6822. }
  6823. /**
  6824. * Sets the `usage` property to the given value.
  6825. *
  6826. * @param {number} value - The usage to set.
  6827. * @return {BufferAttributeNode} A reference to this node.
  6828. */
  6829. setUsage( value ) {
  6830. this.usage = value;
  6831. if ( this.attribute && this.attribute.isBufferAttribute === true ) {
  6832. this.attribute.usage = value;
  6833. }
  6834. return this;
  6835. }
  6836. /**
  6837. * Sets the `instanced` property to the given value.
  6838. *
  6839. * @param {boolean} value - The value to set.
  6840. * @return {BufferAttributeNode} A reference to this node.
  6841. */
  6842. setInstanced( value ) {
  6843. this.instanced = value;
  6844. return this;
  6845. }
  6846. }
  6847. /**
  6848. * Internal method for creating buffer attribute nodes.
  6849. *
  6850. * @private
  6851. * @param {BufferAttribute|InterleavedBuffer|TypedArray} array - The attribute data.
  6852. * @param {?string} [type=null] - The buffer type (e.g. `'vec3'`).
  6853. * @param {number} [stride=0] - The buffer stride.
  6854. * @param {number} [offset=0] - The buffer offset.
  6855. * @param {number} [usage=StaticDrawUsage] - The buffer usage.
  6856. * @param {boolean} [instanced=false] - Whether the buffer is instanced.
  6857. * @returns {BufferAttributeNode|Node} The buffer attribute node.
  6858. */
  6859. function createBufferAttribute( array, type = null, stride = 0, offset = 0, usage = StaticDrawUsage, instanced = false ) {
  6860. if ( type === 'mat3' || ( type === null && array.itemSize === 9 ) ) {
  6861. return mat3(
  6862. new BufferAttributeNode( array, 'vec3', 9, 0 ).setUsage( usage ).setInstanced( instanced ),
  6863. new BufferAttributeNode( array, 'vec3', 9, 3 ).setUsage( usage ).setInstanced( instanced ),
  6864. new BufferAttributeNode( array, 'vec3', 9, 6 ).setUsage( usage ).setInstanced( instanced )
  6865. );
  6866. } else if ( type === 'mat4' || ( type === null && array.itemSize === 16 ) ) {
  6867. return mat4(
  6868. new BufferAttributeNode( array, 'vec4', 16, 0 ).setUsage( usage ).setInstanced( instanced ),
  6869. new BufferAttributeNode( array, 'vec4', 16, 4 ).setUsage( usage ).setInstanced( instanced ),
  6870. new BufferAttributeNode( array, 'vec4', 16, 8 ).setUsage( usage ).setInstanced( instanced ),
  6871. new BufferAttributeNode( array, 'vec4', 16, 12 ).setUsage( usage ).setInstanced( instanced )
  6872. );
  6873. }
  6874. return new BufferAttributeNode( array, type, stride, offset );
  6875. }
  6876. /**
  6877. * TSL function for creating a buffer attribute node.
  6878. *
  6879. * @tsl
  6880. * @function
  6881. * @param {BufferAttribute|InterleavedBuffer|TypedArray} array - The attribute data.
  6882. * @param {?string} [type=null] - The buffer type (e.g. `'vec3'`).
  6883. * @param {number} [stride=0] - The buffer stride.
  6884. * @param {number} [offset=0] - The buffer offset.
  6885. * @returns {BufferAttributeNode|Node}
  6886. */
  6887. const bufferAttribute = ( array, type = null, stride = 0, offset = 0 ) => createBufferAttribute( array, type, stride, offset );
  6888. /**
  6889. * TSL function for creating a buffer attribute node but with dynamic draw usage.
  6890. * Use this function if attribute data are updated per frame.
  6891. *
  6892. * @tsl
  6893. * @function
  6894. * @param {BufferAttribute|InterleavedBuffer|TypedArray} array - The attribute data.
  6895. * @param {?string} [type=null] - The buffer type (e.g. `'vec3'`).
  6896. * @param {number} [stride=0] - The buffer stride.
  6897. * @param {number} [offset=0] - The buffer offset.
  6898. * @returns {BufferAttributeNode|Node}
  6899. */
  6900. const dynamicBufferAttribute = ( array, type = null, stride = 0, offset = 0 ) => createBufferAttribute( array, type, stride, offset, DynamicDrawUsage );
  6901. /**
  6902. * TSL function for creating a buffer attribute node but with enabled instancing
  6903. *
  6904. * @tsl
  6905. * @function
  6906. * @param {BufferAttribute|InterleavedBuffer|TypedArray} array - The attribute data.
  6907. * @param {?string} [type=null] - The buffer type (e.g. `'vec3'`).
  6908. * @param {number} [stride=0] - The buffer stride.
  6909. * @param {number} [offset=0] - The buffer offset.
  6910. * @returns {BufferAttributeNode|Node}
  6911. */
  6912. const instancedBufferAttribute = ( array, type = null, stride = 0, offset = 0 ) => createBufferAttribute( array, type, stride, offset, StaticDrawUsage, true );
  6913. /**
  6914. * TSL function for creating a buffer attribute node but with dynamic draw usage and enabled instancing
  6915. *
  6916. * @tsl
  6917. * @function
  6918. * @param {BufferAttribute|InterleavedBuffer|TypedArray} array - The attribute data.
  6919. * @param {?string} [type=null] - The buffer type (e.g. `'vec3'`).
  6920. * @param {number} [stride=0] - The buffer stride.
  6921. * @param {number} [offset=0] - The buffer offset.
  6922. * @returns {BufferAttributeNode|Node}
  6923. */
  6924. const instancedDynamicBufferAttribute = ( array, type = null, stride = 0, offset = 0 ) => createBufferAttribute( array, type, stride, offset, DynamicDrawUsage, true );
  6925. addMethodChaining( 'toAttribute', ( bufferNode ) => bufferAttribute( bufferNode.value ) );
  6926. /**
  6927. * TODO
  6928. *
  6929. * @augments Node
  6930. */
  6931. class ComputeNode extends Node {
  6932. static get type() {
  6933. return 'ComputeNode';
  6934. }
  6935. /**
  6936. * Constructs a new compute node.
  6937. *
  6938. * @param {Node} computeNode - TODO
  6939. * @param {Array<number>} workgroupSize - TODO.
  6940. */
  6941. constructor( computeNode, workgroupSize ) {
  6942. super( 'void' );
  6943. /**
  6944. * This flag can be used for type testing.
  6945. *
  6946. * @type {boolean}
  6947. * @readonly
  6948. * @default true
  6949. */
  6950. this.isComputeNode = true;
  6951. /**
  6952. * TODO
  6953. *
  6954. * @type {Node}
  6955. */
  6956. this.computeNode = computeNode;
  6957. /**
  6958. * TODO
  6959. *
  6960. * @type {Array<number>}
  6961. * @default [ 64 ]
  6962. */
  6963. this.workgroupSize = workgroupSize;
  6964. /**
  6965. * TODO
  6966. *
  6967. * @type {number|Array<number>}
  6968. */
  6969. this.count = null;
  6970. /**
  6971. * TODO
  6972. *
  6973. * @type {number}
  6974. */
  6975. this.version = 1;
  6976. /**
  6977. * The name or label of the uniform.
  6978. *
  6979. * @type {string}
  6980. * @default ''
  6981. */
  6982. this.name = '';
  6983. /**
  6984. * The `updateBeforeType` is set to `NodeUpdateType.OBJECT` since {@link ComputeNode#updateBefore}
  6985. * is executed once per object by default.
  6986. *
  6987. * @type {string}
  6988. * @default 'object'
  6989. */
  6990. this.updateBeforeType = NodeUpdateType.OBJECT;
  6991. /**
  6992. * TODO
  6993. *
  6994. * @type {?Function}
  6995. */
  6996. this.onInitFunction = null;
  6997. }
  6998. /**
  6999. * TODO
  7000. *
  7001. * @param {number|Array<number>} count - Array with [ x, y, z ] values for dispatch or a single number for the count
  7002. * @return {ComputeNode}
  7003. */
  7004. setCount( count ) {
  7005. this.count = count;
  7006. return this;
  7007. }
  7008. /**
  7009. * TODO
  7010. *
  7011. * @return {number|Array<number>}
  7012. */
  7013. getCount() {
  7014. return this.count;
  7015. }
  7016. /**
  7017. * Executes the `dispose` event for this node.
  7018. */
  7019. dispose() {
  7020. this.dispatchEvent( { type: 'dispose' } );
  7021. }
  7022. /**
  7023. * Sets the {@link ComputeNode#name} property.
  7024. *
  7025. * @param {string} name - The name of the uniform.
  7026. * @return {ComputeNode} A reference to this node.
  7027. */
  7028. setName( name ) {
  7029. this.name = name;
  7030. return this;
  7031. }
  7032. /**
  7033. * Sets the {@link ComputeNode#name} property.
  7034. *
  7035. * @deprecated
  7036. * @param {string} name - The name of the uniform.
  7037. * @return {ComputeNode} A reference to this node.
  7038. */
  7039. label( name ) {
  7040. warn( 'TSL: "label()" has been deprecated. Use "setName()" instead.' ); // @deprecated r179
  7041. return this.setName( name );
  7042. }
  7043. /**
  7044. * TODO
  7045. *
  7046. * @param {Function} callback - TODO.
  7047. * @return {ComputeNode} A reference to this node.
  7048. */
  7049. onInit( callback ) {
  7050. this.onInitFunction = callback;
  7051. return this;
  7052. }
  7053. /**
  7054. * The method execute the compute for this node.
  7055. *
  7056. * @param {NodeFrame} frame - A reference to the current node frame.
  7057. */
  7058. updateBefore( { renderer } ) {
  7059. renderer.compute( this );
  7060. }
  7061. setup( builder ) {
  7062. const result = this.computeNode.build( builder );
  7063. if ( result ) {
  7064. const properties = builder.getNodeProperties( this );
  7065. properties.outputComputeNode = result.outputNode;
  7066. result.outputNode = null;
  7067. }
  7068. return result;
  7069. }
  7070. generate( builder, output ) {
  7071. const { shaderStage } = builder;
  7072. if ( shaderStage === 'compute' ) {
  7073. const snippet = this.computeNode.build( builder, 'void' );
  7074. if ( snippet !== '' ) {
  7075. builder.addLineFlowCode( snippet, this );
  7076. }
  7077. } else {
  7078. const properties = builder.getNodeProperties( this );
  7079. const outputComputeNode = properties.outputComputeNode;
  7080. if ( outputComputeNode ) {
  7081. return outputComputeNode.build( builder, output );
  7082. }
  7083. }
  7084. }
  7085. }
  7086. /**
  7087. * TSL function for creating a compute kernel node.
  7088. *
  7089. * @tsl
  7090. * @function
  7091. * @param {Node} node - TODO
  7092. * @param {Array<number>} [workgroupSize=[64]] - TODO.
  7093. * @returns {AtomicFunctionNode}
  7094. */
  7095. const computeKernel = ( node, workgroupSize = [ 64 ] ) => {
  7096. if ( workgroupSize.length === 0 || workgroupSize.length > 3 ) {
  7097. error( 'TSL: compute() workgroupSize must have 1, 2, or 3 elements' );
  7098. }
  7099. for ( let i = 0; i < workgroupSize.length; i ++ ) {
  7100. const val = workgroupSize[ i ];
  7101. if ( typeof val !== 'number' || val <= 0 || ! Number.isInteger( val ) ) {
  7102. error( `TSL: compute() workgroupSize element at index [ ${ i } ] must be a positive integer` );
  7103. }
  7104. }
  7105. // Implicit fill-up to [ x, y, z ] with 1s, just like WGSL treats @workgroup_size when fewer dimensions are specified
  7106. while ( workgroupSize.length < 3 ) workgroupSize.push( 1 );
  7107. //
  7108. return nodeObject( new ComputeNode( nodeObject( node ), workgroupSize ) );
  7109. };
  7110. /**
  7111. * TSL function for creating a compute node.
  7112. *
  7113. * @tsl
  7114. * @function
  7115. * @param {Node} node - TODO
  7116. * @param {number|Array<number>} count - TODO.
  7117. * @param {Array<number>} [workgroupSize=[64]] - TODO.
  7118. * @returns {AtomicFunctionNode}
  7119. */
  7120. const compute = ( node, count, workgroupSize ) => computeKernel( node, workgroupSize ).setCount( count );
  7121. addMethodChaining( 'compute', compute );
  7122. addMethodChaining( 'computeKernel', computeKernel );
  7123. /**
  7124. * This node can be used as a cache management component for another node.
  7125. * Caching is in general used by default in {@link NodeBuilder} but this node
  7126. * allows the usage of a shared parent cache during the build process.
  7127. *
  7128. * @augments Node
  7129. */
  7130. class IsolateNode extends Node {
  7131. static get type() {
  7132. return 'IsolateNode';
  7133. }
  7134. /**
  7135. * Constructs a new cache node.
  7136. *
  7137. * @param {Node} node - The node that should be cached.
  7138. * @param {boolean} [parent=true] - Whether this node refers to a shared parent cache or not.
  7139. */
  7140. constructor( node, parent = true ) {
  7141. super();
  7142. /**
  7143. * The node that should be cached.
  7144. *
  7145. * @type {Node}
  7146. */
  7147. this.node = node;
  7148. /**
  7149. * Whether this node refers to a shared parent cache or not.
  7150. *
  7151. * @type {boolean}
  7152. * @default true
  7153. */
  7154. this.parent = parent;
  7155. /**
  7156. * This flag can be used for type testing.
  7157. *
  7158. * @type {boolean}
  7159. * @readonly
  7160. * @default true
  7161. */
  7162. this.isIsolateNode = true;
  7163. }
  7164. getNodeType( builder ) {
  7165. const previousCache = builder.getCache();
  7166. const cache = builder.getCacheFromNode( this, this.parent );
  7167. builder.setCache( cache );
  7168. const nodeType = this.node.getNodeType( builder );
  7169. builder.setCache( previousCache );
  7170. return nodeType;
  7171. }
  7172. build( builder, ...params ) {
  7173. const previousCache = builder.getCache();
  7174. const cache = builder.getCacheFromNode( this, this.parent );
  7175. builder.setCache( cache );
  7176. const data = this.node.build( builder, ...params );
  7177. builder.setCache( previousCache );
  7178. return data;
  7179. }
  7180. setParent( parent ) {
  7181. this.parent = parent;
  7182. return this;
  7183. }
  7184. getParent() {
  7185. return this.parent;
  7186. }
  7187. }
  7188. /**
  7189. * TSL function for creating a cache node.
  7190. *
  7191. * @tsl
  7192. * @function
  7193. * @param {Node} node - The node that should be cached.
  7194. * @returns {IsolateNode}
  7195. */
  7196. const isolate = ( node ) => new IsolateNode( nodeObject( node ) );
  7197. /**
  7198. * TSL function for creating a cache node.
  7199. *
  7200. * @tsl
  7201. * @function
  7202. * @deprecated
  7203. * @param {Node} node - The node that should be cached.
  7204. * @param {boolean} [parent=true] - Whether this node refers to a shared parent cache or not.
  7205. * @returns {IsolateNode}
  7206. */
  7207. function cache( node, parent = true ) {
  7208. warn( 'TSL: "cache()" has been deprecated. Use "isolate()" instead.' ); // @deprecated r181
  7209. return isolate( node ).setParent( parent );
  7210. }
  7211. addMethodChaining( 'cache', cache );
  7212. addMethodChaining( 'isolate', isolate );
  7213. /**
  7214. * The class generates the code of a given node but returns another node in the output.
  7215. * This can be used to call a method or node that does not return a value, i.e.
  7216. * type `void` on an input where returning a value is required. Example:
  7217. *
  7218. * ```js
  7219. * material.colorNode = myColor.bypass( runVoidFn() )
  7220. *```
  7221. *
  7222. * @augments Node
  7223. */
  7224. class BypassNode extends Node {
  7225. static get type() {
  7226. return 'BypassNode';
  7227. }
  7228. /**
  7229. * Constructs a new bypass node.
  7230. *
  7231. * @param {Node} outputNode - The output node.
  7232. * @param {Node} callNode - The call node.
  7233. */
  7234. constructor( outputNode, callNode ) {
  7235. super();
  7236. /**
  7237. * This flag can be used for type testing.
  7238. *
  7239. * @type {boolean}
  7240. * @readonly
  7241. * @default true
  7242. */
  7243. this.isBypassNode = true;
  7244. /**
  7245. * The output node.
  7246. *
  7247. * @type {Node}
  7248. */
  7249. this.outputNode = outputNode;
  7250. /**
  7251. * The call node.
  7252. *
  7253. * @type {Node}
  7254. */
  7255. this.callNode = callNode;
  7256. }
  7257. getNodeType( builder ) {
  7258. return this.outputNode.getNodeType( builder );
  7259. }
  7260. generate( builder ) {
  7261. const snippet = this.callNode.build( builder, 'void' );
  7262. if ( snippet !== '' ) {
  7263. builder.addLineFlowCode( snippet, this );
  7264. }
  7265. return this.outputNode.build( builder );
  7266. }
  7267. }
  7268. /**
  7269. * TSL function for creating a bypass node.
  7270. *
  7271. * @tsl
  7272. * @function
  7273. * @param {Node} outputNode - The output node.
  7274. * @param {Node} callNode - The call node.
  7275. * @returns {BypassNode}
  7276. */
  7277. const bypass = /*@__PURE__*/ nodeProxy( BypassNode ).setParameterLength( 2 );
  7278. addMethodChaining( 'bypass', bypass );
  7279. /**
  7280. * This node allows to remap a node value from one range into another. E.g a value of
  7281. * `0.4` in the range `[ 0.3, 0.5 ]` should be remapped into the normalized range `[ 0, 1 ]`.
  7282. * `RemapNode` takes care of that and converts the original value of `0.4` to `0.5`.
  7283. *
  7284. * @augments Node
  7285. */
  7286. class RemapNode extends Node {
  7287. static get type() {
  7288. return 'RemapNode';
  7289. }
  7290. /**
  7291. * Constructs a new remap node.
  7292. *
  7293. * @param {Node} node - The node that should be remapped.
  7294. * @param {Node} inLowNode - The source or current lower bound of the range.
  7295. * @param {Node} inHighNode - The source or current upper bound of the range.
  7296. * @param {Node} [outLowNode=float(0)] - The target lower bound of the range.
  7297. * @param {Node} [outHighNode=float(1)] - The target upper bound of the range.
  7298. */
  7299. constructor( node, inLowNode, inHighNode, outLowNode = float( 0 ), outHighNode = float( 1 ) ) {
  7300. super();
  7301. /**
  7302. * The node that should be remapped.
  7303. *
  7304. * @type {Node}
  7305. */
  7306. this.node = node;
  7307. /**
  7308. * The source or current lower bound of the range.
  7309. *
  7310. * @type {Node}
  7311. */
  7312. this.inLowNode = inLowNode;
  7313. /**
  7314. * The source or current upper bound of the range.
  7315. *
  7316. * @type {Node}
  7317. */
  7318. this.inHighNode = inHighNode;
  7319. /**
  7320. * The target lower bound of the range.
  7321. *
  7322. * @type {Node}
  7323. * @default float(0)
  7324. */
  7325. this.outLowNode = outLowNode;
  7326. /**
  7327. * The target upper bound of the range.
  7328. *
  7329. * @type {Node}
  7330. * @default float(1)
  7331. */
  7332. this.outHighNode = outHighNode;
  7333. /**
  7334. * Whether the node value should be clamped before
  7335. * remapping it to the target range.
  7336. *
  7337. * @type {boolean}
  7338. * @default true
  7339. */
  7340. this.doClamp = true;
  7341. }
  7342. setup() {
  7343. const { node, inLowNode, inHighNode, outLowNode, outHighNode, doClamp } = this;
  7344. let t = node.sub( inLowNode ).div( inHighNode.sub( inLowNode ) );
  7345. if ( doClamp === true ) t = t.clamp();
  7346. return t.mul( outHighNode.sub( outLowNode ) ).add( outLowNode );
  7347. }
  7348. }
  7349. /**
  7350. * TSL function for creating a remap node.
  7351. *
  7352. * @tsl
  7353. * @function
  7354. * @param {Node} node - The node that should be remapped.
  7355. * @param {Node} inLowNode - The source or current lower bound of the range.
  7356. * @param {Node} inHighNode - The source or current upper bound of the range.
  7357. * @param {?Node} [outLowNode=float(0)] - The target lower bound of the range.
  7358. * @param {?Node} [outHighNode=float(1)] - The target upper bound of the range.
  7359. * @returns {RemapNode}
  7360. */
  7361. const remap = /*@__PURE__*/ nodeProxy( RemapNode, null, null, { doClamp: false } ).setParameterLength( 3, 5 );
  7362. /**
  7363. * TSL function for creating a remap node, but with enabled clamping.
  7364. *
  7365. * @tsl
  7366. * @function
  7367. * @param {Node} node - The node that should be remapped.
  7368. * @param {Node} inLowNode - The source or current lower bound of the range.
  7369. * @param {Node} inHighNode - The source or current upper bound of the range.
  7370. * @param {?Node} [outLowNode=float(0)] - The target lower bound of the range.
  7371. * @param {?Node} [outHighNode=float(1)] - The target upper bound of the range.
  7372. * @returns {RemapNode}
  7373. */
  7374. const remapClamp = /*@__PURE__*/ nodeProxy( RemapNode ).setParameterLength( 3, 5 );
  7375. addMethodChaining( 'remap', remap );
  7376. addMethodChaining( 'remapClamp', remapClamp );
  7377. /**
  7378. * This class can be used to implement basic expressions in shader code.
  7379. * Basic examples for that are `return`, `continue` or `discard` statements.
  7380. *
  7381. * @augments Node
  7382. */
  7383. class ExpressionNode extends Node {
  7384. static get type() {
  7385. return 'ExpressionNode';
  7386. }
  7387. /**
  7388. * Constructs a new expression node.
  7389. *
  7390. * @param {string} [snippet=''] - The native code snippet.
  7391. * @param {string} [nodeType='void'] - The node type.
  7392. */
  7393. constructor( snippet = '', nodeType = 'void' ) {
  7394. super( nodeType );
  7395. /**
  7396. * The native code snippet.
  7397. *
  7398. * @type {string}
  7399. * @default ''
  7400. */
  7401. this.snippet = snippet;
  7402. }
  7403. generate( builder, output ) {
  7404. const type = this.getNodeType( builder );
  7405. const snippet = this.snippet;
  7406. if ( type === 'void' ) {
  7407. builder.addLineFlowCode( snippet, this );
  7408. } else {
  7409. return builder.format( snippet, type, output );
  7410. }
  7411. }
  7412. }
  7413. /**
  7414. * TSL function for creating an expression node.
  7415. *
  7416. * @tsl
  7417. * @function
  7418. * @param {string} [snippet] - The native code snippet.
  7419. * @param {?string} [nodeType='void'] - The node type.
  7420. * @returns {ExpressionNode}
  7421. */
  7422. const expression = /*@__PURE__*/ nodeProxy( ExpressionNode ).setParameterLength( 1, 2 );
  7423. /**
  7424. * Represents a `discard` shader operation in TSL.
  7425. *
  7426. * @tsl
  7427. * @function
  7428. * @param {?ConditionalNode} conditional - An optional conditional node. It allows to decide whether the discard should be executed or not.
  7429. * @return {Node} The `discard` expression.
  7430. */
  7431. const Discard = ( conditional ) => ( conditional ? select( conditional, expression( 'discard' ) ) : expression( 'discard' ) ).toStack();
  7432. /**
  7433. * Represents a `return` shader operation in TSL.
  7434. *
  7435. * @tsl
  7436. * @function
  7437. * @return {ExpressionNode} The `return` expression.
  7438. */
  7439. const Return = () => expression( 'return' ).toStack();
  7440. addMethodChaining( 'discard', Discard );
  7441. /**
  7442. * Normally, tone mapping and color conversion happens automatically
  7443. * before outputting pixel too the default (screen) framebuffer. In certain
  7444. * post processing setups this happens to late because certain effects
  7445. * require e.g. sRGB input. For such scenarios, `RenderOutputNode` can be used
  7446. * to apply tone mapping and color space conversion at an arbitrary point
  7447. * in the effect chain.
  7448. *
  7449. * When applying tone mapping and color space conversion manually with this node,
  7450. * you have to set {@link PostProcessing#outputColorTransform} to `false`.
  7451. *
  7452. * ```js
  7453. * const postProcessing = new PostProcessing( renderer );
  7454. * postProcessing.outputColorTransform = false;
  7455. *
  7456. * const scenePass = pass( scene, camera );
  7457. * const outputPass = renderOutput( scenePass );
  7458. *
  7459. * postProcessing.outputNode = outputPass;
  7460. * ```
  7461. *
  7462. * @augments TempNode
  7463. */
  7464. class RenderOutputNode extends TempNode {
  7465. static get type() {
  7466. return 'RenderOutputNode';
  7467. }
  7468. /**
  7469. * Constructs a new render output node.
  7470. *
  7471. * @param {Node} colorNode - The color node to process.
  7472. * @param {?number} toneMapping - The tone mapping type.
  7473. * @param {?string} outputColorSpace - The output color space.
  7474. */
  7475. constructor( colorNode, toneMapping, outputColorSpace ) {
  7476. super( 'vec4' );
  7477. /**
  7478. * The color node to process.
  7479. *
  7480. * @type {Node}
  7481. */
  7482. this.colorNode = colorNode;
  7483. /**
  7484. * The tone mapping type.
  7485. *
  7486. * @private
  7487. * @type {?number}
  7488. */
  7489. this._toneMapping = toneMapping;
  7490. /**
  7491. * The output color space.
  7492. *
  7493. * @type {?string}
  7494. */
  7495. this.outputColorSpace = outputColorSpace;
  7496. /**
  7497. * This flag can be used for type testing.
  7498. *
  7499. * @type {boolean}
  7500. * @readonly
  7501. * @default true
  7502. */
  7503. this.isRenderOutputNode = true;
  7504. }
  7505. /**
  7506. * Sets the tone mapping type.
  7507. *
  7508. * @param {number} value - The tone mapping type.
  7509. * @return {ToneMappingNode} A reference to this node.
  7510. */
  7511. setToneMapping( value ) {
  7512. this._toneMapping = value;
  7513. return this;
  7514. }
  7515. /**
  7516. * Gets the tone mapping type.
  7517. *
  7518. * @returns {number} The tone mapping type.
  7519. */
  7520. getToneMapping() {
  7521. return this._toneMapping;
  7522. }
  7523. setup( { context } ) {
  7524. let outputNode = this.colorNode || context.color;
  7525. // tone mapping
  7526. const toneMapping = ( this._toneMapping !== null ? this._toneMapping : context.toneMapping ) || NoToneMapping;
  7527. const outputColorSpace = ( this.outputColorSpace !== null ? this.outputColorSpace : context.outputColorSpace ) || NoColorSpace;
  7528. if ( toneMapping !== NoToneMapping ) {
  7529. outputNode = outputNode.toneMapping( toneMapping );
  7530. }
  7531. // working to output color space
  7532. if ( outputColorSpace !== NoColorSpace && outputColorSpace !== ColorManagement.workingColorSpace ) {
  7533. outputNode = outputNode.workingToColorSpace( outputColorSpace );
  7534. }
  7535. return outputNode;
  7536. }
  7537. }
  7538. /**
  7539. * TSL function for creating a posterize node.
  7540. *
  7541. * @tsl
  7542. * @function
  7543. * @param {Node} color - The color node to process.
  7544. * @param {?number} [toneMapping=null] - The tone mapping type.
  7545. * @param {?string} [outputColorSpace=null] - The output color space.
  7546. * @returns {RenderOutputNode}
  7547. */
  7548. const renderOutput = ( color, toneMapping = null, outputColorSpace = null ) => nodeObject( new RenderOutputNode( nodeObject( color ), toneMapping, outputColorSpace ) );
  7549. addMethodChaining( 'renderOutput', renderOutput );
  7550. class DebugNode extends TempNode {
  7551. static get type() {
  7552. return 'DebugNode';
  7553. }
  7554. constructor( node, callback = null ) {
  7555. super();
  7556. this.node = node;
  7557. this.callback = callback;
  7558. }
  7559. getNodeType( builder ) {
  7560. return this.node.getNodeType( builder );
  7561. }
  7562. setup( builder ) {
  7563. return this.node.build( builder );
  7564. }
  7565. analyze( builder ) {
  7566. return this.node.build( builder );
  7567. }
  7568. generate( builder ) {
  7569. const callback = this.callback;
  7570. const snippet = this.node.build( builder );
  7571. const title = '--- TSL debug - ' + builder.shaderStage + ' shader ---';
  7572. const border = '-'.repeat( title.length );
  7573. let code = '';
  7574. code += '// #' + title + '#\n';
  7575. code += builder.flow.code.replace( /^\t/mg, '' ) + '\n';
  7576. code += '/* ... */ ' + snippet + ' /* ... */\n';
  7577. code += '// #' + border + '#\n';
  7578. if ( callback !== null ) {
  7579. callback( builder, code );
  7580. } else {
  7581. log$1( code );
  7582. }
  7583. return snippet;
  7584. }
  7585. }
  7586. /**
  7587. * TSL function for creating a debug node.
  7588. *
  7589. * @tsl
  7590. * @function
  7591. * @param {Node} node - The node to debug.
  7592. * @param {?Function} [callback=null] - Optional callback function to handle the debug output.
  7593. * @returns {DebugNode}
  7594. */
  7595. const debug = ( node, callback = null ) => nodeObject( new DebugNode( nodeObject( node ), callback ) ).toStack();
  7596. addMethodChaining( 'debug', debug );
  7597. /**
  7598. * InspectorBase is the base class for all inspectors.
  7599. *
  7600. * @class InspectorBase
  7601. */
  7602. class InspectorBase {
  7603. /**
  7604. * Creates a new InspectorBase.
  7605. */
  7606. constructor() {
  7607. /**
  7608. * The renderer associated with this inspector.
  7609. *
  7610. * @type {WebGLRenderer}
  7611. * @private
  7612. */
  7613. this._renderer = null;
  7614. /**
  7615. * The current frame being processed.
  7616. *
  7617. * @type {Object}
  7618. */
  7619. this.currentFrame = null;
  7620. }
  7621. /**
  7622. * Returns the node frame for the current renderer.
  7623. *
  7624. * @return {Object} The node frame.
  7625. */
  7626. get nodeFrame() {
  7627. return this._renderer._nodes.nodeFrame;
  7628. }
  7629. /**
  7630. * Sets the renderer for this inspector.
  7631. *
  7632. * @param {WebGLRenderer} renderer - The renderer to associate with this inspector.
  7633. * @return {InspectorBase} This inspector instance.
  7634. */
  7635. setRenderer( renderer ) {
  7636. this._renderer = renderer;
  7637. return this;
  7638. }
  7639. /**
  7640. * Returns the renderer associated with this inspector.
  7641. *
  7642. * @return {WebGLRenderer} The associated renderer.
  7643. */
  7644. getRenderer() {
  7645. return this._renderer;
  7646. }
  7647. /**
  7648. * Initializes the inspector.
  7649. */
  7650. init() { }
  7651. /**
  7652. * Called when a frame begins.
  7653. */
  7654. begin() { }
  7655. /**
  7656. * Called when a frame ends.
  7657. */
  7658. finish() { }
  7659. /**
  7660. * Inspects a node.
  7661. *
  7662. * @param {Node} node - The node to inspect.
  7663. */
  7664. inspect( /*node*/ ) { }
  7665. /**
  7666. * When a compute operation is performed.
  7667. *
  7668. * @param {ComputeNode} computeNode - The compute node being executed.
  7669. * @param {number|Array<number>} dispatchSizeOrCount - The dispatch size or count.
  7670. */
  7671. computeAsync( /*computeNode, dispatchSizeOrCount*/ ) { }
  7672. /**
  7673. * Called when a compute operation begins.
  7674. *
  7675. * @param {string} uid - A unique identifier for the render context.
  7676. * @param {ComputeNode} computeNode - The compute node being executed.
  7677. */
  7678. beginCompute( /*uid, computeNode*/ ) { }
  7679. /**
  7680. * Called when a compute operation ends.
  7681. *
  7682. * @param {string} uid - A unique identifier for the render context.
  7683. * @param {ComputeNode} computeNode - The compute node being executed.
  7684. */
  7685. finishCompute( /*uid*/ ) { }
  7686. /**
  7687. * Called when a render operation begins.
  7688. *
  7689. * @param {string} uid - A unique identifier for the render context.
  7690. * @param {Scene} scene - The scene being rendered.
  7691. * @param {Camera} camera - The camera being used for rendering.
  7692. * @param {?WebGLRenderTarget} renderTarget - The render target, if any.
  7693. */
  7694. beginRender( /*uid, scene, camera, renderTarget*/ ) { }
  7695. /**
  7696. * Called when an animation loop ends.
  7697. *
  7698. * @param {string} uid - A unique identifier for the render context.
  7699. */
  7700. finishRender( /*uid*/ ) { }
  7701. /**
  7702. * Called when a texture copy operation is performed.
  7703. *
  7704. * @param {Texture} srcTexture - The source texture.
  7705. * @param {Texture} dstTexture - The destination texture.
  7706. */
  7707. copyTextureToTexture( /*srcTexture, dstTexture*/ ) { }
  7708. /**
  7709. * Called when a framebuffer copy operation is performed.
  7710. *
  7711. * @param {Texture} framebufferTexture - The texture associated with the framebuffer.
  7712. */
  7713. copyFramebufferToTexture( /*framebufferTexture*/ ) { }
  7714. }
  7715. /**
  7716. * InspectorNode is a wrapper node that allows inspection of node values during rendering.
  7717. * It can be used to debug or analyze node outputs in the rendering pipeline.
  7718. *
  7719. * @augments Node
  7720. */
  7721. class InspectorNode extends Node {
  7722. /**
  7723. * Returns the type of the node.
  7724. *
  7725. * @returns {string}
  7726. */
  7727. static get type() {
  7728. return 'InspectorNode';
  7729. }
  7730. /**
  7731. * Creates an InspectorNode.
  7732. *
  7733. * @param {Node} node - The node to inspect.
  7734. * @param {string} [name=''] - Optional name for the inspector node.
  7735. * @param {Function|null} [callback=null] - Optional callback to modify the node during setup.
  7736. */
  7737. constructor( node, name = '', callback = null ) {
  7738. super();
  7739. this.node = node;
  7740. this.name = name;
  7741. this.callback = callback;
  7742. this.updateType = NodeUpdateType.FRAME;
  7743. this.isInspectorNode = true;
  7744. }
  7745. /**
  7746. * Returns the name of the inspector node.
  7747. *
  7748. * @returns {string}
  7749. */
  7750. getName() {
  7751. return this.name || this.node.name;
  7752. }
  7753. /**
  7754. * Updates the inspector node, allowing inspection of the wrapped node.
  7755. *
  7756. * @param {NodeFrame} frame - A reference to the current node frame.
  7757. */
  7758. update( frame ) {
  7759. frame.renderer.inspector.inspect( this );
  7760. }
  7761. /**
  7762. * Returns the type of the wrapped node.
  7763. *
  7764. * @param {NodeBuilder} builder - The node builder.
  7765. * @returns {string}
  7766. */
  7767. getNodeType( builder ) {
  7768. return this.node.getNodeType( builder );
  7769. }
  7770. /**
  7771. * Sets up the inspector node.
  7772. *
  7773. * @param {NodeBuilder} builder - The node builder.
  7774. * @returns {Node} The setup node.
  7775. */
  7776. setup( builder ) {
  7777. let node = this.node;
  7778. if ( builder.context.inspector === true && this.callback !== null ) {
  7779. node = this.callback( node );
  7780. }
  7781. if ( builder.renderer.backend.isWebGPUBackend !== true && builder.renderer.inspector.constructor !== InspectorBase ) {
  7782. warnOnce( 'TSL: ".toInspector()" is only available with WebGPU.' );
  7783. }
  7784. return node;
  7785. }
  7786. }
  7787. /**
  7788. * Creates an inspector node to wrap around a given node for inspection purposes.
  7789. *
  7790. * @tsl
  7791. * @param {Node} node - The node to inspect.
  7792. * @param {string} [name=''] - Optional name for the inspector node.
  7793. * @param {Function|null} [callback=null] - Optional callback to modify the node during setup.
  7794. * @returns {Node} The inspector node.
  7795. */
  7796. function inspector( node, name = '', callback = null ) {
  7797. node = nodeObject( node );
  7798. return node.before( new InspectorNode( node, name, callback ) );
  7799. }
  7800. addMethodChaining( 'toInspector', inspector );
  7801. function addNodeElement( name/*, nodeElement*/ ) {
  7802. warn( 'TSL: AddNodeElement has been removed in favor of tree-shaking. Trying add', name );
  7803. }
  7804. /**
  7805. * Base class for representing shader attributes as nodes.
  7806. *
  7807. * @augments Node
  7808. */
  7809. class AttributeNode extends Node {
  7810. static get type() {
  7811. return 'AttributeNode';
  7812. }
  7813. /**
  7814. * Constructs a new attribute node.
  7815. *
  7816. * @param {string} attributeName - The name of the attribute.
  7817. * @param {?string} nodeType - The node type.
  7818. */
  7819. constructor( attributeName, nodeType = null ) {
  7820. super( nodeType );
  7821. /**
  7822. * `AttributeNode` sets this property to `true` by default.
  7823. *
  7824. * @type {boolean}
  7825. * @default true
  7826. */
  7827. this.global = true;
  7828. this._attributeName = attributeName;
  7829. }
  7830. getHash( builder ) {
  7831. return this.getAttributeName( builder );
  7832. }
  7833. getNodeType( builder ) {
  7834. let nodeType = this.nodeType;
  7835. if ( nodeType === null ) {
  7836. const attributeName = this.getAttributeName( builder );
  7837. if ( builder.hasGeometryAttribute( attributeName ) ) {
  7838. const attribute = builder.geometry.getAttribute( attributeName );
  7839. nodeType = builder.getTypeFromAttribute( attribute );
  7840. } else {
  7841. nodeType = 'float';
  7842. }
  7843. }
  7844. return nodeType;
  7845. }
  7846. /**
  7847. * Sets the attribute name to the given value. The method can be
  7848. * overwritten in derived classes if the final name must be computed
  7849. * analytically.
  7850. *
  7851. * @param {string} attributeName - The name of the attribute.
  7852. * @return {AttributeNode} A reference to this node.
  7853. */
  7854. setAttributeName( attributeName ) {
  7855. this._attributeName = attributeName;
  7856. return this;
  7857. }
  7858. /**
  7859. * Returns the attribute name of this node. The method can be
  7860. * overwritten in derived classes if the final name must be computed
  7861. * analytically.
  7862. *
  7863. * @param {NodeBuilder} builder - The current node builder.
  7864. * @return {string} The attribute name.
  7865. */
  7866. getAttributeName( /*builder*/ ) {
  7867. return this._attributeName;
  7868. }
  7869. generate( builder ) {
  7870. const attributeName = this.getAttributeName( builder );
  7871. const nodeType = this.getNodeType( builder );
  7872. const geometryAttribute = builder.hasGeometryAttribute( attributeName );
  7873. if ( geometryAttribute === true ) {
  7874. const attribute = builder.geometry.getAttribute( attributeName );
  7875. const attributeType = builder.getTypeFromAttribute( attribute );
  7876. const nodeAttribute = builder.getAttribute( attributeName, attributeType );
  7877. if ( builder.shaderStage === 'vertex' ) {
  7878. return builder.format( nodeAttribute.name, attributeType, nodeType );
  7879. } else {
  7880. const nodeVarying = varying( this );
  7881. return nodeVarying.build( builder, nodeType );
  7882. }
  7883. } else {
  7884. warn( `AttributeNode: Vertex attribute "${ attributeName }" not found on geometry.` );
  7885. return builder.generateConst( nodeType );
  7886. }
  7887. }
  7888. serialize( data ) {
  7889. super.serialize( data );
  7890. data.global = this.global;
  7891. data._attributeName = this._attributeName;
  7892. }
  7893. deserialize( data ) {
  7894. super.deserialize( data );
  7895. this.global = data.global;
  7896. this._attributeName = data._attributeName;
  7897. }
  7898. }
  7899. /**
  7900. * TSL function for creating an attribute node.
  7901. *
  7902. * @tsl
  7903. * @function
  7904. * @param {string} name - The name of the attribute.
  7905. * @param {?string} [nodeType=null] - The node type.
  7906. * @returns {AttributeNode}
  7907. */
  7908. const attribute = ( name, nodeType = null ) => nodeObject( new AttributeNode( name, nodeType ) );
  7909. /**
  7910. * TSL function for creating an uv attribute node with the given index.
  7911. *
  7912. * @tsl
  7913. * @function
  7914. * @param {number} [index=0] - The uv index.
  7915. * @return {AttributeNode<vec2>} The uv attribute node.
  7916. */
  7917. const uv$1 = ( index = 0 ) => attribute( 'uv' + ( index > 0 ? index : '' ), 'vec2' );
  7918. /**
  7919. * A node that represents the dimensions of a texture. The texture size is
  7920. * retrieved in the shader via built-in shader functions like `textureDimensions()`
  7921. * or `textureSize()`.
  7922. *
  7923. * @augments Node
  7924. */
  7925. class TextureSizeNode extends Node {
  7926. static get type() {
  7927. return 'TextureSizeNode';
  7928. }
  7929. /**
  7930. * Constructs a new texture size node.
  7931. *
  7932. * @param {TextureNode} textureNode - A texture node which size should be retrieved.
  7933. * @param {?Node<int>} [levelNode=null] - A level node which defines the requested mip.
  7934. */
  7935. constructor( textureNode, levelNode = null ) {
  7936. super( 'uvec2' );
  7937. /**
  7938. * This flag can be used for type testing.
  7939. *
  7940. * @type {boolean}
  7941. * @readonly
  7942. * @default true
  7943. */
  7944. this.isTextureSizeNode = true;
  7945. /**
  7946. * A texture node which size should be retrieved.
  7947. *
  7948. * @type {TextureNode}
  7949. */
  7950. this.textureNode = textureNode;
  7951. /**
  7952. * A level node which defines the requested mip.
  7953. *
  7954. * @type {Node<int>}
  7955. * @default null
  7956. */
  7957. this.levelNode = levelNode;
  7958. }
  7959. generate( builder, output ) {
  7960. const textureProperty = this.textureNode.build( builder, 'property' );
  7961. const level = this.levelNode === null ? '0' : this.levelNode.build( builder, 'int' );
  7962. return builder.format( `${ builder.getMethod( 'textureDimensions' ) }( ${ textureProperty }, ${ level } )`, this.getNodeType( builder ), output );
  7963. }
  7964. }
  7965. /**
  7966. * TSL function for creating a texture size node.
  7967. *
  7968. * @tsl
  7969. * @function
  7970. * @param {TextureNode} textureNode - A texture node which size should be retrieved.
  7971. * @param {?Node<int>} [levelNode=null] - A level node which defines the requested mip.
  7972. * @returns {TextureSizeNode}
  7973. */
  7974. const textureSize = /*@__PURE__*/ nodeProxy( TextureSizeNode ).setParameterLength( 1, 2 );
  7975. /**
  7976. * A special type of uniform node that computes the
  7977. * maximum mipmap level for a given texture node.
  7978. *
  7979. * ```js
  7980. * const level = maxMipLevel( textureNode );
  7981. * ```
  7982. *
  7983. * @augments UniformNode
  7984. */
  7985. class MaxMipLevelNode extends UniformNode {
  7986. static get type() {
  7987. return 'MaxMipLevelNode';
  7988. }
  7989. /**
  7990. * Constructs a new max mip level node.
  7991. *
  7992. * @param {TextureNode} textureNode - The texture node to compute the max mip level for.
  7993. */
  7994. constructor( textureNode ) {
  7995. super( 0 );
  7996. /**
  7997. * The texture node to compute the max mip level for.
  7998. *
  7999. * @private
  8000. * @type {TextureNode}
  8001. */
  8002. this._textureNode = textureNode;
  8003. /**
  8004. * The `updateType` is set to `NodeUpdateType.FRAME` since the node updates
  8005. * the texture once per frame in its {@link MaxMipLevelNode#update} method.
  8006. *
  8007. * @type {string}
  8008. * @default 'frame'
  8009. */
  8010. this.updateType = NodeUpdateType.FRAME;
  8011. }
  8012. /**
  8013. * The texture node to compute the max mip level for.
  8014. *
  8015. * @readonly
  8016. * @type {TextureNode}
  8017. */
  8018. get textureNode() {
  8019. return this._textureNode;
  8020. }
  8021. /**
  8022. * The texture.
  8023. *
  8024. * @readonly
  8025. * @type {Texture}
  8026. */
  8027. get texture() {
  8028. return this._textureNode.value;
  8029. }
  8030. update() {
  8031. const texture = this.texture;
  8032. const images = texture.images;
  8033. const image = ( images && images.length > 0 ) ? ( ( images[ 0 ] && images[ 0 ].image ) || images[ 0 ] ) : texture.image;
  8034. if ( image && image.width !== undefined ) {
  8035. const { width, height } = image;
  8036. this.value = Math.log2( Math.max( width, height ) );
  8037. }
  8038. }
  8039. }
  8040. /**
  8041. * TSL function for creating a max mip level node.
  8042. *
  8043. * @tsl
  8044. * @function
  8045. * @param {TextureNode} textureNode - The texture node to compute the max mip level for.
  8046. * @returns {MaxMipLevelNode}
  8047. */
  8048. const maxMipLevel = /*@__PURE__*/ nodeProxy( MaxMipLevelNode ).setParameterLength( 1 );
  8049. const EmptyTexture$1 = /*@__PURE__*/ new Texture();
  8050. /**
  8051. * This type of uniform node represents a 2D texture.
  8052. *
  8053. * @augments UniformNode
  8054. */
  8055. class TextureNode extends UniformNode {
  8056. static get type() {
  8057. return 'TextureNode';
  8058. }
  8059. /**
  8060. * Constructs a new texture node.
  8061. *
  8062. * @param {Texture} [value=EmptyTexture] - The texture.
  8063. * @param {?Node<vec2|vec3>} [uvNode=null] - The uv node.
  8064. * @param {?Node<int>} [levelNode=null] - The level node.
  8065. * @param {?Node<float>} [biasNode=null] - The bias node.
  8066. */
  8067. constructor( value = EmptyTexture$1, uvNode = null, levelNode = null, biasNode = null ) {
  8068. super( value );
  8069. /**
  8070. * This flag can be used for type testing.
  8071. *
  8072. * @type {boolean}
  8073. * @readonly
  8074. * @default true
  8075. */
  8076. this.isTextureNode = true;
  8077. /**
  8078. * Represents the texture coordinates.
  8079. *
  8080. * @type {?Node<vec2|vec3>}
  8081. * @default null
  8082. */
  8083. this.uvNode = uvNode;
  8084. /**
  8085. * Represents the mip level that should be selected.
  8086. *
  8087. * @type {?Node<int>}
  8088. * @default null
  8089. */
  8090. this.levelNode = levelNode;
  8091. /**
  8092. * Represents the bias to be applied during level-of-detail computation.
  8093. *
  8094. * @type {?Node<float>}
  8095. * @default null
  8096. */
  8097. this.biasNode = biasNode;
  8098. /**
  8099. * Represents a reference value a texture sample is compared to.
  8100. *
  8101. * @type {?Node<float>}
  8102. * @default null
  8103. */
  8104. this.compareNode = null;
  8105. /**
  8106. * When using texture arrays, the depth node defines the layer to select.
  8107. *
  8108. * @type {?Node<int>}
  8109. * @default null
  8110. */
  8111. this.depthNode = null;
  8112. /**
  8113. * When defined, a texture is sampled using explicit gradients.
  8114. *
  8115. * @type {?Array<Node<vec2>>}
  8116. * @default null
  8117. */
  8118. this.gradNode = null;
  8119. /**
  8120. * Represents the optional texel offset applied to the unnormalized texture
  8121. * coordinate before sampling the texture.
  8122. *
  8123. * @type {?Node<ivec2|ivec3>}
  8124. * @default null
  8125. */
  8126. this.offsetNode = null;
  8127. /**
  8128. * Whether texture values should be sampled or fetched.
  8129. *
  8130. * @type {boolean}
  8131. * @default true
  8132. */
  8133. this.sampler = true;
  8134. /**
  8135. * Whether the uv transformation matrix should be
  8136. * automatically updated or not. Use `setUpdateMatrix()`
  8137. * if you want to change the value of the property.
  8138. *
  8139. * @type {boolean}
  8140. * @default false
  8141. */
  8142. this.updateMatrix = false;
  8143. /**
  8144. * By default the `update()` method is not executed. Depending on
  8145. * whether a uv transformation matrix and/or flipY is applied, `update()`
  8146. * is executed per object.
  8147. *
  8148. * @type {string}
  8149. * @default 'none'
  8150. */
  8151. this.updateType = NodeUpdateType.NONE;
  8152. /**
  8153. * The reference node.
  8154. *
  8155. * @type {?Node}
  8156. * @default null
  8157. */
  8158. this.referenceNode = null;
  8159. /**
  8160. * The texture value is stored in a private property.
  8161. *
  8162. * @private
  8163. * @type {Texture}
  8164. */
  8165. this._value = value;
  8166. /**
  8167. * The uniform node that represents the uv transformation matrix.
  8168. *
  8169. * @private
  8170. * @type {?UniformNode<mat3>}
  8171. * @default null
  8172. */
  8173. this._matrixUniform = null;
  8174. /**
  8175. * The uniform node that represents the y-flip. Only required for WebGL.
  8176. *
  8177. * @private
  8178. * @type {?UniformNode<bool>}
  8179. * @default null
  8180. */
  8181. this._flipYUniform = null;
  8182. this.setUpdateMatrix( uvNode === null );
  8183. }
  8184. set value( value ) {
  8185. if ( this.referenceNode ) {
  8186. this.referenceNode.value = value;
  8187. } else {
  8188. this._value = value;
  8189. }
  8190. }
  8191. /**
  8192. * The texture value.
  8193. *
  8194. * @type {Texture}
  8195. */
  8196. get value() {
  8197. return this.referenceNode ? this.referenceNode.value : this._value;
  8198. }
  8199. /**
  8200. * Overwritten since the uniform hash is defined by the texture's UUID.
  8201. *
  8202. * @param {NodeBuilder} builder - The current node builder.
  8203. * @return {string} The uniform hash.
  8204. */
  8205. getUniformHash( /*builder*/ ) {
  8206. return this.value.uuid;
  8207. }
  8208. /**
  8209. * Overwritten since the node type is inferred from the texture type.
  8210. *
  8211. * @param {NodeBuilder} builder - The current node builder.
  8212. * @return {string} The node type.
  8213. */
  8214. getNodeType( /*builder*/ ) {
  8215. if ( this.value.isDepthTexture === true ) return 'float';
  8216. if ( this.value.type === UnsignedIntType ) {
  8217. return 'uvec4';
  8218. } else if ( this.value.type === IntType ) {
  8219. return 'ivec4';
  8220. }
  8221. return 'vec4';
  8222. }
  8223. /**
  8224. * Overwrites the default implementation to return a fixed value `'texture'`.
  8225. *
  8226. * @param {NodeBuilder} builder - The current node builder.
  8227. * @return {string} The input type.
  8228. */
  8229. getInputType( /*builder*/ ) {
  8230. return 'texture';
  8231. }
  8232. /**
  8233. * Returns a default uvs based on the current texture's channel.
  8234. *
  8235. * @return {AttributeNode<vec2>} The default uvs.
  8236. */
  8237. getDefaultUV() {
  8238. return uv$1( this.value.channel );
  8239. }
  8240. /**
  8241. * Overwritten to always return the texture reference of the node.
  8242. *
  8243. * @param {any} state - This method can be invocated in different contexts so `state` can refer to any object type.
  8244. * @return {Texture} The texture reference.
  8245. */
  8246. updateReference( /*state*/ ) {
  8247. return this.value;
  8248. }
  8249. /**
  8250. * Transforms the given uv node with the texture transformation matrix.
  8251. *
  8252. * @param {Node} uvNode - The uv node to transform.
  8253. * @return {Node} The transformed uv node.
  8254. */
  8255. getTransformedUV( uvNode ) {
  8256. if ( this._matrixUniform === null ) this._matrixUniform = uniform( this.value.matrix );
  8257. return this._matrixUniform.mul( vec3( uvNode, 1 ) ).xy;
  8258. }
  8259. /**
  8260. * Defines whether the uv transformation matrix should automatically be updated or not.
  8261. *
  8262. * @param {boolean} value - The update toggle.
  8263. * @return {TextureNode} A reference to this node.
  8264. */
  8265. setUpdateMatrix( value ) {
  8266. this.updateMatrix = value;
  8267. return this;
  8268. }
  8269. /**
  8270. * Setups the uv node. Depending on the backend as well as texture's image and type, it might be necessary
  8271. * to modify the uv node for correct sampling.
  8272. *
  8273. * @param {NodeBuilder} builder - The current node builder.
  8274. * @param {Node} uvNode - The uv node to setup.
  8275. * @return {Node} The updated uv node.
  8276. */
  8277. setupUV( builder, uvNode ) {
  8278. if ( builder.isFlipY() ) {
  8279. if ( this._flipYUniform === null ) this._flipYUniform = uniform( false );
  8280. uvNode = uvNode.toVar();
  8281. if ( this.sampler ) {
  8282. uvNode = this._flipYUniform.select( uvNode.flipY(), uvNode );
  8283. } else {
  8284. uvNode = this._flipYUniform.select( uvNode.setY( int( textureSize( this, this.levelNode ).y ).sub( uvNode.y ).sub( 1 ) ), uvNode );
  8285. }
  8286. }
  8287. return uvNode;
  8288. }
  8289. /**
  8290. * Setups texture node by preparing the internal nodes for code generation.
  8291. *
  8292. * @param {NodeBuilder} builder - The current node builder.
  8293. */
  8294. setup( builder ) {
  8295. const properties = builder.getNodeProperties( this );
  8296. properties.referenceNode = this.referenceNode;
  8297. //
  8298. const texture = this.value;
  8299. if ( ! texture || texture.isTexture !== true ) {
  8300. throw new Error( 'THREE.TSL: `texture( value )` function expects a valid instance of THREE.Texture().' );
  8301. }
  8302. //
  8303. const uvNode = Fn( () => {
  8304. let uvNode = this.uvNode;
  8305. if ( ( uvNode === null || builder.context.forceUVContext === true ) && builder.context.getUV ) {
  8306. uvNode = builder.context.getUV( this, builder );
  8307. }
  8308. if ( ! uvNode ) uvNode = this.getDefaultUV();
  8309. if ( this.updateMatrix === true ) {
  8310. uvNode = this.getTransformedUV( uvNode );
  8311. }
  8312. uvNode = this.setupUV( builder, uvNode );
  8313. //
  8314. this.updateType = ( this._matrixUniform !== null || this._flipYUniform !== null ) ? NodeUpdateType.OBJECT : NodeUpdateType.NONE;
  8315. //
  8316. return uvNode;
  8317. } )();
  8318. //
  8319. let levelNode = this.levelNode;
  8320. if ( levelNode === null && builder.context.getTextureLevel ) {
  8321. levelNode = builder.context.getTextureLevel( this );
  8322. }
  8323. //
  8324. properties.uvNode = uvNode;
  8325. properties.levelNode = levelNode;
  8326. properties.biasNode = this.biasNode;
  8327. properties.compareNode = this.compareNode;
  8328. properties.gradNode = this.gradNode;
  8329. properties.depthNode = this.depthNode;
  8330. properties.offsetNode = this.offsetNode;
  8331. }
  8332. /**
  8333. * Generates the uv code snippet.
  8334. *
  8335. * @param {NodeBuilder} builder - The current node builder.
  8336. * @param {Node} uvNode - The uv node to generate code for.
  8337. * @return {string} The generated code snippet.
  8338. */
  8339. generateUV( builder, uvNode ) {
  8340. return uvNode.build( builder, this.sampler === true ? 'vec2' : 'ivec2' );
  8341. }
  8342. /**
  8343. * Generates the offset code snippet.
  8344. *
  8345. * @param {NodeBuilder} builder - The current node builder.
  8346. * @param {Node} offsetNode - The offset node to generate code for.
  8347. * @return {string} The generated code snippet.
  8348. */
  8349. generateOffset( builder, offsetNode ) {
  8350. return offsetNode.build( builder, 'ivec2' );
  8351. }
  8352. /**
  8353. * Generates the snippet for the texture sampling.
  8354. *
  8355. * @param {NodeBuilder} builder - The current node builder.
  8356. * @param {string} textureProperty - The texture property.
  8357. * @param {string} uvSnippet - The uv snippet.
  8358. * @param {?string} levelSnippet - The level snippet.
  8359. * @param {?string} biasSnippet - The bias snippet.
  8360. * @param {?string} depthSnippet - The depth snippet.
  8361. * @param {?string} compareSnippet - The compare snippet.
  8362. * @param {?Array<string>} gradSnippet - The grad snippet.
  8363. * @param {?string} offsetSnippet - The offset snippet.
  8364. * @return {string} The generated code snippet.
  8365. */
  8366. generateSnippet( builder, textureProperty, uvSnippet, levelSnippet, biasSnippet, depthSnippet, compareSnippet, gradSnippet, offsetSnippet ) {
  8367. const texture = this.value;
  8368. let snippet;
  8369. if ( biasSnippet ) {
  8370. snippet = builder.generateTextureBias( texture, textureProperty, uvSnippet, biasSnippet, depthSnippet, offsetSnippet );
  8371. } else if ( gradSnippet ) {
  8372. snippet = builder.generateTextureGrad( texture, textureProperty, uvSnippet, gradSnippet, depthSnippet, offsetSnippet );
  8373. } else if ( compareSnippet ) {
  8374. snippet = builder.generateTextureCompare( texture, textureProperty, uvSnippet, compareSnippet, depthSnippet, offsetSnippet );
  8375. } else if ( this.sampler === false ) {
  8376. snippet = builder.generateTextureLoad( texture, textureProperty, uvSnippet, levelSnippet, depthSnippet, offsetSnippet );
  8377. } else if ( levelSnippet ) {
  8378. snippet = builder.generateTextureLevel( texture, textureProperty, uvSnippet, levelSnippet, depthSnippet, offsetSnippet );
  8379. } else {
  8380. snippet = builder.generateTexture( texture, textureProperty, uvSnippet, depthSnippet, offsetSnippet );
  8381. }
  8382. return snippet;
  8383. }
  8384. /**
  8385. * Generates the code snippet of the texture node.
  8386. *
  8387. * @param {NodeBuilder} builder - The current node builder.
  8388. * @param {string} output - The current output.
  8389. * @return {string} The generated code snippet.
  8390. */
  8391. generate( builder, output ) {
  8392. const texture = this.value;
  8393. const properties = builder.getNodeProperties( this );
  8394. const textureProperty = super.generate( builder, 'property' );
  8395. if ( /^sampler/.test( output ) ) {
  8396. return textureProperty + '_sampler';
  8397. } else if ( builder.isReference( output ) ) {
  8398. return textureProperty;
  8399. } else {
  8400. const nodeData = builder.getDataFromNode( this );
  8401. let propertyName = nodeData.propertyName;
  8402. if ( propertyName === undefined ) {
  8403. const { uvNode, levelNode, biasNode, compareNode, depthNode, gradNode, offsetNode } = properties;
  8404. const uvSnippet = this.generateUV( builder, uvNode );
  8405. const levelSnippet = levelNode ? levelNode.build( builder, 'float' ) : null;
  8406. const biasSnippet = biasNode ? biasNode.build( builder, 'float' ) : null;
  8407. const depthSnippet = depthNode ? depthNode.build( builder, 'int' ) : null;
  8408. const compareSnippet = compareNode ? compareNode.build( builder, 'float' ) : null;
  8409. const gradSnippet = gradNode ? [ gradNode[ 0 ].build( builder, 'vec2' ), gradNode[ 1 ].build( builder, 'vec2' ) ] : null;
  8410. const offsetSnippet = offsetNode ? this.generateOffset( builder, offsetNode ) : null;
  8411. const nodeVar = builder.getVarFromNode( this );
  8412. propertyName = builder.getPropertyName( nodeVar );
  8413. const snippet = this.generateSnippet( builder, textureProperty, uvSnippet, levelSnippet, biasSnippet, depthSnippet, compareSnippet, gradSnippet, offsetSnippet );
  8414. builder.addLineFlowCode( `${propertyName} = ${snippet}`, this );
  8415. nodeData.snippet = snippet;
  8416. nodeData.propertyName = propertyName;
  8417. }
  8418. let snippet = propertyName;
  8419. const nodeType = this.getNodeType( builder );
  8420. if ( builder.needsToWorkingColorSpace( texture ) ) {
  8421. snippet = colorSpaceToWorking( expression( snippet, nodeType ), texture.colorSpace ).setup( builder ).build( builder, nodeType );
  8422. }
  8423. return builder.format( snippet, nodeType, output );
  8424. }
  8425. }
  8426. /**
  8427. * Sets the sampler value.
  8428. *
  8429. * @param {boolean} value - The sampler value to set.
  8430. * @return {TextureNode} A reference to this texture node.
  8431. */
  8432. setSampler( value ) {
  8433. this.sampler = value;
  8434. return this;
  8435. }
  8436. /**
  8437. * Returns the sampler value.
  8438. *
  8439. * @return {boolean} The sampler value.
  8440. */
  8441. getSampler() {
  8442. return this.sampler;
  8443. }
  8444. // @TODO: Move to TSL
  8445. /**
  8446. * @function
  8447. * @deprecated since r172. Use {@link TextureNode#sample} instead.
  8448. *
  8449. * @param {Node} uvNode - The uv node.
  8450. * @return {TextureNode} A texture node representing the texture sample.
  8451. */
  8452. uv( uvNode ) { // @deprecated, r172
  8453. warn( 'TextureNode: .uv() has been renamed. Use .sample() instead.' );
  8454. return this.sample( uvNode );
  8455. }
  8456. /**
  8457. * Samples the texture with the given uv node.
  8458. *
  8459. * @param {Node} uvNode - The uv node.
  8460. * @return {TextureNode} A texture node representing the texture sample.
  8461. */
  8462. sample( uvNode ) {
  8463. const textureNode = this.clone();
  8464. textureNode.uvNode = nodeObject( uvNode );
  8465. textureNode.referenceNode = this.getBase();
  8466. return nodeObject( textureNode );
  8467. }
  8468. /**
  8469. * TSL function for creating a texture node that fetches/loads texels without interpolation.
  8470. *
  8471. * @param {Node<uvec2>} uvNode - The uv node.
  8472. * @returns {TextureNode} A texture node representing the texture load.
  8473. */
  8474. load( uvNode ) {
  8475. return this.sample( uvNode ).setSampler( false );
  8476. }
  8477. /**
  8478. * Samples a blurred version of the texture by defining an internal bias.
  8479. *
  8480. * @param {Node<float>} amountNode - How blurred the texture should be.
  8481. * @return {TextureNode} A texture node representing the texture sample.
  8482. */
  8483. blur( amountNode ) {
  8484. const textureNode = this.clone();
  8485. textureNode.biasNode = nodeObject( amountNode ).mul( maxMipLevel( textureNode ) );
  8486. textureNode.referenceNode = this.getBase();
  8487. const map = textureNode.value;
  8488. if ( textureNode.generateMipmaps === false && ( map && map.generateMipmaps === false || map.minFilter === NearestFilter || map.magFilter === NearestFilter ) ) {
  8489. warn( 'TSL: texture().blur() requires mipmaps and sampling. Use .generateMipmaps=true and .minFilter/.magFilter=THREE.LinearFilter in the Texture.' );
  8490. textureNode.biasNode = null;
  8491. }
  8492. return nodeObject( textureNode );
  8493. }
  8494. /**
  8495. * Samples a specific mip of the texture.
  8496. *
  8497. * @param {Node<int>} levelNode - The mip level to sample.
  8498. * @return {TextureNode} A texture node representing the texture sample.
  8499. */
  8500. level( levelNode ) {
  8501. const textureNode = this.clone();
  8502. textureNode.levelNode = nodeObject( levelNode );
  8503. textureNode.referenceNode = this.getBase();
  8504. return nodeObject( textureNode );
  8505. }
  8506. /**
  8507. * Returns the texture size of the requested level.
  8508. *
  8509. * @param {Node<int>} levelNode - The level to compute the size for.
  8510. * @return {TextureSizeNode} The texture size.
  8511. */
  8512. size( levelNode ) {
  8513. return textureSize( this, levelNode );
  8514. }
  8515. /**
  8516. * Samples the texture with the given bias.
  8517. *
  8518. * @param {Node<float>} biasNode - The bias node.
  8519. * @return {TextureNode} A texture node representing the texture sample.
  8520. */
  8521. bias( biasNode ) {
  8522. const textureNode = this.clone();
  8523. textureNode.biasNode = nodeObject( biasNode );
  8524. textureNode.referenceNode = this.getBase();
  8525. return nodeObject( textureNode );
  8526. }
  8527. /**
  8528. * Returns the base texture of this node.
  8529. * @return {TextureNode} The base texture node.
  8530. */
  8531. getBase() {
  8532. return this.referenceNode ? this.referenceNode.getBase() : this;
  8533. }
  8534. /**
  8535. * Samples the texture by executing a compare operation.
  8536. *
  8537. * @param {Node<float>} compareNode - The node that defines the compare value.
  8538. * @return {TextureNode} A texture node representing the texture sample.
  8539. */
  8540. compare( compareNode ) {
  8541. const textureNode = this.clone();
  8542. textureNode.compareNode = nodeObject( compareNode );
  8543. textureNode.referenceNode = this.getBase();
  8544. return nodeObject( textureNode );
  8545. }
  8546. /**
  8547. * Samples the texture using an explicit gradient.
  8548. *
  8549. * @param {Node<vec2>} gradNodeX - The gradX node.
  8550. * @param {Node<vec2>} gradNodeY - The gradY node.
  8551. * @return {TextureNode} A texture node representing the texture sample.
  8552. */
  8553. grad( gradNodeX, gradNodeY ) {
  8554. const textureNode = this.clone();
  8555. textureNode.gradNode = [ nodeObject( gradNodeX ), nodeObject( gradNodeY ) ];
  8556. textureNode.referenceNode = this.getBase();
  8557. return nodeObject( textureNode );
  8558. }
  8559. /**
  8560. * Samples the texture by defining a depth node.
  8561. *
  8562. * @param {Node<int>} depthNode - The depth node.
  8563. * @return {TextureNode} A texture node representing the texture sample.
  8564. */
  8565. depth( depthNode ) {
  8566. const textureNode = this.clone();
  8567. textureNode.depthNode = nodeObject( depthNode );
  8568. textureNode.referenceNode = this.getBase();
  8569. return nodeObject( textureNode );
  8570. }
  8571. /**
  8572. * Samples the texture by defining an offset node.
  8573. *
  8574. * @param {Node<ivec2>} offsetNode - The offset node.
  8575. * @return {TextureNode} A texture node representing the texture sample.
  8576. */
  8577. offset( offsetNode ) {
  8578. const textureNode = this.clone();
  8579. textureNode.offsetNode = nodeObject( offsetNode );
  8580. textureNode.referenceNode = this.getBase();
  8581. return nodeObject( textureNode );
  8582. }
  8583. // --
  8584. serialize( data ) {
  8585. super.serialize( data );
  8586. data.value = this.value.toJSON( data.meta ).uuid;
  8587. data.sampler = this.sampler;
  8588. data.updateMatrix = this.updateMatrix;
  8589. data.updateType = this.updateType;
  8590. }
  8591. deserialize( data ) {
  8592. super.deserialize( data );
  8593. this.value = data.meta.textures[ data.value ];
  8594. this.sampler = data.sampler;
  8595. this.updateMatrix = data.updateMatrix;
  8596. this.updateType = data.updateType;
  8597. }
  8598. /**
  8599. * The update is used to implement the update of the uv transformation matrix.
  8600. */
  8601. update() {
  8602. const texture = this.value;
  8603. const matrixUniform = this._matrixUniform;
  8604. if ( matrixUniform !== null ) matrixUniform.value = texture.matrix;
  8605. if ( texture.matrixAutoUpdate === true ) {
  8606. texture.updateMatrix();
  8607. }
  8608. //
  8609. const flipYUniform = this._flipYUniform;
  8610. if ( flipYUniform !== null ) {
  8611. flipYUniform.value = ( ( texture.image instanceof ImageBitmap && texture.flipY === true ) || texture.isRenderTargetTexture === true || texture.isFramebufferTexture === true || texture.isDepthTexture === true );
  8612. }
  8613. }
  8614. /**
  8615. * Clones the texture node.
  8616. *
  8617. * @return {TextureNode} The cloned texture node.
  8618. */
  8619. clone() {
  8620. const newNode = new this.constructor( this.value, this.uvNode, this.levelNode, this.biasNode );
  8621. newNode.sampler = this.sampler;
  8622. newNode.depthNode = this.depthNode;
  8623. newNode.compareNode = this.compareNode;
  8624. newNode.gradNode = this.gradNode;
  8625. newNode.offsetNode = this.offsetNode;
  8626. return newNode;
  8627. }
  8628. }
  8629. /**
  8630. * TSL function for creating a texture node.
  8631. *
  8632. * @tsl
  8633. * @function
  8634. * @param {?Texture} value - The texture.
  8635. * @param {?Node<vec2|vec3>} [uvNode=null] - The uv node.
  8636. * @param {?Node<int>} [levelNode=null] - The level node.
  8637. * @param {?Node<float>} [biasNode=null] - The bias node.
  8638. * @returns {TextureNode}
  8639. */
  8640. const textureBase = /*@__PURE__*/ nodeProxy( TextureNode ).setParameterLength( 1, 4 ).setName( 'texture' );
  8641. /**
  8642. * TSL function for creating a texture node or sample a texture node already existing.
  8643. *
  8644. * @tsl
  8645. * @function
  8646. * @param {?(Texture|TextureNode)} [value=EmptyTexture] - The texture.
  8647. * @param {?Node<vec2|vec3>} [uvNode=null] - The uv node.
  8648. * @param {?Node<int>} [levelNode=null] - The level node.
  8649. * @param {?Node<float>} [biasNode=null] - The bias node.
  8650. * @returns {TextureNode}
  8651. */
  8652. const texture = ( value = EmptyTexture$1, uvNode = null, levelNode = null, biasNode = null ) => {
  8653. let textureNode;
  8654. if ( value && value.isTextureNode === true ) {
  8655. textureNode = nodeObject( value.clone() );
  8656. textureNode.referenceNode = value.getBase(); // Ensure the reference is set to the original node
  8657. if ( uvNode !== null ) textureNode.uvNode = nodeObject( uvNode );
  8658. if ( levelNode !== null ) textureNode.levelNode = nodeObject( levelNode );
  8659. if ( biasNode !== null ) textureNode.biasNode = nodeObject( biasNode );
  8660. } else {
  8661. textureNode = textureBase( value, uvNode, levelNode, biasNode );
  8662. }
  8663. return textureNode;
  8664. };
  8665. /**
  8666. * TSL function for creating a uniform texture node.
  8667. *
  8668. * @tsl
  8669. * @function
  8670. * @param {?Texture} value - The texture.
  8671. * @returns {TextureNode}
  8672. */
  8673. const uniformTexture = ( value = EmptyTexture$1 ) => texture( value );
  8674. /**
  8675. * TSL function for creating a texture node that fetches/loads texels without interpolation.
  8676. *
  8677. * @tsl
  8678. * @function
  8679. * @param {?(Texture|TextureNode)} [value=EmptyTexture] - The texture.
  8680. * @param {?Node<vec2|vec3>} [uvNode=null] - The uv node.
  8681. * @param {?Node<int>} [levelNode=null] - The level node.
  8682. * @param {?Node<float>} [biasNode=null] - The bias node.
  8683. * @returns {TextureNode}
  8684. */
  8685. const textureLoad = ( ...params ) => texture( ...params ).setSampler( false );
  8686. const textureLevel = ( value, uv, level ) => texture( value, uv ).level( level );
  8687. /**
  8688. * Converts a texture or texture node to a sampler.
  8689. *
  8690. * @tsl
  8691. * @function
  8692. * @param {TextureNode|Texture} value - The texture or texture node to convert.
  8693. * @returns {Node}
  8694. */
  8695. const sampler = ( value ) => ( value.isNode === true ? value : texture( value ) ).convert( 'sampler' );
  8696. /**
  8697. * Converts a texture or texture node to a sampler comparison.
  8698. *
  8699. * @tsl
  8700. * @function
  8701. * @param {TextureNode|Texture} value - The texture or texture node to convert.
  8702. * @returns {Node}
  8703. */
  8704. const samplerComparison = ( value ) => ( value.isNode === true ? value : texture( value ) ).convert( 'samplerComparison' );
  8705. /**
  8706. * A special type of uniform node which represents array-like data
  8707. * as uniform buffers. The access usually happens via `element()`
  8708. * which returns an instance of {@link ArrayElementNode}. For example:
  8709. *
  8710. * ```js
  8711. * const bufferNode = buffer( array, 'mat4', count );
  8712. * const matrixNode = bufferNode.element( index ); // access a matrix from the buffer
  8713. * ```
  8714. * In general, it is recommended to use the more managed {@link UniformArrayNode}
  8715. * since it handles more input types and automatically cares about buffer paddings.
  8716. *
  8717. * @augments UniformNode
  8718. */
  8719. class BufferNode extends UniformNode {
  8720. static get type() {
  8721. return 'BufferNode';
  8722. }
  8723. /**
  8724. * Constructs a new buffer node.
  8725. *
  8726. * @param {Array<number>} value - Array-like buffer data.
  8727. * @param {string} bufferType - The data type of the buffer.
  8728. * @param {number} [bufferCount=0] - The count of buffer elements.
  8729. */
  8730. constructor( value, bufferType, bufferCount = 0 ) {
  8731. super( value, bufferType );
  8732. /**
  8733. * This flag can be used for type testing.
  8734. *
  8735. * @type {boolean}
  8736. * @readonly
  8737. * @default true
  8738. */
  8739. this.isBufferNode = true;
  8740. /**
  8741. * The data type of the buffer.
  8742. *
  8743. * @type {string}
  8744. */
  8745. this.bufferType = bufferType;
  8746. /**
  8747. * The uniform node that holds the value of the reference node.
  8748. *
  8749. * @type {number}
  8750. * @default 0
  8751. */
  8752. this.bufferCount = bufferCount;
  8753. }
  8754. /**
  8755. * The data type of the buffer elements.
  8756. *
  8757. * @param {NodeBuilder} builder - The current node builder.
  8758. * @return {string} The element type.
  8759. */
  8760. getElementType( builder ) {
  8761. return this.getNodeType( builder );
  8762. }
  8763. /**
  8764. * Overwrites the default implementation to return a fixed value `'buffer'`.
  8765. *
  8766. * @param {NodeBuilder} builder - The current node builder.
  8767. * @return {string} The input type.
  8768. */
  8769. getInputType( /*builder*/ ) {
  8770. return 'buffer';
  8771. }
  8772. }
  8773. /**
  8774. * TSL function for creating a buffer node.
  8775. *
  8776. * @tsl
  8777. * @function
  8778. * @param {Array<number>} value - Array-like buffer data.
  8779. * @param {string} type - The data type of a buffer element.
  8780. * @param {number} count - The count of buffer elements.
  8781. * @returns {BufferNode}
  8782. */
  8783. const buffer = ( value, type, count ) => nodeObject( new BufferNode( value, type, count ) );
  8784. /**
  8785. * Represents the element access on uniform array nodes.
  8786. *
  8787. * @augments ArrayElementNode
  8788. */
  8789. class UniformArrayElementNode extends ArrayElementNode {
  8790. static get type() {
  8791. return 'UniformArrayElementNode';
  8792. }
  8793. /**
  8794. * Constructs a new buffer node.
  8795. *
  8796. * @param {UniformArrayNode} uniformArrayNode - The uniform array node to access.
  8797. * @param {IndexNode} indexNode - The index data that define the position of the accessed element in the array.
  8798. */
  8799. constructor( uniformArrayNode, indexNode ) {
  8800. super( uniformArrayNode, indexNode );
  8801. /**
  8802. * This flag can be used for type testing.
  8803. *
  8804. * @type {boolean}
  8805. * @readonly
  8806. * @default true
  8807. */
  8808. this.isArrayBufferElementNode = true;
  8809. }
  8810. generate( builder ) {
  8811. const snippet = super.generate( builder );
  8812. const type = this.getNodeType();
  8813. const paddedType = this.node.getPaddedType();
  8814. return builder.format( snippet, paddedType, type );
  8815. }
  8816. }
  8817. /**
  8818. * Similar to {@link BufferNode} this module represents array-like data as
  8819. * uniform buffers. Unlike {@link BufferNode}, it can handle more common
  8820. * data types in the array (e.g `three.js` primitives) and automatically
  8821. * manage buffer padding. It should be the first choice when working with
  8822. * uniforms buffers.
  8823. * ```js
  8824. * const tintColors = uniformArray( [
  8825. * new Color( 1, 0, 0 ),
  8826. * new Color( 0, 1, 0 ),
  8827. * new Color( 0, 0, 1 )
  8828. * ], 'color' );
  8829. *
  8830. * const redColor = tintColors.element( 0 );
  8831. *
  8832. * @augments BufferNode
  8833. */
  8834. class UniformArrayNode extends BufferNode {
  8835. static get type() {
  8836. return 'UniformArrayNode';
  8837. }
  8838. /**
  8839. * Constructs a new uniform array node.
  8840. *
  8841. * @param {Array<any>} value - Array holding the buffer data.
  8842. * @param {?string} [elementType=null] - The data type of a buffer element.
  8843. */
  8844. constructor( value, elementType = null ) {
  8845. super( null );
  8846. /**
  8847. * Array holding the buffer data. Unlike {@link BufferNode}, the array can
  8848. * hold number primitives as well as three.js objects like vectors, matrices
  8849. * or colors.
  8850. *
  8851. * @type {Array<any>}
  8852. */
  8853. this.array = value;
  8854. /**
  8855. * The data type of an array element.
  8856. *
  8857. * @type {string}
  8858. */
  8859. this.elementType = elementType === null ? getValueType( value[ 0 ] ) : elementType;
  8860. /**
  8861. * The padded type. Uniform buffers must conform to a certain buffer layout
  8862. * so a separate type is computed to ensure correct buffer size.
  8863. *
  8864. * @type {string}
  8865. */
  8866. this.paddedType = this.getPaddedType();
  8867. /**
  8868. * Overwritten since uniform array nodes are updated per render.
  8869. *
  8870. * @type {string}
  8871. * @default 'render'
  8872. */
  8873. this.updateType = NodeUpdateType.RENDER;
  8874. /**
  8875. * This flag can be used for type testing.
  8876. *
  8877. * @type {boolean}
  8878. * @readonly
  8879. * @default true
  8880. */
  8881. this.isArrayBufferNode = true;
  8882. }
  8883. /**
  8884. * This method is overwritten since the node type is inferred from the
  8885. * {@link UniformArrayNode#paddedType}.
  8886. *
  8887. * @param {NodeBuilder} builder - The current node builder.
  8888. * @return {string} The node type.
  8889. */
  8890. getNodeType( /*builder*/ ) {
  8891. return this.paddedType;
  8892. }
  8893. /**
  8894. * The data type of the array elements.
  8895. *
  8896. * @param {NodeBuilder} builder - The current node builder.
  8897. * @return {string} The element type.
  8898. */
  8899. getElementType() {
  8900. return this.elementType;
  8901. }
  8902. /**
  8903. * Returns the padded type based on the element type.
  8904. *
  8905. * @return {string} The padded type.
  8906. */
  8907. getPaddedType() {
  8908. const elementType = this.elementType;
  8909. let paddedType = 'vec4';
  8910. if ( elementType === 'mat2' ) {
  8911. paddedType = 'mat2';
  8912. } else if ( /mat/.test( elementType ) === true ) {
  8913. paddedType = 'mat4';
  8914. } else if ( elementType.charAt( 0 ) === 'i' ) {
  8915. paddedType = 'ivec4';
  8916. } else if ( elementType.charAt( 0 ) === 'u' ) {
  8917. paddedType = 'uvec4';
  8918. }
  8919. return paddedType;
  8920. }
  8921. /**
  8922. * The update makes sure to correctly transfer the data from the (complex) objects
  8923. * in the array to the internal, correctly padded value buffer.
  8924. *
  8925. * @param {NodeFrame} frame - A reference to the current node frame.
  8926. */
  8927. update( /*frame*/ ) {
  8928. const { array, value } = this;
  8929. const elementType = this.elementType;
  8930. if ( elementType === 'float' || elementType === 'int' || elementType === 'uint' ) {
  8931. for ( let i = 0; i < array.length; i ++ ) {
  8932. const index = i * 4;
  8933. value[ index ] = array[ i ];
  8934. }
  8935. } else if ( elementType === 'color' ) {
  8936. for ( let i = 0; i < array.length; i ++ ) {
  8937. const index = i * 4;
  8938. const vector = array[ i ];
  8939. value[ index ] = vector.r;
  8940. value[ index + 1 ] = vector.g;
  8941. value[ index + 2 ] = vector.b || 0;
  8942. //value[ index + 3 ] = vector.a || 0;
  8943. }
  8944. } else if ( elementType === 'mat2' ) {
  8945. for ( let i = 0; i < array.length; i ++ ) {
  8946. const index = i * 4;
  8947. const matrix = array[ i ];
  8948. value[ index ] = matrix.elements[ 0 ];
  8949. value[ index + 1 ] = matrix.elements[ 1 ];
  8950. value[ index + 2 ] = matrix.elements[ 2 ];
  8951. value[ index + 3 ] = matrix.elements[ 3 ];
  8952. }
  8953. } else if ( elementType === 'mat3' ) {
  8954. for ( let i = 0; i < array.length; i ++ ) {
  8955. const index = i * 16;
  8956. const matrix = array[ i ];
  8957. value[ index ] = matrix.elements[ 0 ];
  8958. value[ index + 1 ] = matrix.elements[ 1 ];
  8959. value[ index + 2 ] = matrix.elements[ 2 ];
  8960. value[ index + 4 ] = matrix.elements[ 3 ];
  8961. value[ index + 5 ] = matrix.elements[ 4 ];
  8962. value[ index + 6 ] = matrix.elements[ 5 ];
  8963. value[ index + 8 ] = matrix.elements[ 6 ];
  8964. value[ index + 9 ] = matrix.elements[ 7 ];
  8965. value[ index + 10 ] = matrix.elements[ 8 ];
  8966. value[ index + 15 ] = 1;
  8967. }
  8968. } else if ( elementType === 'mat4' ) {
  8969. for ( let i = 0; i < array.length; i ++ ) {
  8970. const index = i * 16;
  8971. const matrix = array[ i ];
  8972. for ( let i = 0; i < matrix.elements.length; i ++ ) {
  8973. value[ index + i ] = matrix.elements[ i ];
  8974. }
  8975. }
  8976. } else {
  8977. for ( let i = 0; i < array.length; i ++ ) {
  8978. const index = i * 4;
  8979. const vector = array[ i ];
  8980. value[ index ] = vector.x;
  8981. value[ index + 1 ] = vector.y;
  8982. value[ index + 2 ] = vector.z || 0;
  8983. value[ index + 3 ] = vector.w || 0;
  8984. }
  8985. }
  8986. }
  8987. /**
  8988. * Implement the value buffer creation based on the array data.
  8989. *
  8990. * @param {NodeBuilder} builder - A reference to the current node builder.
  8991. * @return {null}
  8992. */
  8993. setup( builder ) {
  8994. const length = this.array.length;
  8995. const elementType = this.elementType;
  8996. let arrayType = Float32Array;
  8997. const paddedType = this.paddedType;
  8998. const paddedElementLength = builder.getTypeLength( paddedType );
  8999. if ( elementType.charAt( 0 ) === 'i' ) arrayType = Int32Array;
  9000. if ( elementType.charAt( 0 ) === 'u' ) arrayType = Uint32Array;
  9001. this.value = new arrayType( length * paddedElementLength );
  9002. this.bufferCount = length;
  9003. this.bufferType = paddedType;
  9004. return super.setup( builder );
  9005. }
  9006. /**
  9007. * Overwrites the default `element()` method to provide element access
  9008. * based on {@link UniformArrayNode}.
  9009. *
  9010. * @param {IndexNode} indexNode - The index node.
  9011. * @return {UniformArrayElementNode}
  9012. */
  9013. element( indexNode ) {
  9014. return nodeObject( new UniformArrayElementNode( this, nodeObject( indexNode ) ) );
  9015. }
  9016. }
  9017. /**
  9018. * TSL function for creating an uniform array node.
  9019. *
  9020. * @tsl
  9021. * @function
  9022. * @param {Array<any>} values - Array-like data.
  9023. * @param {?string} [nodeType] - The data type of the array elements.
  9024. * @returns {UniformArrayNode}
  9025. */
  9026. const uniformArray = ( values, nodeType ) => nodeObject( new UniformArrayNode( values, nodeType ) );
  9027. /**
  9028. * The node allows to set values for built-in shader variables. That is
  9029. * required for features like hardware-accelerated vertex clipping.
  9030. *
  9031. * @augments Node
  9032. */
  9033. class BuiltinNode extends Node {
  9034. /**
  9035. * Constructs a new builtin node.
  9036. *
  9037. * @param {string} name - The name of the built-in shader variable.
  9038. */
  9039. constructor( name ) {
  9040. super( 'float' );
  9041. /**
  9042. * The name of the built-in shader variable.
  9043. *
  9044. * @type {string}
  9045. */
  9046. this.name = name;
  9047. /**
  9048. * This flag can be used for type testing.
  9049. *
  9050. * @type {boolean}
  9051. * @readonly
  9052. * @default true
  9053. */
  9054. this.isBuiltinNode = true;
  9055. }
  9056. /**
  9057. * Generates the code snippet of the builtin node.
  9058. *
  9059. * @param {NodeBuilder} builder - The current node builder.
  9060. * @return {string} The generated code snippet.
  9061. */
  9062. generate( /* builder */ ) {
  9063. return this.name;
  9064. }
  9065. }
  9066. /**
  9067. * TSL function for creating a builtin node.
  9068. *
  9069. * @tsl
  9070. * @function
  9071. * @param {string} name - The name of the built-in shader variable.
  9072. * @returns {BuiltinNode}
  9073. */
  9074. const builtin = nodeProxy( BuiltinNode ).setParameterLength( 1 );
  9075. let _screenSizeVec, _viewportVec;
  9076. /**
  9077. * This node provides a collection of screen related metrics.
  9078. * Depending on {@link ScreenNode#scope}, the nodes can represent
  9079. * resolution or viewport data as well as fragment or uv coordinates.
  9080. *
  9081. * @augments Node
  9082. */
  9083. class ScreenNode extends Node {
  9084. static get type() {
  9085. return 'ScreenNode';
  9086. }
  9087. /**
  9088. * Constructs a new screen node.
  9089. *
  9090. * @param {('coordinate'|'viewport'|'size'|'uv'|'dpr')} scope - The node's scope.
  9091. */
  9092. constructor( scope ) {
  9093. super();
  9094. /**
  9095. * The node represents different metric depending on which scope is selected.
  9096. *
  9097. * - `ScreenNode.COORDINATE`: Window-relative coordinates of the current fragment according to WebGPU standards.
  9098. * - `ScreenNode.VIEWPORT`: The current viewport defined as a four-dimensional vector.
  9099. * - `ScreenNode.SIZE`: The dimensions of the current bound framebuffer.
  9100. * - `ScreenNode.UV`: Normalized coordinates.
  9101. * - `ScreenNode.DPR`: Device pixel ratio.
  9102. *
  9103. * @type {('coordinate'|'viewport'|'size'|'uv'|'dpr')}
  9104. */
  9105. this.scope = scope;
  9106. /**
  9107. * This output node.
  9108. *
  9109. * @private
  9110. * @type {?Node}
  9111. * @default null
  9112. */
  9113. this._output = null;
  9114. /**
  9115. * This flag can be used for type testing.
  9116. *
  9117. * @type {boolean}
  9118. * @readonly
  9119. * @default true
  9120. */
  9121. this.isViewportNode = true;
  9122. }
  9123. /**
  9124. * This method is overwritten since the node type depends on the selected scope.
  9125. *
  9126. * @return {('float'|'vec2'|'vec4')} The node type.
  9127. */
  9128. getNodeType() {
  9129. if ( this.scope === ScreenNode.DPR ) return 'float';
  9130. if ( this.scope === ScreenNode.VIEWPORT ) return 'vec4';
  9131. else return 'vec2';
  9132. }
  9133. /**
  9134. * This method is overwritten since the node's update type depends on the selected scope.
  9135. *
  9136. * @return {NodeUpdateType} The update type.
  9137. */
  9138. getUpdateType() {
  9139. let updateType = NodeUpdateType.NONE;
  9140. if ( this.scope === ScreenNode.SIZE || this.scope === ScreenNode.VIEWPORT || this.scope === ScreenNode.DPR ) {
  9141. updateType = NodeUpdateType.RENDER;
  9142. }
  9143. this.updateType = updateType;
  9144. return updateType;
  9145. }
  9146. /**
  9147. * `ScreenNode` implements {@link Node#update} to retrieve viewport and size information
  9148. * from the current renderer.
  9149. *
  9150. * @param {NodeFrame} frame - A reference to the current node frame.
  9151. */
  9152. update( { renderer } ) {
  9153. const renderTarget = renderer.getRenderTarget();
  9154. if ( this.scope === ScreenNode.VIEWPORT ) {
  9155. if ( renderTarget !== null ) {
  9156. _viewportVec.copy( renderTarget.viewport );
  9157. } else {
  9158. renderer.getViewport( _viewportVec );
  9159. _viewportVec.multiplyScalar( renderer.getPixelRatio() );
  9160. }
  9161. } else if ( this.scope === ScreenNode.DPR ) {
  9162. this._output.value = renderer.getPixelRatio();
  9163. } else {
  9164. if ( renderTarget !== null ) {
  9165. _screenSizeVec.width = renderTarget.width;
  9166. _screenSizeVec.height = renderTarget.height;
  9167. } else {
  9168. renderer.getDrawingBufferSize( _screenSizeVec );
  9169. }
  9170. }
  9171. }
  9172. setup( /*builder*/ ) {
  9173. const scope = this.scope;
  9174. let output = null;
  9175. if ( scope === ScreenNode.SIZE ) {
  9176. output = uniform( _screenSizeVec || ( _screenSizeVec = new Vector2() ) );
  9177. } else if ( scope === ScreenNode.VIEWPORT ) {
  9178. output = uniform( _viewportVec || ( _viewportVec = new Vector4() ) );
  9179. } else if ( scope === ScreenNode.DPR ) {
  9180. output = uniform( 1 );
  9181. } else {
  9182. output = vec2( screenCoordinate.div( screenSize ) );
  9183. }
  9184. this._output = output;
  9185. return output;
  9186. }
  9187. generate( builder ) {
  9188. if ( this.scope === ScreenNode.COORDINATE ) {
  9189. let coord = builder.getFragCoord();
  9190. if ( builder.isFlipY() ) {
  9191. // follow webgpu standards
  9192. const size = builder.getNodeProperties( screenSize ).outputNode.build( builder );
  9193. coord = `${ builder.getType( 'vec2' ) }( ${ coord }.x, ${ size }.y - ${ coord }.y )`;
  9194. }
  9195. return coord;
  9196. }
  9197. return super.generate( builder );
  9198. }
  9199. }
  9200. ScreenNode.COORDINATE = 'coordinate';
  9201. ScreenNode.VIEWPORT = 'viewport';
  9202. ScreenNode.SIZE = 'size';
  9203. ScreenNode.UV = 'uv';
  9204. ScreenNode.DPR = 'dpr';
  9205. // Screen
  9206. /**
  9207. * TSL object that represents the current DPR.
  9208. *
  9209. * @tsl
  9210. * @type {ScreenNode<float>}
  9211. */
  9212. const screenDPR = /*@__PURE__*/ nodeImmutable( ScreenNode, ScreenNode.DPR );
  9213. /**
  9214. * TSL object that represents normalized screen coordinates, unitless in `[0, 1]`.
  9215. *
  9216. * @tsl
  9217. * @type {ScreenNode<vec2>}
  9218. */
  9219. const screenUV = /*@__PURE__*/ nodeImmutable( ScreenNode, ScreenNode.UV );
  9220. /**
  9221. * TSL object that represents the screen resolution in physical pixel units.
  9222. *
  9223. * @tsl
  9224. * @type {ScreenNode<vec2>}
  9225. */
  9226. const screenSize = /*@__PURE__*/ nodeImmutable( ScreenNode, ScreenNode.SIZE );
  9227. /**
  9228. * TSL object that represents the current `x`/`y` pixel position on the screen in physical pixel units.
  9229. *
  9230. * @tsl
  9231. * @type {ScreenNode<vec2>}
  9232. */
  9233. const screenCoordinate = /*@__PURE__*/ nodeImmutable( ScreenNode, ScreenNode.COORDINATE );
  9234. // Viewport
  9235. /**
  9236. * TSL object that represents the viewport rectangle as `x`, `y`, `width` and `height` in physical pixel units.
  9237. *
  9238. * @tsl
  9239. * @type {ScreenNode<vec4>}
  9240. */
  9241. const viewport = /*@__PURE__*/ nodeImmutable( ScreenNode, ScreenNode.VIEWPORT );
  9242. /**
  9243. * TSL object that represents the viewport resolution in physical pixel units.
  9244. *
  9245. * @tsl
  9246. * @type {ScreenNode<vec2>}
  9247. */
  9248. const viewportSize = viewport.zw;
  9249. /**
  9250. * TSL object that represents the current `x`/`y` pixel position on the viewport in physical pixel units.
  9251. *
  9252. * @tsl
  9253. * @type {ScreenNode<vec2>}
  9254. */
  9255. const viewportCoordinate = /*@__PURE__*/ screenCoordinate.sub( viewport.xy );
  9256. /**
  9257. * TSL object that represents normalized viewport coordinates, unitless in `[0, 1]`.
  9258. *
  9259. * @tsl
  9260. * @type {ScreenNode<vec2>}
  9261. */
  9262. const viewportUV = /*@__PURE__*/ viewportCoordinate.div( viewportSize );
  9263. // Deprecated
  9264. /**
  9265. * @deprecated since r169. Use {@link screenSize} instead.
  9266. */
  9267. const viewportResolution = /*@__PURE__*/ ( Fn( () => { // @deprecated, r169
  9268. warn( 'TSL: "viewportResolution" is deprecated. Use "screenSize" instead.' );
  9269. return screenSize;
  9270. }, 'vec2' ).once() )();
  9271. /**
  9272. * TSL object that represents the current `index` value of the camera if used ArrayCamera.
  9273. *
  9274. * @tsl
  9275. * @type {UniformNode<uint>}
  9276. */
  9277. const cameraIndex = /*@__PURE__*/ uniform( 0, 'uint' ).setName( 'u_cameraIndex' ).setGroup( sharedUniformGroup( 'cameraIndex' ) ).toVarying( 'v_cameraIndex' );
  9278. /**
  9279. * TSL object that represents the `near` value of the camera used for the current render.
  9280. *
  9281. * @tsl
  9282. * @type {UniformNode<float>}
  9283. */
  9284. const cameraNear = /*@__PURE__*/ uniform( 'float' ).setName( 'cameraNear' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.near );
  9285. /**
  9286. * TSL object that represents the `far` value of the camera used for the current render.
  9287. *
  9288. * @tsl
  9289. * @type {UniformNode<float>}
  9290. */
  9291. const cameraFar = /*@__PURE__*/ uniform( 'float' ).setName( 'cameraFar' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.far );
  9292. /**
  9293. * TSL object that represents the projection matrix of the camera used for the current render.
  9294. *
  9295. * @tsl
  9296. * @type {UniformNode<mat4>}
  9297. */
  9298. const cameraProjectionMatrix = /*@__PURE__*/ ( Fn( ( { camera } ) => {
  9299. let cameraProjectionMatrix;
  9300. if ( camera.isArrayCamera && camera.cameras.length > 0 ) {
  9301. const matrices = [];
  9302. for ( const subCamera of camera.cameras ) {
  9303. matrices.push( subCamera.projectionMatrix );
  9304. }
  9305. const cameraProjectionMatrices = uniformArray( matrices ).setGroup( renderGroup ).setName( 'cameraProjectionMatrices' );
  9306. cameraProjectionMatrix = cameraProjectionMatrices.element( camera.isMultiViewCamera ? builtin( 'gl_ViewID_OVR' ) : cameraIndex ).toConst( 'cameraProjectionMatrix' );
  9307. } else {
  9308. cameraProjectionMatrix = uniform( 'mat4' ).setName( 'cameraProjectionMatrix' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.projectionMatrix );
  9309. }
  9310. return cameraProjectionMatrix;
  9311. } ).once() )();
  9312. /**
  9313. * TSL object that represents the inverse projection matrix of the camera used for the current render.
  9314. *
  9315. * @tsl
  9316. * @type {UniformNode<mat4>}
  9317. */
  9318. const cameraProjectionMatrixInverse = /*@__PURE__*/ ( Fn( ( { camera } ) => {
  9319. let cameraProjectionMatrixInverse;
  9320. if ( camera.isArrayCamera && camera.cameras.length > 0 ) {
  9321. const matrices = [];
  9322. for ( const subCamera of camera.cameras ) {
  9323. matrices.push( subCamera.projectionMatrixInverse );
  9324. }
  9325. const cameraProjectionMatricesInverse = uniformArray( matrices ).setGroup( renderGroup ).setName( 'cameraProjectionMatricesInverse' );
  9326. cameraProjectionMatrixInverse = cameraProjectionMatricesInverse.element( camera.isMultiViewCamera ? builtin( 'gl_ViewID_OVR' ) : cameraIndex ).toConst( 'cameraProjectionMatrixInverse' );
  9327. } else {
  9328. cameraProjectionMatrixInverse = uniform( 'mat4' ).setName( 'cameraProjectionMatrixInverse' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.projectionMatrixInverse );
  9329. }
  9330. return cameraProjectionMatrixInverse;
  9331. } ).once() )();
  9332. /**
  9333. * TSL object that represents the view matrix of the camera used for the current render.
  9334. *
  9335. * @tsl
  9336. * @type {UniformNode<mat4>}
  9337. */
  9338. const cameraViewMatrix = /*@__PURE__*/ ( Fn( ( { camera } ) => {
  9339. let cameraViewMatrix;
  9340. if ( camera.isArrayCamera && camera.cameras.length > 0 ) {
  9341. const matrices = [];
  9342. for ( const subCamera of camera.cameras ) {
  9343. matrices.push( subCamera.matrixWorldInverse );
  9344. }
  9345. const cameraViewMatrices = uniformArray( matrices ).setGroup( renderGroup ).setName( 'cameraViewMatrices' );
  9346. cameraViewMatrix = cameraViewMatrices.element( camera.isMultiViewCamera ? builtin( 'gl_ViewID_OVR' ) : cameraIndex ).toConst( 'cameraViewMatrix' );
  9347. } else {
  9348. cameraViewMatrix = uniform( 'mat4' ).setName( 'cameraViewMatrix' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.matrixWorldInverse );
  9349. }
  9350. return cameraViewMatrix;
  9351. } ).once() )();
  9352. /**
  9353. * TSL object that represents the world matrix of the camera used for the current render.
  9354. *
  9355. * @tsl
  9356. * @type {UniformNode<mat4>}
  9357. */
  9358. const cameraWorldMatrix = /*@__PURE__*/ ( Fn( ( { camera } ) => {
  9359. let cameraWorldMatrix;
  9360. if ( camera.isArrayCamera && camera.cameras.length > 0 ) {
  9361. const matrices = [];
  9362. for ( const subCamera of camera.cameras ) {
  9363. matrices.push( subCamera.matrixWorld );
  9364. }
  9365. const cameraWorldMatrices = uniformArray( matrices ).setGroup( renderGroup ).setName( 'cameraWorldMatrices' );
  9366. cameraWorldMatrix = cameraWorldMatrices.element( camera.isMultiViewCamera ? builtin( 'gl_ViewID_OVR' ) : cameraIndex ).toConst( 'cameraWorldMatrix' );
  9367. } else {
  9368. cameraWorldMatrix = uniform( 'mat4' ).setName( 'cameraWorldMatrix' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.matrixWorld );
  9369. }
  9370. return cameraWorldMatrix;
  9371. } ).once() )();
  9372. /**
  9373. * TSL object that represents the normal matrix of the camera used for the current render.
  9374. *
  9375. * @tsl
  9376. * @type {UniformNode<mat3>}
  9377. */
  9378. const cameraNormalMatrix = /*@__PURE__*/ ( Fn( ( { camera } ) => {
  9379. let cameraNormalMatrix;
  9380. if ( camera.isArrayCamera && camera.cameras.length > 0 ) {
  9381. const matrices = [];
  9382. for ( const subCamera of camera.cameras ) {
  9383. matrices.push( subCamera.normalMatrix );
  9384. }
  9385. const cameraNormalMatrices = uniformArray( matrices ).setGroup( renderGroup ).setName( 'cameraNormalMatrices' );
  9386. cameraNormalMatrix = cameraNormalMatrices.element( camera.isMultiViewCamera ? builtin( 'gl_ViewID_OVR' ) : cameraIndex ).toConst( 'cameraNormalMatrix' );
  9387. } else {
  9388. cameraNormalMatrix = uniform( 'mat3' ).setName( 'cameraNormalMatrix' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.normalMatrix );
  9389. }
  9390. return cameraNormalMatrix;
  9391. } ).once() )();
  9392. /**
  9393. * TSL object that represents the position in world space of the camera used for the current render.
  9394. *
  9395. * @tsl
  9396. * @type {UniformNode<vec3>}
  9397. */
  9398. const cameraPosition = /*@__PURE__*/ ( Fn( ( { camera } ) => {
  9399. let cameraPosition;
  9400. if ( camera.isArrayCamera && camera.cameras.length > 0 ) {
  9401. const positions = [];
  9402. for ( let i = 0, l = camera.cameras.length; i < l; i ++ ) {
  9403. positions.push( new Vector3() );
  9404. }
  9405. const cameraPositions = uniformArray( positions ).setGroup( renderGroup ).setName( 'cameraPositions' ).onRenderUpdate( ( { camera }, self ) => {
  9406. const subCameras = camera.cameras;
  9407. const array = self.array;
  9408. for ( let i = 0, l = subCameras.length; i < l; i ++ ) {
  9409. array[ i ].setFromMatrixPosition( subCameras[ i ].matrixWorld );
  9410. }
  9411. } );
  9412. cameraPosition = cameraPositions.element( camera.isMultiViewCamera ? builtin( 'gl_ViewID_OVR' ) : cameraIndex ).toConst( 'cameraPosition' );
  9413. } else {
  9414. cameraPosition = uniform( new Vector3() ).setName( 'cameraPosition' ).setGroup( renderGroup ).onRenderUpdate( ( { camera }, self ) => self.value.setFromMatrixPosition( camera.matrixWorld ) );
  9415. }
  9416. return cameraPosition;
  9417. } ).once() )();
  9418. /**
  9419. * TSL object that represents the viewport of the camera used for the current render.
  9420. *
  9421. * @tsl
  9422. * @type {UniformNode<vec4>}
  9423. */
  9424. const cameraViewport = /*@__PURE__*/ ( Fn( ( { camera } ) => {
  9425. let cameraViewport;
  9426. if ( camera.isArrayCamera && camera.cameras.length > 0 ) {
  9427. const viewports = [];
  9428. for ( const subCamera of camera.cameras ) {
  9429. viewports.push( subCamera.viewport );
  9430. }
  9431. const cameraViewports = uniformArray( viewports, 'vec4' ).setGroup( renderGroup ).setName( 'cameraViewports' );
  9432. cameraViewport = cameraViewports.element( cameraIndex ).toConst( 'cameraViewport' );
  9433. } else {
  9434. // Fallback for single camera
  9435. cameraViewport = vec4( 0, 0, screenSize.x, screenSize.y ).toConst( 'cameraViewport' );
  9436. }
  9437. return cameraViewport;
  9438. } ).once() )();
  9439. const _sphere = /*@__PURE__*/ new Sphere();
  9440. /**
  9441. * This node can be used to access transformation related metrics of 3D objects.
  9442. * Depending on the selected scope, a different metric is represented as a uniform
  9443. * in the shader. The following scopes are supported:
  9444. *
  9445. * - `POSITION`: The object's position in world space.
  9446. * - `VIEW_POSITION`: The object's position in view/camera space.
  9447. * - `DIRECTION`: The object's direction in world space.
  9448. * - `SCALE`: The object's scale in world space.
  9449. * - `WORLD_MATRIX`: The object's matrix in world space.
  9450. *
  9451. * @augments Node
  9452. */
  9453. class Object3DNode extends Node {
  9454. static get type() {
  9455. return 'Object3DNode';
  9456. }
  9457. /**
  9458. * Constructs a new object 3D node.
  9459. *
  9460. * @param {('position'|'viewPosition'|'direction'|'scale'|'worldMatrix')} scope - The node represents a different type of transformation depending on the scope.
  9461. * @param {?Object3D} [object3d=null] - The 3D object.
  9462. */
  9463. constructor( scope, object3d = null ) {
  9464. super();
  9465. /**
  9466. * The node reports a different type of transformation depending on the scope.
  9467. *
  9468. * @type {('position'|'viewPosition'|'direction'|'scale'|'worldMatrix')}
  9469. */
  9470. this.scope = scope;
  9471. /**
  9472. * The 3D object.
  9473. *
  9474. * @type {?Object3D}
  9475. * @default null
  9476. */
  9477. this.object3d = object3d;
  9478. /**
  9479. * Overwritten since this type of node is updated per object.
  9480. *
  9481. * @type {string}
  9482. * @default 'object'
  9483. */
  9484. this.updateType = NodeUpdateType.OBJECT;
  9485. /**
  9486. * Holds the value of the node as a uniform.
  9487. *
  9488. * @type {UniformNode}
  9489. */
  9490. this.uniformNode = new UniformNode( null );
  9491. }
  9492. /**
  9493. * Overwritten since the node type is inferred from the scope.
  9494. *
  9495. * @return {('mat4'|'vec3'|'float')} The node type.
  9496. */
  9497. getNodeType() {
  9498. const scope = this.scope;
  9499. if ( scope === Object3DNode.WORLD_MATRIX ) {
  9500. return 'mat4';
  9501. } else if ( scope === Object3DNode.POSITION || scope === Object3DNode.VIEW_POSITION || scope === Object3DNode.DIRECTION || scope === Object3DNode.SCALE ) {
  9502. return 'vec3';
  9503. } else if ( scope === Object3DNode.RADIUS ) {
  9504. return 'float';
  9505. }
  9506. }
  9507. /**
  9508. * Updates the uniform value depending on the scope.
  9509. *
  9510. * @param {NodeFrame} frame - The current node frame.
  9511. */
  9512. update( frame ) {
  9513. const object = this.object3d;
  9514. const uniformNode = this.uniformNode;
  9515. const scope = this.scope;
  9516. if ( scope === Object3DNode.WORLD_MATRIX ) {
  9517. uniformNode.value = object.matrixWorld;
  9518. } else if ( scope === Object3DNode.POSITION ) {
  9519. uniformNode.value = uniformNode.value || new Vector3();
  9520. uniformNode.value.setFromMatrixPosition( object.matrixWorld );
  9521. } else if ( scope === Object3DNode.SCALE ) {
  9522. uniformNode.value = uniformNode.value || new Vector3();
  9523. uniformNode.value.setFromMatrixScale( object.matrixWorld );
  9524. } else if ( scope === Object3DNode.DIRECTION ) {
  9525. uniformNode.value = uniformNode.value || new Vector3();
  9526. object.getWorldDirection( uniformNode.value );
  9527. } else if ( scope === Object3DNode.VIEW_POSITION ) {
  9528. const camera = frame.camera;
  9529. uniformNode.value = uniformNode.value || new Vector3();
  9530. uniformNode.value.setFromMatrixPosition( object.matrixWorld );
  9531. uniformNode.value.applyMatrix4( camera.matrixWorldInverse );
  9532. } else if ( scope === Object3DNode.RADIUS ) {
  9533. const geometry = frame.object.geometry;
  9534. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  9535. _sphere.copy( geometry.boundingSphere ).applyMatrix4( object.matrixWorld );
  9536. uniformNode.value = _sphere.radius;
  9537. }
  9538. }
  9539. /**
  9540. * Generates the code snippet of the uniform node. The node type of the uniform
  9541. * node also depends on the selected scope.
  9542. *
  9543. * @param {NodeBuilder} builder - The current node builder.
  9544. * @return {string} The generated code snippet.
  9545. */
  9546. generate( builder ) {
  9547. const scope = this.scope;
  9548. if ( scope === Object3DNode.WORLD_MATRIX ) {
  9549. this.uniformNode.nodeType = 'mat4';
  9550. } else if ( scope === Object3DNode.POSITION || scope === Object3DNode.VIEW_POSITION || scope === Object3DNode.DIRECTION || scope === Object3DNode.SCALE ) {
  9551. this.uniformNode.nodeType = 'vec3';
  9552. } else if ( scope === Object3DNode.RADIUS ) {
  9553. this.uniformNode.nodeType = 'float';
  9554. }
  9555. return this.uniformNode.build( builder );
  9556. }
  9557. serialize( data ) {
  9558. super.serialize( data );
  9559. data.scope = this.scope;
  9560. }
  9561. deserialize( data ) {
  9562. super.deserialize( data );
  9563. this.scope = data.scope;
  9564. }
  9565. }
  9566. Object3DNode.WORLD_MATRIX = 'worldMatrix';
  9567. Object3DNode.POSITION = 'position';
  9568. Object3DNode.SCALE = 'scale';
  9569. Object3DNode.VIEW_POSITION = 'viewPosition';
  9570. Object3DNode.DIRECTION = 'direction';
  9571. Object3DNode.RADIUS = 'radius';
  9572. /**
  9573. * TSL function for creating an object 3D node that represents the object's direction in world space.
  9574. *
  9575. * @tsl
  9576. * @function
  9577. * @param {?Object3D} [object3d] - The 3D object.
  9578. * @returns {Object3DNode<vec3>}
  9579. */
  9580. const objectDirection = /*@__PURE__*/ nodeProxy( Object3DNode, Object3DNode.DIRECTION ).setParameterLength( 1 );
  9581. /**
  9582. * TSL function for creating an object 3D node that represents the object's world matrix.
  9583. *
  9584. * @tsl
  9585. * @function
  9586. * @param {?Object3D} [object3d] - The 3D object.
  9587. * @returns {Object3DNode<mat4>}
  9588. */
  9589. const objectWorldMatrix = /*@__PURE__*/ nodeProxy( Object3DNode, Object3DNode.WORLD_MATRIX ).setParameterLength( 1 );
  9590. /**
  9591. * TSL function for creating an object 3D node that represents the object's position in world space.
  9592. *
  9593. * @tsl
  9594. * @function
  9595. * @param {?Object3D} [object3d] - The 3D object.
  9596. * @returns {Object3DNode<vec3>}
  9597. */
  9598. const objectPosition = /*@__PURE__*/ nodeProxy( Object3DNode, Object3DNode.POSITION ).setParameterLength( 1 );
  9599. /**
  9600. * TSL function for creating an object 3D node that represents the object's scale in world space.
  9601. *
  9602. * @tsl
  9603. * @function
  9604. * @param {?Object3D} [object3d] - The 3D object.
  9605. * @returns {Object3DNode<vec3>}
  9606. */
  9607. const objectScale = /*@__PURE__*/ nodeProxy( Object3DNode, Object3DNode.SCALE ).setParameterLength( 1 );
  9608. /**
  9609. * TSL function for creating an object 3D node that represents the object's position in view/camera space.
  9610. *
  9611. * @tsl
  9612. * @function
  9613. * @param {?Object3D} [object3d] - The 3D object.
  9614. * @returns {Object3DNode<vec3>}
  9615. */
  9616. const objectViewPosition = /*@__PURE__*/ nodeProxy( Object3DNode, Object3DNode.VIEW_POSITION ).setParameterLength( 1 );
  9617. /**
  9618. * TSL function for creating an object 3D node that represents the object's radius.
  9619. *
  9620. * @tsl
  9621. * @function
  9622. * @param {?Object3D} [object3d] - The 3D object.
  9623. * @returns {Object3DNode<float>}
  9624. */
  9625. const objectRadius = /*@__PURE__*/ nodeProxy( Object3DNode, Object3DNode.RADIUS ).setParameterLength( 1 );
  9626. /**
  9627. * This type of node is a specialized version of `Object3DNode`
  9628. * with larger set of model related metrics. Unlike `Object3DNode`,
  9629. * `ModelNode` extracts the reference to the 3D object from the
  9630. * current node frame state.
  9631. *
  9632. * @augments Object3DNode
  9633. */
  9634. class ModelNode extends Object3DNode {
  9635. static get type() {
  9636. return 'ModelNode';
  9637. }
  9638. /**
  9639. * Constructs a new object model node.
  9640. *
  9641. * @param {('position'|'viewPosition'|'direction'|'scale'|'worldMatrix')} scope - The node represents a different type of transformation depending on the scope.
  9642. */
  9643. constructor( scope ) {
  9644. super( scope );
  9645. }
  9646. /**
  9647. * Extracts the model reference from the frame state and then
  9648. * updates the uniform value depending on the scope.
  9649. *
  9650. * @param {NodeFrame} frame - The current node frame.
  9651. */
  9652. update( frame ) {
  9653. this.object3d = frame.object;
  9654. super.update( frame );
  9655. }
  9656. }
  9657. /**
  9658. * TSL object that represents the object's direction in world space.
  9659. *
  9660. * @tsl
  9661. * @type {ModelNode<vec3>}
  9662. */
  9663. const modelDirection = /*@__PURE__*/ nodeImmutable( ModelNode, ModelNode.DIRECTION );
  9664. /**
  9665. * TSL object that represents the object's world matrix.
  9666. *
  9667. * @tsl
  9668. * @type {ModelNode<mat4>}
  9669. */
  9670. const modelWorldMatrix = /*@__PURE__*/ nodeImmutable( ModelNode, ModelNode.WORLD_MATRIX );
  9671. /**
  9672. * TSL object that represents the object's position in world space.
  9673. *
  9674. * @tsl
  9675. * @type {ModelNode<vec3>}
  9676. */
  9677. const modelPosition = /*@__PURE__*/ nodeImmutable( ModelNode, ModelNode.POSITION );
  9678. /**
  9679. * TSL object that represents the object's scale in world space.
  9680. *
  9681. * @tsl
  9682. * @type {ModelNode<vec3>}
  9683. */
  9684. const modelScale = /*@__PURE__*/ nodeImmutable( ModelNode, ModelNode.SCALE );
  9685. /**
  9686. * TSL object that represents the object's position in view/camera space.
  9687. *
  9688. * @tsl
  9689. * @type {ModelNode<vec3>}
  9690. */
  9691. const modelViewPosition = /*@__PURE__*/ nodeImmutable( ModelNode, ModelNode.VIEW_POSITION );
  9692. /**
  9693. * TSL object that represents the object's radius.
  9694. *
  9695. * @tsl
  9696. * @type {ModelNode<float>}
  9697. */
  9698. const modelRadius = /*@__PURE__*/ nodeImmutable( ModelNode, ModelNode.RADIUS );
  9699. /**
  9700. * TSL object that represents the object's normal matrix.
  9701. *
  9702. * @tsl
  9703. * @type {UniformNode<mat3>}
  9704. */
  9705. const modelNormalMatrix = /*@__PURE__*/ uniform( new Matrix3() ).onObjectUpdate( ( { object }, self ) => self.value.getNormalMatrix( object.matrixWorld ) );
  9706. /**
  9707. * TSL object that represents the object's inverse world matrix.
  9708. *
  9709. * @tsl
  9710. * @type {UniformNode<mat4>}
  9711. */
  9712. const modelWorldMatrixInverse = /*@__PURE__*/ uniform( new Matrix4() ).onObjectUpdate( ( { object }, self ) => self.value.copy( object.matrixWorld ).invert() );
  9713. /**
  9714. * TSL object that represents the object's model view matrix.
  9715. *
  9716. * @tsl
  9717. * @type {Node<mat4>}
  9718. */
  9719. const modelViewMatrix = /*@__PURE__*/ ( Fn( ( builder ) => {
  9720. return builder.renderer.overrideNodes.modelViewMatrix || mediumpModelViewMatrix;
  9721. } ).once() )().toVar( 'modelViewMatrix' );
  9722. // GPU Precision
  9723. /**
  9724. * TSL object that represents the object's model view in `mediump` precision.
  9725. *
  9726. * @tsl
  9727. * @type {Node<mat4>}
  9728. */
  9729. const mediumpModelViewMatrix = /*@__PURE__*/ cameraViewMatrix.mul( modelWorldMatrix );
  9730. // CPU Precision
  9731. /**
  9732. * TSL object that represents the object's model view in `highp` precision
  9733. * which is achieved by computing the matrix in JS and not in the shader.
  9734. *
  9735. * @tsl
  9736. * @type {Node<mat4>}
  9737. */
  9738. const highpModelViewMatrix = /*@__PURE__*/ ( Fn( ( builder ) => {
  9739. builder.context.isHighPrecisionModelViewMatrix = true;
  9740. return uniform( 'mat4' ).onObjectUpdate( ( { object, camera } ) => {
  9741. return object.modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld );
  9742. } );
  9743. } ).once() )().toVar( 'highpModelViewMatrix' );
  9744. /**
  9745. * TSL object that represents the object's model normal view in `highp` precision
  9746. * which is achieved by computing the matrix in JS and not in the shader.
  9747. *
  9748. * @tsl
  9749. * @type {Node<mat3>}
  9750. */
  9751. const highpModelNormalViewMatrix = /*@__PURE__*/ ( Fn( ( builder ) => {
  9752. const isHighPrecisionModelViewMatrix = builder.context.isHighPrecisionModelViewMatrix;
  9753. return uniform( 'mat3' ).onObjectUpdate( ( { object, camera } ) => {
  9754. if ( isHighPrecisionModelViewMatrix !== true ) {
  9755. object.modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld );
  9756. }
  9757. return object.normalMatrix.getNormalMatrix( object.modelViewMatrix );
  9758. } );
  9759. } ).once() )().toVar( 'highpModelNormalViewMatrix' );
  9760. /**
  9761. * TSL object that represents the position attribute of the current rendered object.
  9762. *
  9763. * @tsl
  9764. * @type {AttributeNode<vec3>}
  9765. */
  9766. const positionGeometry = /*@__PURE__*/ attribute( 'position', 'vec3' );
  9767. /**
  9768. * TSL object that represents the vertex position in local space of the current rendered object.
  9769. *
  9770. * @tsl
  9771. * @type {AttributeNode<vec3>}
  9772. */
  9773. const positionLocal = /*@__PURE__*/ positionGeometry.toVarying( 'positionLocal' );
  9774. /**
  9775. * TSL object that represents the previous vertex position in local space of the current rendered object.
  9776. * Used in context of {@link VelocityNode} for rendering motion vectors.
  9777. *
  9778. * @tsl
  9779. * @type {AttributeNode<vec3>}
  9780. */
  9781. const positionPrevious = /*@__PURE__*/ positionGeometry.toVarying( 'positionPrevious' );
  9782. /**
  9783. * TSL object that represents the vertex position in world space of the current rendered object.
  9784. *
  9785. * @tsl
  9786. * @type {VaryingNode<vec3>}
  9787. */
  9788. const positionWorld = /*@__PURE__*/ ( Fn( ( builder ) => {
  9789. return modelWorldMatrix.mul( positionLocal ).xyz.toVarying( builder.getSubBuildProperty( 'v_positionWorld' ) );
  9790. }, 'vec3' ).once( [ 'POSITION' ] ) )();
  9791. /**
  9792. * TSL object that represents the position world direction of the current rendered object.
  9793. *
  9794. * @tsl
  9795. * @type {Node<vec3>}
  9796. */
  9797. const positionWorldDirection = /*@__PURE__*/ ( Fn( () => {
  9798. const vertexPWD = positionLocal.transformDirection( modelWorldMatrix ).toVarying( 'v_positionWorldDirection' );
  9799. return vertexPWD.normalize().toVar( 'positionWorldDirection' );
  9800. }, 'vec3' ).once( [ 'POSITION' ] ) )();
  9801. /**
  9802. * TSL object that represents the vertex position in view space of the current rendered object.
  9803. *
  9804. * @tsl
  9805. * @type {VaryingNode<vec3>}
  9806. */
  9807. const positionView = /*@__PURE__*/ ( Fn( ( builder ) => {
  9808. return builder.context.setupPositionView().toVarying( 'v_positionView' );
  9809. }, 'vec3' ).once( [ 'POSITION' ] ) )();
  9810. /**
  9811. * TSL object that represents the position view direction of the current rendered object.
  9812. *
  9813. * @tsl
  9814. * @type {VaryingNode<vec3>}
  9815. */
  9816. const positionViewDirection = /*@__PURE__*/ ( Fn( ( builder ) => {
  9817. let output;
  9818. if ( builder.camera.isOrthographicCamera ) {
  9819. output = vec3( 0, 0, 1 );
  9820. } else {
  9821. output = positionView.negate().toVarying( 'v_positionViewDirection' ).normalize();
  9822. }
  9823. return output.toVar( 'positionViewDirection' );
  9824. }, 'vec3' ).once( [ 'POSITION' ] ) )();
  9825. /**
  9826. * This node can be used to evaluate whether a primitive is front or back facing.
  9827. *
  9828. * @augments Node
  9829. */
  9830. class FrontFacingNode extends Node {
  9831. static get type() {
  9832. return 'FrontFacingNode';
  9833. }
  9834. /**
  9835. * Constructs a new front facing node.
  9836. */
  9837. constructor() {
  9838. super( 'bool' );
  9839. /**
  9840. * This flag can be used for type testing.
  9841. *
  9842. * @type {boolean}
  9843. * @readonly
  9844. * @default true
  9845. */
  9846. this.isFrontFacingNode = true;
  9847. }
  9848. generate( builder ) {
  9849. if ( builder.shaderStage !== 'fragment' ) return 'true';
  9850. //
  9851. const { material } = builder;
  9852. if ( material.side === BackSide ) {
  9853. return 'false';
  9854. }
  9855. return builder.getFrontFacing();
  9856. }
  9857. }
  9858. /**
  9859. * TSL object that represents whether a primitive is front or back facing
  9860. *
  9861. * @tsl
  9862. * @type {FrontFacingNode<bool>}
  9863. */
  9864. const frontFacing = /*@__PURE__*/ nodeImmutable( FrontFacingNode );
  9865. /**
  9866. * TSL object that represents the front facing status as a number instead of a bool.
  9867. * `1` means front facing, `-1` means back facing.
  9868. *
  9869. * @tsl
  9870. * @type {Node<float>}
  9871. */
  9872. const faceDirection = /*@__PURE__*/ float( frontFacing ).mul( 2.0 ).sub( 1.0 );
  9873. /**
  9874. * Converts a direction vector to a face direction vector based on the material's side.
  9875. *
  9876. * If the material is set to `BackSide`, the direction is inverted.
  9877. * If the material is set to `DoubleSide`, the direction is multiplied by `faceDirection`.
  9878. *
  9879. * @tsl
  9880. * @param {Node<vec3>} direction - The direction vector to convert.
  9881. * @returns {Node<vec3>} The converted direction vector.
  9882. */
  9883. const directionToFaceDirection = /*@__PURE__*/ Fn( ( [ direction ], { material } ) => {
  9884. const side = material.side;
  9885. if ( side === BackSide ) {
  9886. direction = direction.mul( -1 );
  9887. } else if ( side === DoubleSide ) {
  9888. direction = direction.mul( faceDirection );
  9889. }
  9890. return direction;
  9891. } );
  9892. /**
  9893. * TSL object that represents the normal attribute of the current rendered object in local space.
  9894. *
  9895. * @tsl
  9896. * @type {Node<vec3>}
  9897. */
  9898. const normalGeometry = /*@__PURE__*/ attribute( 'normal', 'vec3' );
  9899. /**
  9900. * TSL object that represents the vertex normal of the current rendered object in local space.
  9901. *
  9902. * @tsl
  9903. * @type {Node<vec3>}
  9904. */
  9905. const normalLocal = /*@__PURE__*/ ( Fn( ( builder ) => {
  9906. if ( builder.geometry.hasAttribute( 'normal' ) === false ) {
  9907. warn( 'TSL: Vertex attribute "normal" not found on geometry.' );
  9908. return vec3( 0, 1, 0 );
  9909. }
  9910. return normalGeometry;
  9911. }, 'vec3' ).once() )().toVar( 'normalLocal' );
  9912. /**
  9913. * TSL object that represents the flat vertex normal of the current rendered object in view space.
  9914. *
  9915. * @tsl
  9916. * @type {Node<vec3>}
  9917. */
  9918. const normalFlat = /*@__PURE__*/ positionView.dFdx().cross( positionView.dFdy() ).normalize().toVar( 'normalFlat' );
  9919. /**
  9920. * TSL object that represents the vertex normal of the current rendered object in view space.
  9921. *
  9922. * @tsl
  9923. * @type {Node<vec3>}
  9924. */
  9925. const normalViewGeometry = /*@__PURE__*/ ( Fn( ( builder ) => {
  9926. let node;
  9927. if ( builder.material.flatShading === true ) {
  9928. node = normalFlat;
  9929. } else {
  9930. node = transformNormalToView( normalLocal ).toVarying( 'v_normalViewGeometry' ).normalize();
  9931. }
  9932. return node;
  9933. }, 'vec3' ).once() )().toVar( 'normalViewGeometry' );
  9934. /**
  9935. * TSL object that represents the vertex normal of the current rendered object in world space.
  9936. *
  9937. * @tsl
  9938. * @type {Node<vec3>}
  9939. */
  9940. const normalWorldGeometry = /*@__PURE__*/ ( Fn( ( builder ) => {
  9941. let normal = normalViewGeometry.transformDirection( cameraViewMatrix );
  9942. if ( builder.material.flatShading !== true ) {
  9943. normal = normal.toVarying( 'v_normalWorldGeometry' );
  9944. }
  9945. return normal.normalize().toVar( 'normalWorldGeometry' );
  9946. }, 'vec3' ).once() )();
  9947. /**
  9948. * TSL object that represents the vertex normal of the current rendered object in view space.
  9949. *
  9950. * @tsl
  9951. * @type {Node<vec3>}
  9952. */
  9953. const normalView = /*@__PURE__*/ ( Fn( ( { subBuildFn, material, context } ) => {
  9954. let node;
  9955. if ( subBuildFn === 'NORMAL' || subBuildFn === 'VERTEX' ) {
  9956. node = normalViewGeometry;
  9957. if ( material.flatShading !== true ) {
  9958. node = directionToFaceDirection( node );
  9959. }
  9960. } else {
  9961. // Use getUV context to avoid side effects from nodes overwriting getUV in the context (e.g. EnvironmentNode)
  9962. node = context.setupNormal().context( { getUV: null } );
  9963. }
  9964. return node;
  9965. }, 'vec3' ).once( [ 'NORMAL', 'VERTEX' ] ) )().toVar( 'normalView' );
  9966. /**
  9967. * TSL object that represents the vertex normal of the current rendered object in world space.
  9968. *
  9969. * @tsl
  9970. * @type {Node<vec3>}
  9971. */
  9972. const normalWorld = /*@__PURE__*/ normalView.transformDirection( cameraViewMatrix ).toVar( 'normalWorld' );
  9973. /**
  9974. * TSL object that represents the clearcoat vertex normal of the current rendered object in view space.
  9975. *
  9976. * @tsl
  9977. * @type {Node<vec3>}
  9978. */
  9979. const clearcoatNormalView = /*@__PURE__*/ ( Fn( ( { subBuildFn, context } ) => {
  9980. let node;
  9981. if ( subBuildFn === 'NORMAL' || subBuildFn === 'VERTEX' ) {
  9982. node = normalView;
  9983. } else {
  9984. // Use getUV context to avoid side effects from nodes overwriting getUV in the context (e.g. EnvironmentNode)
  9985. node = context.setupClearcoatNormal().context( { getUV: null } );
  9986. }
  9987. return node;
  9988. }, 'vec3' ).once( [ 'NORMAL', 'VERTEX' ] ) )().toVar( 'clearcoatNormalView' );
  9989. /**
  9990. * Transforms the normal with the given matrix.
  9991. *
  9992. * @tsl
  9993. * @function
  9994. * @param {Node<vec3>} normal - The normal.
  9995. * @param {Node<mat3>} [matrix=modelWorldMatrix] - The matrix.
  9996. * @return {Node<vec3>} The transformed normal.
  9997. */
  9998. const transformNormal = /*@__PURE__*/ Fn( ( [ normal, matrix = modelWorldMatrix ] ) => {
  9999. const m = mat3( matrix );
  10000. const transformedNormal = normal.div( vec3( m[ 0 ].dot( m[ 0 ] ), m[ 1 ].dot( m[ 1 ] ), m[ 2 ].dot( m[ 2 ] ) ) );
  10001. return m.mul( transformedNormal ).xyz;
  10002. } );
  10003. /**
  10004. * Transforms the given normal from local to view space.
  10005. *
  10006. * @tsl
  10007. * @function
  10008. * @param {Node<vec3>} normal - The normal.
  10009. * @param {NodeBuilder} builder - The current node builder.
  10010. * @return {Node<vec3>} The transformed normal.
  10011. */
  10012. const transformNormalToView = /*@__PURE__*/ Fn( ( [ normal ], builder ) => {
  10013. const modelNormalViewMatrix = builder.renderer.overrideNodes.modelNormalViewMatrix;
  10014. if ( modelNormalViewMatrix !== null ) {
  10015. return modelNormalViewMatrix.transformDirection( normal );
  10016. }
  10017. //
  10018. const transformedNormal = modelNormalMatrix.mul( normal );
  10019. return cameraViewMatrix.transformDirection( transformedNormal );
  10020. } );
  10021. // Deprecated
  10022. /**
  10023. * TSL object that represents the transformed vertex normal of the current rendered object in view space.
  10024. *
  10025. * @tsl
  10026. * @type {Node<vec3>}
  10027. * @deprecated since r178. Use `normalView` instead.
  10028. */
  10029. const transformedNormalView = ( Fn( () => { // @deprecated, r177
  10030. warn( 'TSL: "transformedNormalView" is deprecated. Use "normalView" instead.' );
  10031. return normalView;
  10032. } ).once( [ 'NORMAL', 'VERTEX' ] ) )();
  10033. /**
  10034. * TSL object that represents the transformed vertex normal of the current rendered object in world space.
  10035. *
  10036. * @tsl
  10037. * @type {Node<vec3>}
  10038. * @deprecated since r178. Use `normalWorld` instead.
  10039. */
  10040. const transformedNormalWorld = ( Fn( () => { // @deprecated, r177
  10041. warn( 'TSL: "transformedNormalWorld" is deprecated. Use "normalWorld" instead.' );
  10042. return normalWorld;
  10043. } ).once( [ 'NORMAL', 'VERTEX' ] ) )();
  10044. /**
  10045. * TSL object that represents the transformed clearcoat vertex normal of the current rendered object in view space.
  10046. *
  10047. * @tsl
  10048. * @type {Node<vec3>}
  10049. * @deprecated since r178. Use `clearcoatNormalView` instead.
  10050. */
  10051. const transformedClearcoatNormalView = ( Fn( () => { // @deprecated, r177
  10052. warn( 'TSL: "transformedClearcoatNormalView" is deprecated. Use "clearcoatNormalView" instead.' );
  10053. return clearcoatNormalView;
  10054. } ).once( [ 'NORMAL', 'VERTEX' ] ) )();
  10055. const _e1$1 = /*@__PURE__*/ new Euler();
  10056. const _m1$1 = /*@__PURE__*/ new Matrix4();
  10057. /**
  10058. * TSL object that represents the refraction ratio of the material used for rendering the current object.
  10059. *
  10060. * @tsl
  10061. * @type {UniformNode<float>}
  10062. */
  10063. const materialRefractionRatio = /*@__PURE__*/ uniform( 0 ).onReference( ( { material } ) => material ).onObjectUpdate( ( { material } ) => material.refractionRatio );
  10064. /**
  10065. * TSL object that represents the intensity of environment maps of PBR materials.
  10066. * When `material.envMap` is set, the value is `material.envMapIntensity` otherwise `scene.environmentIntensity`.
  10067. *
  10068. * @tsl
  10069. * @type {Node<float>}
  10070. */
  10071. const materialEnvIntensity = /*@__PURE__*/ uniform( 1 ).onReference( ( { material } ) => material ).onObjectUpdate( function ( { material, scene } ) {
  10072. return material.envMap ? material.envMapIntensity : scene.environmentIntensity;
  10073. } );
  10074. /**
  10075. * TSL object that represents the rotation of environment maps.
  10076. * When `material.envMap` is set, the value is `material.envMapRotation`. `scene.environmentRotation` controls the
  10077. * rotation of `scene.environment` instead.
  10078. *
  10079. * @tsl
  10080. * @type {Node<mat4>}
  10081. */
  10082. const materialEnvRotation = /*@__PURE__*/ uniform( new Matrix4() ).onReference( function ( frame ) {
  10083. return frame.material;
  10084. } ).onObjectUpdate( function ( { material, scene } ) {
  10085. const rotation = ( scene.environment !== null && material.envMap === null ) ? scene.environmentRotation : material.envMapRotation;
  10086. if ( rotation ) {
  10087. _e1$1.copy( rotation );
  10088. _m1$1.makeRotationFromEuler( _e1$1 );
  10089. } else {
  10090. _m1$1.identity();
  10091. }
  10092. return _m1$1;
  10093. } );
  10094. /**
  10095. * The reflect vector in view space.
  10096. *
  10097. * @tsl
  10098. * @type {Node<vec3>}
  10099. */
  10100. const reflectView = /*@__PURE__*/ positionViewDirection.negate().reflect( normalView );
  10101. /**
  10102. * The refract vector in view space.
  10103. *
  10104. * @tsl
  10105. * @type {Node<vec3>}
  10106. */
  10107. const refractView = /*@__PURE__*/ positionViewDirection.negate().refract( normalView, materialRefractionRatio );
  10108. /**
  10109. * Used for sampling cube maps when using cube reflection mapping.
  10110. *
  10111. * @tsl
  10112. * @type {Node<vec3>}
  10113. */
  10114. const reflectVector = /*@__PURE__*/ reflectView.transformDirection( cameraViewMatrix ).toVar( 'reflectVector' );
  10115. /**
  10116. * Used for sampling cube maps when using cube refraction mapping.
  10117. *
  10118. * @tsl
  10119. * @type {Node<vec3>}
  10120. */
  10121. const refractVector = /*@__PURE__*/ refractView.transformDirection( cameraViewMatrix ).toVar( 'reflectVector' );
  10122. const EmptyTexture = /*@__PURE__*/ new CubeTexture();
  10123. /**
  10124. * This type of uniform node represents a cube texture.
  10125. *
  10126. * @augments TextureNode
  10127. */
  10128. class CubeTextureNode extends TextureNode {
  10129. static get type() {
  10130. return 'CubeTextureNode';
  10131. }
  10132. /**
  10133. * Constructs a new cube texture node.
  10134. *
  10135. * @param {CubeTexture} value - The cube texture.
  10136. * @param {?Node<vec3>} [uvNode=null] - The uv node.
  10137. * @param {?Node<int>} [levelNode=null] - The level node.
  10138. * @param {?Node<float>} [biasNode=null] - The bias node.
  10139. */
  10140. constructor( value, uvNode = null, levelNode = null, biasNode = null ) {
  10141. super( value, uvNode, levelNode, biasNode );
  10142. /**
  10143. * This flag can be used for type testing.
  10144. *
  10145. * @type {boolean}
  10146. * @readonly
  10147. * @default true
  10148. */
  10149. this.isCubeTextureNode = true;
  10150. }
  10151. /**
  10152. * Overwrites the default implementation to return a fixed value `'cubeTexture'`.
  10153. *
  10154. * @param {NodeBuilder} builder - The current node builder.
  10155. * @return {string} The input type.
  10156. */
  10157. getInputType( /*builder*/ ) {
  10158. return 'cubeTexture';
  10159. }
  10160. /**
  10161. * Returns a default uvs based on the mapping type of the cube texture.
  10162. *
  10163. * @return {Node<vec3>} The default uv attribute.
  10164. */
  10165. getDefaultUV() {
  10166. const texture = this.value;
  10167. if ( texture.mapping === CubeReflectionMapping ) {
  10168. return reflectVector;
  10169. } else if ( texture.mapping === CubeRefractionMapping ) {
  10170. return refractVector;
  10171. } else {
  10172. error( 'CubeTextureNode: Mapping "%s" not supported.', texture.mapping );
  10173. return vec3( 0, 0, 0 );
  10174. }
  10175. }
  10176. /**
  10177. * Overwritten with an empty implementation since the `updateMatrix` flag is ignored
  10178. * for cube textures. The uv transformation matrix is not applied to cube textures.
  10179. *
  10180. * @param {boolean} value - The update toggle.
  10181. */
  10182. setUpdateMatrix( /*updateMatrix*/ ) { } // Ignore .updateMatrix for CubeTextureNode
  10183. /**
  10184. * Setups the uv node. Depending on the backend as well as the texture type, it might be necessary
  10185. * to modify the uv node for correct sampling.
  10186. *
  10187. * @param {NodeBuilder} builder - The current node builder.
  10188. * @param {Node} uvNode - The uv node to setup.
  10189. * @return {Node} The updated uv node.
  10190. */
  10191. setupUV( builder, uvNode ) {
  10192. const texture = this.value;
  10193. if ( builder.renderer.coordinateSystem === WebGPUCoordinateSystem || ! texture.isRenderTargetTexture ) {
  10194. uvNode = vec3( uvNode.x.negate(), uvNode.yz );
  10195. }
  10196. return materialEnvRotation.mul( uvNode );
  10197. }
  10198. /**
  10199. * Generates the uv code snippet.
  10200. *
  10201. * @param {NodeBuilder} builder - The current node builder.
  10202. * @param {Node} cubeUV - The uv node to generate code for.
  10203. * @return {string} The generated code snippet.
  10204. */
  10205. generateUV( builder, cubeUV ) {
  10206. return cubeUV.build( builder, this.sampler === true ? 'vec3' : 'ivec3' );
  10207. }
  10208. }
  10209. /**
  10210. * TSL function for creating a cube texture node.
  10211. *
  10212. * @tsl
  10213. * @function
  10214. * @param {CubeTexture} value - The cube texture.
  10215. * @param {?Node<vec3>} [uvNode=null] - The uv node.
  10216. * @param {?Node<int>} [levelNode=null] - The level node.
  10217. * @param {?Node<float>} [biasNode=null] - The bias node.
  10218. * @returns {CubeTextureNode}
  10219. */
  10220. const cubeTextureBase = /*@__PURE__*/ nodeProxy( CubeTextureNode ).setParameterLength( 1, 4 ).setName( 'cubeTexture' );
  10221. /**
  10222. * TSL function for creating a cube texture uniform node.
  10223. *
  10224. * @tsl
  10225. * @function
  10226. * @param {?(CubeTexture|CubeTextureNode)} [value=EmptyTexture] - The cube texture.
  10227. * @param {?Node<vec3>} [uvNode=null] - The uv node.
  10228. * @param {?Node<int>} [levelNode=null] - The level node.
  10229. * @param {?Node<float>} [biasNode=null] - The bias node.
  10230. * @returns {CubeTextureNode}
  10231. */
  10232. const cubeTexture = ( value = EmptyTexture, uvNode = null, levelNode = null, biasNode = null ) => {
  10233. let textureNode;
  10234. if ( value && value.isCubeTextureNode === true ) {
  10235. textureNode = nodeObject( value.clone() );
  10236. textureNode.referenceNode = value; // Ensure the reference is set to the original node
  10237. if ( uvNode !== null ) textureNode.uvNode = nodeObject( uvNode );
  10238. if ( levelNode !== null ) textureNode.levelNode = nodeObject( levelNode );
  10239. if ( biasNode !== null ) textureNode.biasNode = nodeObject( biasNode );
  10240. } else {
  10241. textureNode = cubeTextureBase( value, uvNode, levelNode, biasNode );
  10242. }
  10243. return textureNode;
  10244. };
  10245. /**
  10246. * TSL function for creating a uniform cube texture node.
  10247. *
  10248. * @tsl
  10249. * @function
  10250. * @param {?CubeTexture} [value=EmptyTexture] - The cube texture.
  10251. * @returns {CubeTextureNode}
  10252. */
  10253. const uniformCubeTexture = ( value = EmptyTexture ) => cubeTextureBase( value );
  10254. // TODO: Avoid duplicated code and ues only ReferenceBaseNode or ReferenceNode
  10255. /**
  10256. * This class is only relevant if the referenced property is array-like.
  10257. * In this case, `ReferenceElementNode` allows to refer to a specific
  10258. * element inside the data structure via an index.
  10259. *
  10260. * @augments ArrayElementNode
  10261. */
  10262. class ReferenceElementNode extends ArrayElementNode {
  10263. static get type() {
  10264. return 'ReferenceElementNode';
  10265. }
  10266. /**
  10267. * Constructs a new reference element node.
  10268. *
  10269. * @param {?ReferenceNode} referenceNode - The reference node.
  10270. * @param {Node} indexNode - The index node that defines the element access.
  10271. */
  10272. constructor( referenceNode, indexNode ) {
  10273. super( referenceNode, indexNode );
  10274. /**
  10275. * Similar to {@link ReferenceNode#reference}, an additional
  10276. * property references to the current node.
  10277. *
  10278. * @type {?ReferenceNode}
  10279. * @default null
  10280. */
  10281. this.referenceNode = referenceNode;
  10282. /**
  10283. * This flag can be used for type testing.
  10284. *
  10285. * @type {boolean}
  10286. * @readonly
  10287. * @default true
  10288. */
  10289. this.isReferenceElementNode = true;
  10290. }
  10291. /**
  10292. * This method is overwritten since the node type is inferred from
  10293. * the uniform type of the reference node.
  10294. *
  10295. * @return {string} The node type.
  10296. */
  10297. getNodeType() {
  10298. return this.referenceNode.uniformType;
  10299. }
  10300. generate( builder ) {
  10301. const snippet = super.generate( builder );
  10302. const arrayType = this.referenceNode.getNodeType();
  10303. const elementType = this.getNodeType();
  10304. return builder.format( snippet, arrayType, elementType );
  10305. }
  10306. }
  10307. /**
  10308. * This type of node establishes a reference to a property of another object.
  10309. * In this way, the value of the node is automatically linked to the value of
  10310. * referenced object. Reference nodes internally represent the linked value
  10311. * as a uniform.
  10312. *
  10313. * @augments Node
  10314. */
  10315. class ReferenceNode extends Node {
  10316. static get type() {
  10317. return 'ReferenceNode';
  10318. }
  10319. /**
  10320. * Constructs a new reference node.
  10321. *
  10322. * @param {string} property - The name of the property the node refers to.
  10323. * @param {string} uniformType - The uniform type that should be used to represent the property value.
  10324. * @param {?Object} [object=null] - The object the property belongs to.
  10325. * @param {?number} [count=null] - When the linked property is an array-like, this parameter defines its length.
  10326. */
  10327. constructor( property, uniformType, object = null, count = null ) {
  10328. super();
  10329. /**
  10330. * The name of the property the node refers to.
  10331. *
  10332. * @type {string}
  10333. */
  10334. this.property = property;
  10335. /**
  10336. * The uniform type that should be used to represent the property value.
  10337. *
  10338. * @type {string}
  10339. */
  10340. this.uniformType = uniformType;
  10341. /**
  10342. * The object the property belongs to.
  10343. *
  10344. * @type {?Object}
  10345. * @default null
  10346. */
  10347. this.object = object;
  10348. /**
  10349. * When the linked property is an array, this parameter defines its length.
  10350. *
  10351. * @type {?number}
  10352. * @default null
  10353. */
  10354. this.count = count;
  10355. /**
  10356. * The property name might have dots so nested properties can be referred.
  10357. * The hierarchy of the names is stored inside this array.
  10358. *
  10359. * @type {Array<string>}
  10360. */
  10361. this.properties = property.split( '.' );
  10362. /**
  10363. * Points to the current referred object. This property exists next to {@link ReferenceNode#object}
  10364. * since the final reference might be updated from calling code.
  10365. *
  10366. * @type {?Object}
  10367. * @default null
  10368. */
  10369. this.reference = object;
  10370. /**
  10371. * The uniform node that holds the value of the reference node.
  10372. *
  10373. * @type {UniformNode}
  10374. * @default null
  10375. */
  10376. this.node = null;
  10377. /**
  10378. * The uniform group of the internal uniform.
  10379. *
  10380. * @type {UniformGroupNode}
  10381. * @default null
  10382. */
  10383. this.group = null;
  10384. /**
  10385. * An optional label of the internal uniform node.
  10386. *
  10387. * @type {?string}
  10388. * @default null
  10389. */
  10390. this.name = null;
  10391. /**
  10392. * Overwritten since reference nodes are updated per object.
  10393. *
  10394. * @type {string}
  10395. * @default 'object'
  10396. */
  10397. this.updateType = NodeUpdateType.OBJECT;
  10398. }
  10399. /**
  10400. * When the referred property is array-like, this method can be used
  10401. * to access elements via an index node.
  10402. *
  10403. * @param {IndexNode} indexNode - indexNode.
  10404. * @return {ReferenceElementNode} A reference to an element.
  10405. */
  10406. element( indexNode ) {
  10407. return nodeObject( new ReferenceElementNode( this, nodeObject( indexNode ) ) );
  10408. }
  10409. /**
  10410. * Sets the uniform group for this reference node.
  10411. *
  10412. * @param {UniformGroupNode} group - The uniform group to set.
  10413. * @return {ReferenceNode} A reference to this node.
  10414. */
  10415. setGroup( group ) {
  10416. this.group = group;
  10417. return this;
  10418. }
  10419. /**
  10420. * Sets the name for the internal uniform.
  10421. *
  10422. * @param {string} name - The label to set.
  10423. * @return {ReferenceNode} A reference to this node.
  10424. */
  10425. setName( name ) {
  10426. this.name = name;
  10427. return this;
  10428. }
  10429. /**
  10430. * Sets the label for the internal uniform.
  10431. *
  10432. * @deprecated
  10433. * @param {string} name - The label to set.
  10434. * @return {ReferenceNode} A reference to this node.
  10435. */
  10436. label( name ) {
  10437. warn( 'TSL: "label()" has been deprecated. Use "setName()" instead.' ); // @deprecated r179
  10438. return this.setName( name );
  10439. }
  10440. /**
  10441. * Sets the node type which automatically defines the internal
  10442. * uniform type.
  10443. *
  10444. * @param {string} uniformType - The type to set.
  10445. */
  10446. setNodeType( uniformType ) {
  10447. let node = null;
  10448. if ( this.count !== null ) {
  10449. node = buffer( null, uniformType, this.count );
  10450. } else if ( Array.isArray( this.getValueFromReference() ) ) {
  10451. node = uniformArray( null, uniformType );
  10452. } else if ( uniformType === 'texture' ) {
  10453. node = texture( null );
  10454. } else if ( uniformType === 'cubeTexture' ) {
  10455. node = cubeTexture( null );
  10456. } else {
  10457. node = uniform( null, uniformType );
  10458. }
  10459. if ( this.group !== null ) {
  10460. node.setGroup( this.group );
  10461. }
  10462. if ( this.name !== null ) node.setName( this.name );
  10463. this.node = node;
  10464. }
  10465. /**
  10466. * This method is overwritten since the node type is inferred from
  10467. * the type of the reference node.
  10468. *
  10469. * @param {NodeBuilder} builder - The current node builder.
  10470. * @return {string} The node type.
  10471. */
  10472. getNodeType( builder ) {
  10473. if ( this.node === null ) {
  10474. this.updateReference( builder );
  10475. this.updateValue();
  10476. }
  10477. return this.node.getNodeType( builder );
  10478. }
  10479. /**
  10480. * Returns the property value from the given referred object.
  10481. *
  10482. * @param {Object} [object=this.reference] - The object to retrieve the property value from.
  10483. * @return {any} The value.
  10484. */
  10485. getValueFromReference( object = this.reference ) {
  10486. const { properties } = this;
  10487. let value = object[ properties[ 0 ] ];
  10488. for ( let i = 1; i < properties.length; i ++ ) {
  10489. value = value[ properties[ i ] ];
  10490. }
  10491. return value;
  10492. }
  10493. /**
  10494. * Allows to update the reference based on the given state. The state is only
  10495. * evaluated {@link ReferenceNode#object} is not set.
  10496. *
  10497. * @param {(NodeFrame|NodeBuilder)} state - The current state.
  10498. * @return {Object} The updated reference.
  10499. */
  10500. updateReference( state ) {
  10501. this.reference = this.object !== null ? this.object : state.object;
  10502. return this.reference;
  10503. }
  10504. /**
  10505. * The output of the reference node is the internal uniform node.
  10506. *
  10507. * @param {NodeBuilder} builder - The current node builder.
  10508. * @return {UniformNode} The output node.
  10509. */
  10510. setup( /* builder */ ) {
  10511. this.updateValue();
  10512. return this.node;
  10513. }
  10514. /**
  10515. * Overwritten to update the internal uniform value.
  10516. *
  10517. * @param {NodeFrame} frame - A reference to the current node frame.
  10518. */
  10519. update( /*frame*/ ) {
  10520. this.updateValue();
  10521. }
  10522. /**
  10523. * Retrieves the value from the referred object property and uses it
  10524. * to updated the internal uniform.
  10525. */
  10526. updateValue() {
  10527. if ( this.node === null ) this.setNodeType( this.uniformType );
  10528. const value = this.getValueFromReference();
  10529. if ( Array.isArray( value ) ) {
  10530. this.node.array = value;
  10531. } else {
  10532. this.node.value = value;
  10533. }
  10534. }
  10535. }
  10536. /**
  10537. * TSL function for creating a reference node.
  10538. *
  10539. * @tsl
  10540. * @function
  10541. * @param {string} name - The name of the property the node refers to.
  10542. * @param {string} type - The uniform type that should be used to represent the property value.
  10543. * @param {?Object} [object] - The object the property belongs to.
  10544. * @returns {ReferenceNode}
  10545. */
  10546. const reference = ( name, type, object ) => nodeObject( new ReferenceNode( name, type, object ) );
  10547. /**
  10548. * TSL function for creating a reference node. Use this function if you want need a reference
  10549. * to an array-like property that should be represented as a uniform buffer.
  10550. *
  10551. * @tsl
  10552. * @function
  10553. * @param {string} name - The name of the property the node refers to.
  10554. * @param {string} type - The uniform type that should be used to represent the property value.
  10555. * @param {number} count - The number of value inside the array-like object.
  10556. * @param {Object} object - An array-like object the property belongs to.
  10557. * @returns {ReferenceNode}
  10558. */
  10559. const referenceBuffer = ( name, type, count, object ) => nodeObject( new ReferenceNode( name, type, object, count ) );
  10560. /**
  10561. * This node is a special type of reference node which is intended
  10562. * for linking material properties with node values.
  10563. * ```js
  10564. * const opacityNode = materialReference( 'opacity', 'float', material );
  10565. * ```
  10566. * When changing `material.opacity`, the node value of `opacityNode` will
  10567. * automatically be updated.
  10568. *
  10569. * @augments ReferenceNode
  10570. */
  10571. class MaterialReferenceNode extends ReferenceNode {
  10572. static get type() {
  10573. return 'MaterialReferenceNode';
  10574. }
  10575. /**
  10576. * Constructs a new material reference node.
  10577. *
  10578. * @param {string} property - The name of the property the node refers to.
  10579. * @param {string} inputType - The uniform type that should be used to represent the property value.
  10580. * @param {?Material} [material=null] - The material the property belongs to. When no material is set,
  10581. * the node refers to the material of the current rendered object.
  10582. */
  10583. constructor( property, inputType, material = null ) {
  10584. super( property, inputType, material );
  10585. /**
  10586. * The material the property belongs to. When no material is set,
  10587. * the node refers to the material of the current rendered object.
  10588. *
  10589. * @type {?Material}
  10590. * @default null
  10591. */
  10592. this.material = material;
  10593. /**
  10594. * This flag can be used for type testing.
  10595. *
  10596. * @type {boolean}
  10597. * @readonly
  10598. * @default true
  10599. */
  10600. this.isMaterialReferenceNode = true;
  10601. }
  10602. /**
  10603. * Updates the reference based on the given state. The state is only evaluated
  10604. * {@link MaterialReferenceNode#material} is not set.
  10605. *
  10606. * @param {(NodeFrame|NodeBuilder)} state - The current state.
  10607. * @return {Object} The updated reference.
  10608. */
  10609. updateReference( state ) {
  10610. this.reference = this.material !== null ? this.material : state.material;
  10611. return this.reference;
  10612. }
  10613. }
  10614. /**
  10615. * TSL function for creating a material reference node.
  10616. *
  10617. * @tsl
  10618. * @function
  10619. * @param {string} name - The name of the property the node refers to.
  10620. * @param {string} type - The uniform type that should be used to represent the property value.
  10621. * @param {?Material} [material=null] - The material the property belongs to.
  10622. * When no material is set, the node refers to the material of the current rendered object.
  10623. * @returns {MaterialReferenceNode}
  10624. */
  10625. const materialReference = ( name, type, material = null ) => nodeObject( new MaterialReferenceNode( name, type, material ) );
  10626. // Normal Mapping Without Precomputed Tangents
  10627. // http://www.thetenthplanet.de/archives/1180
  10628. const uv = uv$1();
  10629. const q0 = positionView.dFdx();
  10630. const q1 = positionView.dFdy();
  10631. const st0 = uv.dFdx();
  10632. const st1 = uv.dFdy();
  10633. const N = normalView;
  10634. const q1perp = q1.cross( N );
  10635. const q0perp = N.cross( q0 );
  10636. const T = q1perp.mul( st0.x ).add( q0perp.mul( st1.x ) );
  10637. const B = q1perp.mul( st0.y ).add( q0perp.mul( st1.y ) );
  10638. const det = T.dot( T ).max( B.dot( B ) );
  10639. const scale$1 = det.equal( 0.0 ).select( 0.0, det.inverseSqrt() );
  10640. /**
  10641. * Tangent vector in view space, computed dynamically from geometry and UV derivatives.
  10642. * Useful for normal mapping without precomputed tangents.
  10643. *
  10644. * Reference: http://www.thetenthplanet.de/archives/1180
  10645. *
  10646. * @tsl
  10647. * @type {Node<vec3>}
  10648. */
  10649. const tangentViewFrame = /*@__PURE__*/ T.mul( scale$1 ).toVar( 'tangentViewFrame' );
  10650. /**
  10651. * Bitangent vector in view space, computed dynamically from geometry and UV derivatives.
  10652. * Complements the tangentViewFrame for constructing the tangent space basis.
  10653. *
  10654. * Reference: http://www.thetenthplanet.de/archives/1180
  10655. *
  10656. * @tsl
  10657. * @type {Node<vec3>}
  10658. */
  10659. const bitangentViewFrame = /*@__PURE__*/ B.mul( scale$1 ).toVar( 'bitangentViewFrame' );
  10660. /**
  10661. * TSL object that represents the tangent attribute of the current rendered object.
  10662. *
  10663. * @tsl
  10664. * @type {Node<vec4>}
  10665. */
  10666. const tangentGeometry = /*@__PURE__*/ Fn( ( builder ) => {
  10667. if ( builder.geometry.hasAttribute( 'tangent' ) === false ) {
  10668. builder.geometry.computeTangents();
  10669. }
  10670. return attribute( 'tangent', 'vec4' );
  10671. } )();
  10672. /**
  10673. * TSL object that represents the vertex tangent in local space of the current rendered object.
  10674. *
  10675. * @tsl
  10676. * @type {Node<vec3>}
  10677. */
  10678. const tangentLocal = /*@__PURE__*/ tangentGeometry.xyz.toVar( 'tangentLocal' );
  10679. /**
  10680. * TSL object that represents the vertex tangent in view space of the current rendered object.
  10681. *
  10682. * @tsl
  10683. * @type {Node<vec3>}
  10684. */
  10685. const tangentView = /*@__PURE__*/ ( Fn( ( { subBuildFn, geometry, material } ) => {
  10686. let node;
  10687. if ( subBuildFn === 'VERTEX' || geometry.hasAttribute( 'tangent' ) ) {
  10688. node = modelViewMatrix.mul( vec4( tangentLocal, 0 ) ).xyz.toVarying( 'v_tangentView' ).normalize();
  10689. } else {
  10690. node = tangentViewFrame;
  10691. }
  10692. if ( material.flatShading !== true ) {
  10693. node = directionToFaceDirection( node );
  10694. }
  10695. return node;
  10696. }, 'vec3' ).once( [ 'NORMAL', 'VERTEX' ] ) )().toVar( 'tangentView' );
  10697. /**
  10698. * TSL object that represents the vertex tangent in world space of the current rendered object.
  10699. *
  10700. * @tsl
  10701. * @type {Node<vec3>}
  10702. */
  10703. const tangentWorld = /*@__PURE__*/ tangentView.transformDirection( cameraViewMatrix ).toVarying( 'v_tangentWorld' ).normalize().toVar( 'tangentWorld' );
  10704. /**
  10705. * Returns the bitangent node and assigns it to a varying if the material is not flat shaded.
  10706. *
  10707. * @tsl
  10708. * @private
  10709. * @param {Node<vec3>} crossNormalTangent - The cross product of the normal and tangent vectors.
  10710. * @param {string} varyingName - The name of the varying to assign the bitangent to.
  10711. * @returns {Node<vec3>} The bitangent node.
  10712. */
  10713. const getBitangent = /*@__PURE__*/ Fn( ( [ crossNormalTangent, varyingName ], { subBuildFn, material } ) => {
  10714. let bitangent = crossNormalTangent.mul( tangentGeometry.w ).xyz;
  10715. if ( subBuildFn === 'NORMAL' && material.flatShading !== true ) {
  10716. bitangent = bitangent.toVarying( varyingName );
  10717. }
  10718. return bitangent;
  10719. } ).once( [ 'NORMAL' ] );
  10720. /**
  10721. * TSL object that represents the bitangent attribute of the current rendered object.
  10722. *
  10723. * @tsl
  10724. * @type {Node<vec3>}
  10725. */
  10726. const bitangentGeometry = /*@__PURE__*/ getBitangent( normalGeometry.cross( tangentGeometry ), 'v_bitangentGeometry' ).normalize().toVar( 'bitangentGeometry' );
  10727. /**
  10728. * TSL object that represents the vertex bitangent in local space of the current rendered object.
  10729. *
  10730. * @tsl
  10731. * @type {Node<vec3>}
  10732. */
  10733. const bitangentLocal = /*@__PURE__*/ getBitangent( normalLocal.cross( tangentLocal ), 'v_bitangentLocal' ).normalize().toVar( 'bitangentLocal' );
  10734. /**
  10735. * TSL object that represents the vertex bitangent in view space of the current rendered object.
  10736. *
  10737. * @tsl
  10738. * @type {Node<vec3>}
  10739. */
  10740. const bitangentView = /*@__PURE__*/ ( Fn( ( { subBuildFn, geometry, material } ) => {
  10741. let node;
  10742. if ( subBuildFn === 'VERTEX' || geometry.hasAttribute( 'tangent' ) ) {
  10743. node = getBitangent( normalView.cross( tangentView ), 'v_bitangentView' ).normalize();
  10744. } else {
  10745. node = bitangentViewFrame;
  10746. }
  10747. if ( material.flatShading !== true ) {
  10748. node = directionToFaceDirection( node );
  10749. }
  10750. return node;
  10751. }, 'vec3' ).once( [ 'NORMAL', 'VERTEX' ] ) )().toVar( 'bitangentView' );
  10752. /**
  10753. * TSL object that represents the vertex bitangent in world space of the current rendered object.
  10754. *
  10755. * @tsl
  10756. * @type {Node<vec3>}
  10757. */
  10758. const bitangentWorld = /*@__PURE__*/ getBitangent( normalWorld.cross( tangentWorld ), 'v_bitangentWorld' ).normalize().toVar( 'bitangentWorld' );
  10759. /**
  10760. * TSL object that represents the TBN matrix in view space.
  10761. *
  10762. * @tsl
  10763. * @type {Node<mat3>}
  10764. */
  10765. const TBNViewMatrix = /*@__PURE__*/ mat3( tangentView, bitangentView, normalView ).toVar( 'TBNViewMatrix' );
  10766. /**
  10767. * TSL object that represents the parallax direction.
  10768. *
  10769. * @tsl
  10770. * @type {Node<mat3>}
  10771. */
  10772. const parallaxDirection = /*@__PURE__*/ positionViewDirection.mul( TBNViewMatrix )/*.normalize()*/;
  10773. /**
  10774. * TSL function for computing parallax uv coordinates.
  10775. *
  10776. * @tsl
  10777. * @function
  10778. * @param {Node<vec2>} uv - A uv node.
  10779. * @param {Node<vec2>} scale - A scale node.
  10780. * @returns {Node<vec2>} Parallax uv coordinates.
  10781. */
  10782. const parallaxUV = ( uv, scale ) => uv.sub( parallaxDirection.mul( scale ) );
  10783. /**
  10784. * TSL function for computing bent normals.
  10785. *
  10786. * @tsl
  10787. * @function
  10788. * @returns {Node<vec3>} Bent normals.
  10789. */
  10790. const bentNormalView = /*@__PURE__*/ ( Fn( () => {
  10791. // https://google.github.io/filament/Filament.md.html#lighting/imagebasedlights/anisotropy
  10792. let bentNormal = anisotropyB.cross( positionViewDirection );
  10793. bentNormal = bentNormal.cross( anisotropyB ).normalize();
  10794. bentNormal = mix( bentNormal, normalView, anisotropy.mul( roughness.oneMinus() ).oneMinus().pow2().pow2() ).normalize();
  10795. return bentNormal;
  10796. } ).once() )();
  10797. /**
  10798. * This class can be used for applying normals maps to materials.
  10799. *
  10800. * ```js
  10801. * material.normalNode = normalMap( texture( normalTex ) );
  10802. * ```
  10803. *
  10804. * @augments TempNode
  10805. */
  10806. class NormalMapNode extends TempNode {
  10807. static get type() {
  10808. return 'NormalMapNode';
  10809. }
  10810. /**
  10811. * Constructs a new normal map node.
  10812. *
  10813. * @param {Node<vec3>} node - Represents the normal map data.
  10814. * @param {?Node<vec2>} [scaleNode=null] - Controls the intensity of the effect.
  10815. */
  10816. constructor( node, scaleNode = null ) {
  10817. super( 'vec3' );
  10818. /**
  10819. * Represents the normal map data.
  10820. *
  10821. * @type {Node<vec3>}
  10822. */
  10823. this.node = node;
  10824. /**
  10825. * Controls the intensity of the effect.
  10826. *
  10827. * @type {?Node<vec2>}
  10828. * @default null
  10829. */
  10830. this.scaleNode = scaleNode;
  10831. /**
  10832. * The normal map type.
  10833. *
  10834. * @type {(TangentSpaceNormalMap|ObjectSpaceNormalMap)}
  10835. * @default TangentSpaceNormalMap
  10836. */
  10837. this.normalMapType = TangentSpaceNormalMap;
  10838. }
  10839. setup( { material } ) {
  10840. const { normalMapType, scaleNode } = this;
  10841. let normalMap = this.node.mul( 2.0 ).sub( 1.0 );
  10842. if ( scaleNode !== null ) {
  10843. let scale = scaleNode;
  10844. if ( material.flatShading === true ) {
  10845. scale = directionToFaceDirection( scale );
  10846. }
  10847. normalMap = vec3( normalMap.xy.mul( scale ), normalMap.z );
  10848. }
  10849. let output = null;
  10850. if ( normalMapType === ObjectSpaceNormalMap ) {
  10851. output = transformNormalToView( normalMap );
  10852. } else if ( normalMapType === TangentSpaceNormalMap ) {
  10853. output = TBNViewMatrix.mul( normalMap ).normalize();
  10854. } else {
  10855. error( `NodeMaterial: Unsupported normal map type: ${ normalMapType }` );
  10856. output = normalView; // Fallback to default normal view
  10857. }
  10858. return output;
  10859. }
  10860. }
  10861. /**
  10862. * TSL function for creating a normal map node.
  10863. *
  10864. * @tsl
  10865. * @function
  10866. * @param {Node<vec3>} node - Represents the normal map data.
  10867. * @param {?Node<vec2>} [scaleNode=null] - Controls the intensity of the effect.
  10868. * @returns {NormalMapNode}
  10869. */
  10870. const normalMap = /*@__PURE__*/ nodeProxy( NormalMapNode ).setParameterLength( 1, 2 );
  10871. // Bump Mapping Unparametrized Surfaces on the GPU by Morten S. Mikkelsen
  10872. // https://mmikk.github.io/papers3d/mm_sfgrad_bump.pdf
  10873. const dHdxy_fwd = Fn( ( { textureNode, bumpScale } ) => {
  10874. // It's used to preserve the same TextureNode instance
  10875. const sampleTexture = ( callback ) => textureNode.isolate().context( { getUV: ( texNode ) => callback( texNode.uvNode || uv$1() ), forceUVContext: true } );
  10876. const Hll = float( sampleTexture( ( uvNode ) => uvNode ) );
  10877. return vec2(
  10878. float( sampleTexture( ( uvNode ) => uvNode.add( uvNode.dFdx() ) ) ).sub( Hll ),
  10879. float( sampleTexture( ( uvNode ) => uvNode.add( uvNode.dFdy() ) ) ).sub( Hll )
  10880. ).mul( bumpScale );
  10881. } );
  10882. // Evaluate the derivative of the height w.r.t. screen-space using forward differencing (listing 2)
  10883. const perturbNormalArb = Fn( ( inputs ) => {
  10884. const { surf_pos, surf_norm, dHdxy } = inputs;
  10885. // normalize is done to ensure that the bump map looks the same regardless of the texture's scale
  10886. const vSigmaX = surf_pos.dFdx().normalize();
  10887. const vSigmaY = surf_pos.dFdy().normalize();
  10888. const vN = surf_norm; // normalized
  10889. const R1 = vSigmaY.cross( vN );
  10890. const R2 = vN.cross( vSigmaX );
  10891. const fDet = vSigmaX.dot( R1 ).mul( faceDirection );
  10892. const vGrad = fDet.sign().mul( dHdxy.x.mul( R1 ).add( dHdxy.y.mul( R2 ) ) );
  10893. return fDet.abs().mul( surf_norm ).sub( vGrad ).normalize();
  10894. } );
  10895. /**
  10896. * This class can be used for applying bump maps to materials.
  10897. *
  10898. * ```js
  10899. * material.normalNode = bumpMap( texture( bumpTex ) );
  10900. * ```
  10901. *
  10902. * @augments TempNode
  10903. */
  10904. class BumpMapNode extends TempNode {
  10905. static get type() {
  10906. return 'BumpMapNode';
  10907. }
  10908. /**
  10909. * Constructs a new bump map node.
  10910. *
  10911. * @param {Node<float>} textureNode - Represents the bump map data.
  10912. * @param {?Node<float>} [scaleNode=null] - Controls the intensity of the bump effect.
  10913. */
  10914. constructor( textureNode, scaleNode = null ) {
  10915. super( 'vec3' );
  10916. /**
  10917. * Represents the bump map data.
  10918. *
  10919. * @type {Node<float>}
  10920. */
  10921. this.textureNode = textureNode;
  10922. /**
  10923. * Controls the intensity of the bump effect.
  10924. *
  10925. * @type {?Node<float>}
  10926. * @default null
  10927. */
  10928. this.scaleNode = scaleNode;
  10929. }
  10930. setup() {
  10931. const bumpScale = this.scaleNode !== null ? this.scaleNode : 1;
  10932. const dHdxy = dHdxy_fwd( { textureNode: this.textureNode, bumpScale } );
  10933. return perturbNormalArb( {
  10934. surf_pos: positionView,
  10935. surf_norm: normalView,
  10936. dHdxy
  10937. } );
  10938. }
  10939. }
  10940. /**
  10941. * TSL function for creating a bump map node.
  10942. *
  10943. * @tsl
  10944. * @function
  10945. * @param {Node<float>} textureNode - Represents the bump map data.
  10946. * @param {?Node<float>} [scaleNode=null] - Controls the intensity of the bump effect.
  10947. * @returns {BumpMapNode}
  10948. */
  10949. const bumpMap = /*@__PURE__*/ nodeProxy( BumpMapNode ).setParameterLength( 1, 2 );
  10950. const _propertyCache = new Map();
  10951. /**
  10952. * This class should simplify the node access to material properties.
  10953. * It internal uses reference nodes to make sure changes to material
  10954. * properties are automatically reflected to predefined TSL objects
  10955. * like e.g. `materialColor`.
  10956. *
  10957. * @augments Node
  10958. */
  10959. class MaterialNode extends Node {
  10960. static get type() {
  10961. return 'MaterialNode';
  10962. }
  10963. /**
  10964. * Constructs a new material node.
  10965. *
  10966. * @param {string} scope - The scope defines what kind of material property is referred by the node.
  10967. */
  10968. constructor( scope ) {
  10969. super();
  10970. /**
  10971. * The scope defines what material property is referred by the node.
  10972. *
  10973. * @type {string}
  10974. */
  10975. this.scope = scope;
  10976. }
  10977. /**
  10978. * Returns a cached reference node for the given property and type.
  10979. *
  10980. * @param {string} property - The name of the material property.
  10981. * @param {string} type - The uniform type of the property.
  10982. * @return {MaterialReferenceNode} A material reference node representing the property access.
  10983. */
  10984. getCache( property, type ) {
  10985. let node = _propertyCache.get( property );
  10986. if ( node === undefined ) {
  10987. node = materialReference( property, type );
  10988. _propertyCache.set( property, node );
  10989. }
  10990. return node;
  10991. }
  10992. /**
  10993. * Returns a float-typed material reference node for the given property name.
  10994. *
  10995. * @param {string} property - The name of the material property.
  10996. * @return {MaterialReferenceNode<float>} A material reference node representing the property access.
  10997. */
  10998. getFloat( property ) {
  10999. return this.getCache( property, 'float' );
  11000. }
  11001. /**
  11002. * Returns a color-typed material reference node for the given property name.
  11003. *
  11004. * @param {string} property - The name of the material property.
  11005. * @return {MaterialReferenceNode<color>} A material reference node representing the property access.
  11006. */
  11007. getColor( property ) {
  11008. return this.getCache( property, 'color' );
  11009. }
  11010. /**
  11011. * Returns a texture-typed material reference node for the given property name.
  11012. *
  11013. * @param {string} property - The name of the material property.
  11014. * @return {MaterialReferenceNode} A material reference node representing the property access.
  11015. */
  11016. getTexture( property ) {
  11017. return this.getCache( property === 'map' ? 'map' : property + 'Map', 'texture' );
  11018. }
  11019. /**
  11020. * The node setup is done depending on the selected scope. Multiple material properties
  11021. * might be grouped into a single node composition if they logically belong together.
  11022. *
  11023. * @param {NodeBuilder} builder - The current node builder.
  11024. * @return {Node} The node representing the selected scope.
  11025. */
  11026. setup( builder ) {
  11027. const material = builder.context.material;
  11028. const scope = this.scope;
  11029. let node = null;
  11030. if ( scope === MaterialNode.COLOR ) {
  11031. const colorNode = material.color !== undefined ? this.getColor( scope ) : vec3();
  11032. if ( material.map && material.map.isTexture === true ) {
  11033. node = colorNode.mul( this.getTexture( 'map' ) );
  11034. } else {
  11035. node = colorNode;
  11036. }
  11037. } else if ( scope === MaterialNode.OPACITY ) {
  11038. const opacityNode = this.getFloat( scope );
  11039. if ( material.alphaMap && material.alphaMap.isTexture === true ) {
  11040. node = opacityNode.mul( this.getTexture( 'alpha' ) );
  11041. } else {
  11042. node = opacityNode;
  11043. }
  11044. } else if ( scope === MaterialNode.SPECULAR_STRENGTH ) {
  11045. if ( material.specularMap && material.specularMap.isTexture === true ) {
  11046. node = this.getTexture( 'specular' ).r;
  11047. } else {
  11048. node = float( 1 );
  11049. }
  11050. } else if ( scope === MaterialNode.SPECULAR_INTENSITY ) {
  11051. const specularIntensityNode = this.getFloat( scope );
  11052. if ( material.specularIntensityMap && material.specularIntensityMap.isTexture === true ) {
  11053. node = specularIntensityNode.mul( this.getTexture( scope ).a );
  11054. } else {
  11055. node = specularIntensityNode;
  11056. }
  11057. } else if ( scope === MaterialNode.SPECULAR_COLOR ) {
  11058. const specularColorNode = this.getColor( scope );
  11059. if ( material.specularColorMap && material.specularColorMap.isTexture === true ) {
  11060. node = specularColorNode.mul( this.getTexture( scope ).rgb );
  11061. } else {
  11062. node = specularColorNode;
  11063. }
  11064. } else if ( scope === MaterialNode.ROUGHNESS ) { // TODO: cleanup similar branches
  11065. const roughnessNode = this.getFloat( scope );
  11066. if ( material.roughnessMap && material.roughnessMap.isTexture === true ) {
  11067. node = roughnessNode.mul( this.getTexture( scope ).g );
  11068. } else {
  11069. node = roughnessNode;
  11070. }
  11071. } else if ( scope === MaterialNode.METALNESS ) {
  11072. const metalnessNode = this.getFloat( scope );
  11073. if ( material.metalnessMap && material.metalnessMap.isTexture === true ) {
  11074. node = metalnessNode.mul( this.getTexture( scope ).b );
  11075. } else {
  11076. node = metalnessNode;
  11077. }
  11078. } else if ( scope === MaterialNode.EMISSIVE ) {
  11079. const emissiveIntensityNode = this.getFloat( 'emissiveIntensity' );
  11080. const emissiveNode = this.getColor( scope ).mul( emissiveIntensityNode );
  11081. if ( material.emissiveMap && material.emissiveMap.isTexture === true ) {
  11082. node = emissiveNode.mul( this.getTexture( scope ) );
  11083. } else {
  11084. node = emissiveNode;
  11085. }
  11086. } else if ( scope === MaterialNode.NORMAL ) {
  11087. if ( material.normalMap ) {
  11088. node = normalMap( this.getTexture( 'normal' ), this.getCache( 'normalScale', 'vec2' ) );
  11089. node.normalMapType = material.normalMapType;
  11090. } else if ( material.bumpMap ) {
  11091. node = bumpMap( this.getTexture( 'bump' ).r, this.getFloat( 'bumpScale' ) );
  11092. } else {
  11093. node = normalView;
  11094. }
  11095. } else if ( scope === MaterialNode.CLEARCOAT ) {
  11096. const clearcoatNode = this.getFloat( scope );
  11097. if ( material.clearcoatMap && material.clearcoatMap.isTexture === true ) {
  11098. node = clearcoatNode.mul( this.getTexture( scope ).r );
  11099. } else {
  11100. node = clearcoatNode;
  11101. }
  11102. } else if ( scope === MaterialNode.CLEARCOAT_ROUGHNESS ) {
  11103. const clearcoatRoughnessNode = this.getFloat( scope );
  11104. if ( material.clearcoatRoughnessMap && material.clearcoatRoughnessMap.isTexture === true ) {
  11105. node = clearcoatRoughnessNode.mul( this.getTexture( scope ).r );
  11106. } else {
  11107. node = clearcoatRoughnessNode;
  11108. }
  11109. } else if ( scope === MaterialNode.CLEARCOAT_NORMAL ) {
  11110. if ( material.clearcoatNormalMap ) {
  11111. node = normalMap( this.getTexture( scope ), this.getCache( scope + 'Scale', 'vec2' ) );
  11112. } else {
  11113. node = normalView;
  11114. }
  11115. } else if ( scope === MaterialNode.SHEEN ) {
  11116. const sheenNode = this.getColor( 'sheenColor' ).mul( this.getFloat( 'sheen' ) ); // Move this mul() to CPU
  11117. if ( material.sheenColorMap && material.sheenColorMap.isTexture === true ) {
  11118. node = sheenNode.mul( this.getTexture( 'sheenColor' ).rgb );
  11119. } else {
  11120. node = sheenNode;
  11121. }
  11122. } else if ( scope === MaterialNode.SHEEN_ROUGHNESS ) {
  11123. const sheenRoughnessNode = this.getFloat( scope );
  11124. if ( material.sheenRoughnessMap && material.sheenRoughnessMap.isTexture === true ) {
  11125. node = sheenRoughnessNode.mul( this.getTexture( scope ).a );
  11126. } else {
  11127. node = sheenRoughnessNode;
  11128. }
  11129. node = node.clamp( 0.07, 1.0 );
  11130. } else if ( scope === MaterialNode.ANISOTROPY ) {
  11131. if ( material.anisotropyMap && material.anisotropyMap.isTexture === true ) {
  11132. const anisotropyPolar = this.getTexture( scope );
  11133. const anisotropyMat = mat2( materialAnisotropyVector.x, materialAnisotropyVector.y, materialAnisotropyVector.y.negate(), materialAnisotropyVector.x );
  11134. node = anisotropyMat.mul( anisotropyPolar.rg.mul( 2.0 ).sub( vec2( 1.0 ) ).normalize().mul( anisotropyPolar.b ) );
  11135. } else {
  11136. node = materialAnisotropyVector;
  11137. }
  11138. } else if ( scope === MaterialNode.IRIDESCENCE_THICKNESS ) {
  11139. const iridescenceThicknessMaximum = reference( '1', 'float', material.iridescenceThicknessRange );
  11140. if ( material.iridescenceThicknessMap ) {
  11141. const iridescenceThicknessMinimum = reference( '0', 'float', material.iridescenceThicknessRange );
  11142. node = iridescenceThicknessMaximum.sub( iridescenceThicknessMinimum ).mul( this.getTexture( scope ).g ).add( iridescenceThicknessMinimum );
  11143. } else {
  11144. node = iridescenceThicknessMaximum;
  11145. }
  11146. } else if ( scope === MaterialNode.TRANSMISSION ) {
  11147. const transmissionNode = this.getFloat( scope );
  11148. if ( material.transmissionMap ) {
  11149. node = transmissionNode.mul( this.getTexture( scope ).r );
  11150. } else {
  11151. node = transmissionNode;
  11152. }
  11153. } else if ( scope === MaterialNode.THICKNESS ) {
  11154. const thicknessNode = this.getFloat( scope );
  11155. if ( material.thicknessMap ) {
  11156. node = thicknessNode.mul( this.getTexture( scope ).g );
  11157. } else {
  11158. node = thicknessNode;
  11159. }
  11160. } else if ( scope === MaterialNode.IOR ) {
  11161. node = this.getFloat( scope );
  11162. } else if ( scope === MaterialNode.LIGHT_MAP ) {
  11163. node = this.getTexture( scope ).rgb.mul( this.getFloat( 'lightMapIntensity' ) );
  11164. } else if ( scope === MaterialNode.AO ) {
  11165. node = this.getTexture( scope ).r.sub( 1.0 ).mul( this.getFloat( 'aoMapIntensity' ) ).add( 1.0 );
  11166. } else if ( scope === MaterialNode.LINE_DASH_OFFSET ) {
  11167. node = ( material.dashOffset ) ? this.getFloat( scope ) : float( 0 );
  11168. } else {
  11169. const outputType = this.getNodeType( builder );
  11170. node = this.getCache( scope, outputType );
  11171. }
  11172. return node;
  11173. }
  11174. }
  11175. MaterialNode.ALPHA_TEST = 'alphaTest';
  11176. MaterialNode.COLOR = 'color';
  11177. MaterialNode.OPACITY = 'opacity';
  11178. MaterialNode.SHININESS = 'shininess';
  11179. MaterialNode.SPECULAR = 'specular';
  11180. MaterialNode.SPECULAR_STRENGTH = 'specularStrength';
  11181. MaterialNode.SPECULAR_INTENSITY = 'specularIntensity';
  11182. MaterialNode.SPECULAR_COLOR = 'specularColor';
  11183. MaterialNode.REFLECTIVITY = 'reflectivity';
  11184. MaterialNode.ROUGHNESS = 'roughness';
  11185. MaterialNode.METALNESS = 'metalness';
  11186. MaterialNode.NORMAL = 'normal';
  11187. MaterialNode.CLEARCOAT = 'clearcoat';
  11188. MaterialNode.CLEARCOAT_ROUGHNESS = 'clearcoatRoughness';
  11189. MaterialNode.CLEARCOAT_NORMAL = 'clearcoatNormal';
  11190. MaterialNode.EMISSIVE = 'emissive';
  11191. MaterialNode.ROTATION = 'rotation';
  11192. MaterialNode.SHEEN = 'sheen';
  11193. MaterialNode.SHEEN_ROUGHNESS = 'sheenRoughness';
  11194. MaterialNode.ANISOTROPY = 'anisotropy';
  11195. MaterialNode.IRIDESCENCE = 'iridescence';
  11196. MaterialNode.IRIDESCENCE_IOR = 'iridescenceIOR';
  11197. MaterialNode.IRIDESCENCE_THICKNESS = 'iridescenceThickness';
  11198. MaterialNode.IOR = 'ior';
  11199. MaterialNode.TRANSMISSION = 'transmission';
  11200. MaterialNode.THICKNESS = 'thickness';
  11201. MaterialNode.ATTENUATION_DISTANCE = 'attenuationDistance';
  11202. MaterialNode.ATTENUATION_COLOR = 'attenuationColor';
  11203. MaterialNode.LINE_SCALE = 'scale';
  11204. MaterialNode.LINE_DASH_SIZE = 'dashSize';
  11205. MaterialNode.LINE_GAP_SIZE = 'gapSize';
  11206. MaterialNode.LINE_WIDTH = 'linewidth';
  11207. MaterialNode.LINE_DASH_OFFSET = 'dashOffset';
  11208. MaterialNode.POINT_SIZE = 'size';
  11209. MaterialNode.DISPERSION = 'dispersion';
  11210. MaterialNode.LIGHT_MAP = 'light';
  11211. MaterialNode.AO = 'ao';
  11212. /**
  11213. * TSL object that represents alpha test of the current material.
  11214. *
  11215. * @tsl
  11216. * @type {Node<float>}
  11217. */
  11218. const materialAlphaTest = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.ALPHA_TEST );
  11219. /**
  11220. * TSL object that represents the diffuse color of the current material.
  11221. * The value is composed via `color` * `map`.
  11222. *
  11223. * @tsl
  11224. * @type {Node<vec3>}
  11225. */
  11226. const materialColor = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.COLOR );
  11227. /**
  11228. * TSL object that represents the shininess of the current material.
  11229. *
  11230. * @tsl
  11231. * @type {Node<float>}
  11232. */
  11233. const materialShininess = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SHININESS );
  11234. /**
  11235. * TSL object that represents the emissive color of the current material.
  11236. * The value is composed via `emissive` * `emissiveIntensity` * `emissiveMap`.
  11237. *
  11238. * @tsl
  11239. * @type {Node<vec3>}
  11240. */
  11241. const materialEmissive = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.EMISSIVE );
  11242. /**
  11243. * TSL object that represents the opacity of the current material.
  11244. * The value is composed via `opacity` * `alphaMap`.
  11245. *
  11246. * @tsl
  11247. * @type {Node<float>}
  11248. */
  11249. const materialOpacity = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.OPACITY );
  11250. /**
  11251. * TSL object that represents the specular of the current material.
  11252. *
  11253. * @tsl
  11254. * @type {Node<vec3>}
  11255. */
  11256. const materialSpecular = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SPECULAR );
  11257. /**
  11258. * TSL object that represents the specular intensity of the current material.
  11259. * The value is composed via `specularIntensity` * `specularMap.a`.
  11260. *
  11261. * @tsl
  11262. * @type {Node<float>}
  11263. */
  11264. const materialSpecularIntensity = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SPECULAR_INTENSITY );
  11265. /**
  11266. * TSL object that represents the specular color of the current material.
  11267. * The value is composed via `specularColor` * `specularMap.rgb`.
  11268. *
  11269. * @tsl
  11270. * @type {Node<vec3>}
  11271. */
  11272. const materialSpecularColor = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SPECULAR_COLOR );
  11273. /**
  11274. * TSL object that represents the specular strength of the current material.
  11275. * The value is composed via `specularMap.r`.
  11276. *
  11277. * @tsl
  11278. * @type {Node<float>}
  11279. */
  11280. const materialSpecularStrength = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SPECULAR_STRENGTH );
  11281. /**
  11282. * TSL object that represents the reflectivity of the current material.
  11283. *
  11284. * @tsl
  11285. * @type {Node<float>}
  11286. */
  11287. const materialReflectivity = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.REFLECTIVITY );
  11288. /**
  11289. * TSL object that represents the roughness of the current material.
  11290. * The value is composed via `roughness` * `roughnessMap.g`.
  11291. *
  11292. * @tsl
  11293. * @type {Node<float>}
  11294. */
  11295. const materialRoughness = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.ROUGHNESS );
  11296. /**
  11297. * TSL object that represents the metalness of the current material.
  11298. * The value is composed via `metalness` * `metalnessMap.b`.
  11299. *
  11300. * @tsl
  11301. * @type {Node<float>}
  11302. */
  11303. const materialMetalness = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.METALNESS );
  11304. /**
  11305. * TSL object that represents the normal of the current material.
  11306. * The value will be either `normalMap` * `normalScale`, `bumpMap` * `bumpScale` or `normalView`.
  11307. *
  11308. * @tsl
  11309. * @type {Node<vec3>}
  11310. */
  11311. const materialNormal = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.NORMAL );
  11312. /**
  11313. * TSL object that represents the clearcoat of the current material.
  11314. * The value is composed via `clearcoat` * `clearcoatMap.r`
  11315. *
  11316. * @tsl
  11317. * @type {Node<float>}
  11318. */
  11319. const materialClearcoat = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.CLEARCOAT );
  11320. /**
  11321. * TSL object that represents the clearcoat roughness of the current material.
  11322. * The value is composed via `clearcoatRoughness` * `clearcoatRoughnessMap.r`.
  11323. *
  11324. * @tsl
  11325. * @type {Node<float>}
  11326. */
  11327. const materialClearcoatRoughness = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.CLEARCOAT_ROUGHNESS );
  11328. /**
  11329. * TSL object that represents the clearcoat normal of the current material.
  11330. * The value will be either `clearcoatNormalMap` or `normalView`.
  11331. *
  11332. * @tsl
  11333. * @type {Node<vec3>}
  11334. */
  11335. const materialClearcoatNormal = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.CLEARCOAT_NORMAL );
  11336. /**
  11337. * TSL object that represents the rotation of the current sprite material.
  11338. *
  11339. * @tsl
  11340. * @type {Node<float>}
  11341. */
  11342. const materialRotation = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.ROTATION );
  11343. /**
  11344. * TSL object that represents the sheen color of the current material.
  11345. * The value is composed via `sheen` * `sheenColor` * `sheenColorMap`.
  11346. *
  11347. * @tsl
  11348. * @type {Node<vec3>}
  11349. */
  11350. const materialSheen = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SHEEN );
  11351. /**
  11352. * TSL object that represents the sheen roughness of the current material.
  11353. * The value is composed via `sheenRoughness` * `sheenRoughnessMap.a`.
  11354. *
  11355. * @tsl
  11356. * @type {Node<float>}
  11357. */
  11358. const materialSheenRoughness = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SHEEN_ROUGHNESS );
  11359. /**
  11360. * TSL object that represents the anisotropy of the current material.
  11361. *
  11362. * @tsl
  11363. * @type {Node<vec2>}
  11364. */
  11365. const materialAnisotropy = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.ANISOTROPY );
  11366. /**
  11367. * TSL object that represents the iridescence of the current material.
  11368. *
  11369. * @tsl
  11370. * @type {Node<float>}
  11371. */
  11372. const materialIridescence = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.IRIDESCENCE );
  11373. /**
  11374. * TSL object that represents the iridescence IOR of the current material.
  11375. *
  11376. * @tsl
  11377. * @type {Node<float>}
  11378. */
  11379. const materialIridescenceIOR = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.IRIDESCENCE_IOR );
  11380. /**
  11381. * TSL object that represents the iridescence thickness of the current material.
  11382. *
  11383. * @tsl
  11384. * @type {Node<float>}
  11385. */
  11386. const materialIridescenceThickness = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.IRIDESCENCE_THICKNESS );
  11387. /**
  11388. * TSL object that represents the transmission of the current material.
  11389. * The value is composed via `transmission` * `transmissionMap.r`.
  11390. *
  11391. * @tsl
  11392. * @type {Node<float>}
  11393. */
  11394. const materialTransmission = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.TRANSMISSION );
  11395. /**
  11396. * TSL object that represents the thickness of the current material.
  11397. * The value is composed via `thickness` * `thicknessMap.g`.
  11398. *
  11399. * @tsl
  11400. * @type {Node<float>}
  11401. */
  11402. const materialThickness = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.THICKNESS );
  11403. /**
  11404. * TSL object that represents the IOR of the current material.
  11405. *
  11406. * @tsl
  11407. * @type {Node<float>}
  11408. */
  11409. const materialIOR = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.IOR );
  11410. /**
  11411. * TSL object that represents the attenuation distance of the current material.
  11412. *
  11413. * @tsl
  11414. * @type {Node<float>}
  11415. */
  11416. const materialAttenuationDistance = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.ATTENUATION_DISTANCE );
  11417. /**
  11418. * TSL object that represents the attenuation color of the current material.
  11419. *
  11420. * @tsl
  11421. * @type {Node<vec3>}
  11422. */
  11423. const materialAttenuationColor = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.ATTENUATION_COLOR );
  11424. /**
  11425. * TSL object that represents the scale of the current dashed line material.
  11426. *
  11427. * @tsl
  11428. * @type {Node<float>}
  11429. */
  11430. const materialLineScale = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.LINE_SCALE );
  11431. /**
  11432. * TSL object that represents the dash size of the current dashed line material.
  11433. *
  11434. * @tsl
  11435. * @type {Node<float>}
  11436. */
  11437. const materialLineDashSize = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.LINE_DASH_SIZE );
  11438. /**
  11439. * TSL object that represents the gap size of the current dashed line material.
  11440. *
  11441. * @tsl
  11442. * @type {Node<float>}
  11443. */
  11444. const materialLineGapSize = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.LINE_GAP_SIZE );
  11445. /**
  11446. * TSL object that represents the line width of the current line material.
  11447. *
  11448. * @tsl
  11449. * @type {Node<float>}
  11450. */
  11451. const materialLineWidth = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.LINE_WIDTH );
  11452. /**
  11453. * TSL object that represents the dash offset of the current line material.
  11454. *
  11455. * @tsl
  11456. * @type {Node<float>}
  11457. */
  11458. const materialLineDashOffset = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.LINE_DASH_OFFSET );
  11459. /**
  11460. * TSL object that represents the point size of the current points material.
  11461. *
  11462. * @tsl
  11463. * @type {Node<float>}
  11464. */
  11465. const materialPointSize = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.POINT_SIZE );
  11466. /**
  11467. * TSL object that represents the dispersion of the current material.
  11468. *
  11469. * @tsl
  11470. * @type {Node<float>}
  11471. */
  11472. const materialDispersion = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.DISPERSION );
  11473. /**
  11474. * TSL object that represents the light map of the current material.
  11475. * The value is composed via `lightMapIntensity` * `lightMap.rgb`.
  11476. *
  11477. * @tsl
  11478. * @type {Node<vec3>}
  11479. */
  11480. const materialLightMap = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.LIGHT_MAP );
  11481. /**
  11482. * TSL object that represents the ambient occlusion map of the current material.
  11483. * The value is composed via `aoMap.r` - 1 * `aoMapIntensity` + 1.
  11484. *
  11485. * @tsl
  11486. * @type {Node<float>}
  11487. */
  11488. const materialAO = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.AO );
  11489. /**
  11490. * TSL object that represents the anisotropy vector of the current material.
  11491. *
  11492. * @tsl
  11493. * @type {Node<vec2>}
  11494. */
  11495. const materialAnisotropyVector = /*@__PURE__*/ uniform( new Vector2() ).onReference( function ( frame ) {
  11496. return frame.material;
  11497. } ).onRenderUpdate( function ( { material } ) {
  11498. this.value.set( material.anisotropy * Math.cos( material.anisotropyRotation ), material.anisotropy * Math.sin( material.anisotropyRotation ) );
  11499. } );
  11500. /**
  11501. * TSL object that represents the position in clip space after the model-view-projection transform of the current rendered object.
  11502. *
  11503. * @tsl
  11504. * @type {VaryingNode<vec4>}
  11505. */
  11506. const modelViewProjection = /*@__PURE__*/ ( Fn( ( builder ) => {
  11507. return builder.context.setupModelViewProjection();
  11508. }, 'vec4' ).once() )().toVarying( 'v_modelViewProjection' );
  11509. /**
  11510. * This class represents shader indices of different types. The following predefined node
  11511. * objects cover frequent use cases:
  11512. *
  11513. * - `vertexIndex`: The index of a vertex within a mesh.
  11514. * - `instanceIndex`: The index of either a mesh instance or an invocation of a compute shader.
  11515. * - `drawIndex`: The index of a draw call.
  11516. * - `invocationLocalIndex`: The index of a compute invocation within the scope of a workgroup load.
  11517. * - `invocationSubgroupIndex`: The index of a compute invocation within the scope of a subgroup.
  11518. * - `subgroupIndex`: The index of a compute invocation's subgroup within its workgroup.
  11519. *
  11520. * @augments Node
  11521. */
  11522. class IndexNode extends Node {
  11523. static get type() {
  11524. return 'IndexNode';
  11525. }
  11526. /**
  11527. * Constructs a new index node.
  11528. *
  11529. * @param {('vertex'|'instance'|'subgroup'|'invocationLocal'|'invocationGlobal'|'invocationSubgroup'|'draw')} scope - The scope of the index node.
  11530. */
  11531. constructor( scope ) {
  11532. super( 'uint' );
  11533. /**
  11534. * The scope of the index node.
  11535. *
  11536. * @type {string}
  11537. */
  11538. this.scope = scope;
  11539. /**
  11540. * This flag can be used for type testing.
  11541. *
  11542. * @type {boolean}
  11543. * @readonly
  11544. * @default true
  11545. */
  11546. this.isIndexNode = true;
  11547. }
  11548. generate( builder ) {
  11549. const nodeType = this.getNodeType( builder );
  11550. const scope = this.scope;
  11551. let propertyName;
  11552. if ( scope === IndexNode.VERTEX ) {
  11553. propertyName = builder.getVertexIndex();
  11554. } else if ( scope === IndexNode.INSTANCE ) {
  11555. propertyName = builder.getInstanceIndex();
  11556. } else if ( scope === IndexNode.DRAW ) {
  11557. propertyName = builder.getDrawIndex();
  11558. } else if ( scope === IndexNode.INVOCATION_LOCAL ) {
  11559. propertyName = builder.getInvocationLocalIndex();
  11560. } else if ( scope === IndexNode.INVOCATION_SUBGROUP ) {
  11561. propertyName = builder.getInvocationSubgroupIndex();
  11562. } else if ( scope === IndexNode.SUBGROUP ) {
  11563. propertyName = builder.getSubgroupIndex();
  11564. } else {
  11565. throw new Error( 'THREE.IndexNode: Unknown scope: ' + scope );
  11566. }
  11567. let output;
  11568. if ( builder.shaderStage === 'vertex' || builder.shaderStage === 'compute' ) {
  11569. output = propertyName;
  11570. } else {
  11571. const nodeVarying = varying( this );
  11572. output = nodeVarying.build( builder, nodeType );
  11573. }
  11574. return output;
  11575. }
  11576. }
  11577. IndexNode.VERTEX = 'vertex';
  11578. IndexNode.INSTANCE = 'instance';
  11579. IndexNode.SUBGROUP = 'subgroup';
  11580. IndexNode.INVOCATION_LOCAL = 'invocationLocal';
  11581. IndexNode.INVOCATION_SUBGROUP = 'invocationSubgroup';
  11582. IndexNode.DRAW = 'draw';
  11583. /**
  11584. * TSL object that represents the index of a vertex within a mesh.
  11585. *
  11586. * @tsl
  11587. * @type {IndexNode}
  11588. */
  11589. const vertexIndex = /*@__PURE__*/ nodeImmutable( IndexNode, IndexNode.VERTEX );
  11590. /**
  11591. * TSL object that represents the index of either a mesh instance or an invocation of a compute shader.
  11592. *
  11593. * @tsl
  11594. * @type {IndexNode}
  11595. */
  11596. const instanceIndex = /*@__PURE__*/ nodeImmutable( IndexNode, IndexNode.INSTANCE );
  11597. /**
  11598. * TSL object that represents the index of the subgroup the current compute invocation belongs to.
  11599. *
  11600. * @tsl
  11601. * @type {IndexNode}
  11602. */
  11603. const subgroupIndex = /*@__PURE__*/ nodeImmutable( IndexNode, IndexNode.SUBGROUP );
  11604. /**
  11605. * TSL object that represents the index of a compute invocation within the scope of a subgroup.
  11606. *
  11607. * @tsl
  11608. * @type {IndexNode}
  11609. */
  11610. const invocationSubgroupIndex = /*@__PURE__*/ nodeImmutable( IndexNode, IndexNode.INVOCATION_SUBGROUP );
  11611. /**
  11612. * TSL object that represents the index of a compute invocation within the scope of a workgroup load.
  11613. *
  11614. * @tsl
  11615. * @type {IndexNode}
  11616. */
  11617. const invocationLocalIndex = /*@__PURE__*/ nodeImmutable( IndexNode, IndexNode.INVOCATION_LOCAL );
  11618. /**
  11619. * TSL object that represents the index of a draw call.
  11620. *
  11621. * @tsl
  11622. * @type {IndexNode}
  11623. */
  11624. const drawIndex = /*@__PURE__*/ nodeImmutable( IndexNode, IndexNode.DRAW );
  11625. /**
  11626. * This node implements the vertex shader logic which is required
  11627. * when rendering 3D objects via instancing. The code makes sure
  11628. * vertex positions, normals and colors can be modified via instanced
  11629. * data.
  11630. *
  11631. * @augments Node
  11632. */
  11633. class InstanceNode extends Node {
  11634. static get type() {
  11635. return 'InstanceNode';
  11636. }
  11637. /**
  11638. * Constructs a new instance node.
  11639. *
  11640. * @param {number} count - The number of instances.
  11641. * @param {InstancedBufferAttribute} instanceMatrix - Instanced buffer attribute representing the instance transformations.
  11642. * @param {?InstancedBufferAttribute} instanceColor - Instanced buffer attribute representing the instance colors.
  11643. */
  11644. constructor( count, instanceMatrix, instanceColor = null ) {
  11645. super( 'void' );
  11646. /**
  11647. * The number of instances.
  11648. *
  11649. * @type {number}
  11650. */
  11651. this.count = count;
  11652. /**
  11653. * Instanced buffer attribute representing the transformation of instances.
  11654. *
  11655. * @type {InstancedBufferAttribute}
  11656. */
  11657. this.instanceMatrix = instanceMatrix;
  11658. /**
  11659. * Instanced buffer attribute representing the color of instances.
  11660. *
  11661. * @type {InstancedBufferAttribute}
  11662. */
  11663. this.instanceColor = instanceColor;
  11664. /**
  11665. * The node that represents the instance matrix data.
  11666. *
  11667. * @type {?Node}
  11668. */
  11669. this.instanceMatrixNode = null;
  11670. /**
  11671. * The node that represents the instance color data.
  11672. *
  11673. * @type {?Node}
  11674. * @default null
  11675. */
  11676. this.instanceColorNode = null;
  11677. /**
  11678. * The update type is set to `frame` since an update
  11679. * of instanced buffer data must be checked per frame.
  11680. *
  11681. * @type {string}
  11682. * @default 'frame'
  11683. */
  11684. this.updateType = NodeUpdateType.FRAME;
  11685. /**
  11686. * A reference to a buffer that is used by `instanceMatrixNode`.
  11687. *
  11688. * @type {?InstancedInterleavedBuffer}
  11689. */
  11690. this.buffer = null;
  11691. /**
  11692. * A reference to a buffer that is used by `instanceColorNode`.
  11693. *
  11694. * @type {?InstancedBufferAttribute}
  11695. */
  11696. this.bufferColor = null;
  11697. }
  11698. /**
  11699. * Setups the internal buffers and nodes and assigns the transformed vertex data
  11700. * to predefined node variables for accumulation. That follows the same patterns
  11701. * like with morph and skinning nodes.
  11702. *
  11703. * @param {NodeBuilder} builder - The current node builder.
  11704. */
  11705. setup( builder ) {
  11706. const { instanceMatrix, instanceColor } = this;
  11707. const { count } = instanceMatrix;
  11708. let { instanceMatrixNode, instanceColorNode } = this;
  11709. if ( instanceMatrixNode === null ) {
  11710. // 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.
  11711. if ( count <= 1000 ) {
  11712. instanceMatrixNode = buffer( instanceMatrix.array, 'mat4', Math.max( count, 1 ) ).element( instanceIndex );
  11713. } else {
  11714. const buffer = new InstancedInterleavedBuffer( instanceMatrix.array, 16, 1 );
  11715. const instancedBufferAttributeFn = instanceMatrix.usage === DynamicDrawUsage ? instancedDynamicBufferAttribute : instancedBufferAttribute;
  11716. instanceMatrixNode = instancedBufferAttributeFn( buffer, 'mat4' );
  11717. this.buffer = buffer;
  11718. }
  11719. this.instanceMatrixNode = instanceMatrixNode;
  11720. }
  11721. if ( instanceColor && instanceColorNode === null ) {
  11722. const buffer = new InstancedBufferAttribute( instanceColor.array, 3 );
  11723. const bufferFn = instanceColor.usage === DynamicDrawUsage ? instancedDynamicBufferAttribute : instancedBufferAttribute;
  11724. this.bufferColor = buffer;
  11725. instanceColorNode = vec3( bufferFn( buffer, 'vec3', 3, 0 ) );
  11726. this.instanceColorNode = instanceColorNode;
  11727. }
  11728. // POSITION
  11729. const instancePosition = instanceMatrixNode.mul( positionLocal ).xyz;
  11730. positionLocal.assign( instancePosition );
  11731. // NORMAL
  11732. if ( builder.hasGeometryAttribute( 'normal' ) ) {
  11733. const instanceNormal = transformNormal( normalLocal, instanceMatrixNode );
  11734. // ASSIGNS
  11735. normalLocal.assign( instanceNormal );
  11736. }
  11737. // COLOR
  11738. if ( this.instanceColorNode !== null ) {
  11739. varyingProperty( 'vec3', 'vInstanceColor' ).assign( this.instanceColorNode );
  11740. }
  11741. }
  11742. /**
  11743. * Checks if the internal buffers required an update.
  11744. *
  11745. * @param {NodeFrame} frame - The current node frame.
  11746. */
  11747. update( /*frame*/ ) {
  11748. if ( this.buffer !== null ) {
  11749. // keep update ranges in sync
  11750. this.buffer.clearUpdateRanges();
  11751. this.buffer.updateRanges.push( ... this.instanceMatrix.updateRanges );
  11752. // update version if necessary
  11753. if ( this.instanceMatrix.usage !== DynamicDrawUsage && this.instanceMatrix.version !== this.buffer.version ) {
  11754. this.buffer.version = this.instanceMatrix.version;
  11755. }
  11756. }
  11757. if ( this.instanceColor && this.bufferColor !== null ) {
  11758. this.bufferColor.clearUpdateRanges();
  11759. this.bufferColor.updateRanges.push( ... this.instanceColor.updateRanges );
  11760. if ( this.instanceColor.usage !== DynamicDrawUsage && this.instanceColor.version !== this.bufferColor.version ) {
  11761. this.bufferColor.version = this.instanceColor.version;
  11762. }
  11763. }
  11764. }
  11765. }
  11766. /**
  11767. * TSL function for creating an instance node.
  11768. *
  11769. * @tsl
  11770. * @function
  11771. * @param {number} count - The number of instances.
  11772. * @param {InstancedBufferAttribute} instanceMatrix - Instanced buffer attribute representing the instance transformations.
  11773. * @param {?InstancedBufferAttribute} instanceColor - Instanced buffer attribute representing the instance colors.
  11774. * @returns {InstanceNode}
  11775. */
  11776. const instance = /*@__PURE__*/ nodeProxy( InstanceNode ).setParameterLength( 2, 3 );
  11777. /**
  11778. * This is a special version of `InstanceNode` which requires the usage of {@link InstancedMesh}.
  11779. * It allows an easier setup of the instance node.
  11780. *
  11781. * @augments InstanceNode
  11782. */
  11783. class InstancedMeshNode extends InstanceNode {
  11784. static get type() {
  11785. return 'InstancedMeshNode';
  11786. }
  11787. /**
  11788. * Constructs a new instanced mesh node.
  11789. *
  11790. * @param {InstancedMesh} instancedMesh - The instanced mesh.
  11791. */
  11792. constructor( instancedMesh ) {
  11793. const { count, instanceMatrix, instanceColor } = instancedMesh;
  11794. super( count, instanceMatrix, instanceColor );
  11795. /**
  11796. * A reference to the instanced mesh.
  11797. *
  11798. * @type {InstancedMesh}
  11799. */
  11800. this.instancedMesh = instancedMesh;
  11801. }
  11802. }
  11803. /**
  11804. * TSL function for creating an instanced mesh node.
  11805. *
  11806. * @tsl
  11807. * @function
  11808. * @param {InstancedMesh} instancedMesh - The instancedMesh.
  11809. * @returns {InstancedMeshNode}
  11810. */
  11811. const instancedMesh = /*@__PURE__*/ nodeProxy( InstancedMeshNode ).setParameterLength( 1 );
  11812. /**
  11813. * This node implements the vertex shader logic which is required
  11814. * when rendering 3D objects via batching. `BatchNode` must be used
  11815. * with instances of {@link BatchedMesh}.
  11816. *
  11817. * @augments Node
  11818. */
  11819. class BatchNode extends Node {
  11820. static get type() {
  11821. return 'BatchNode';
  11822. }
  11823. /**
  11824. * Constructs a new batch node.
  11825. *
  11826. * @param {BatchedMesh} batchMesh - A reference to batched mesh.
  11827. */
  11828. constructor( batchMesh ) {
  11829. super( 'void' );
  11830. /**
  11831. * A reference to batched mesh.
  11832. *
  11833. * @type {BatchedMesh}
  11834. */
  11835. this.batchMesh = batchMesh;
  11836. /**
  11837. * The batching index node.
  11838. *
  11839. * @type {?IndexNode}
  11840. * @default null
  11841. */
  11842. this.batchingIdNode = null;
  11843. }
  11844. /**
  11845. * Setups the internal buffers and nodes and assigns the transformed vertex data
  11846. * to predefined node variables for accumulation. That follows the same patterns
  11847. * like with morph and skinning nodes.
  11848. *
  11849. * @param {NodeBuilder} builder - The current node builder.
  11850. */
  11851. setup( builder ) {
  11852. if ( this.batchingIdNode === null ) {
  11853. if ( builder.getDrawIndex() === null ) {
  11854. this.batchingIdNode = instanceIndex;
  11855. } else {
  11856. this.batchingIdNode = drawIndex;
  11857. }
  11858. }
  11859. const getIndirectIndex = Fn( ( [ id ] ) => {
  11860. const size = int( textureSize( textureLoad( this.batchMesh._indirectTexture ), 0 ).x ).toConst();
  11861. const x = int( id ).mod( size ).toConst();
  11862. const y = int( id ).div( size ).toConst();
  11863. return textureLoad( this.batchMesh._indirectTexture, ivec2( x, y ) ).x;
  11864. } ).setLayout( {
  11865. name: 'getIndirectIndex',
  11866. type: 'uint',
  11867. inputs: [
  11868. { name: 'id', type: 'int' }
  11869. ]
  11870. } );
  11871. const indirectId = getIndirectIndex( int( this.batchingIdNode ) );
  11872. const matricesTexture = this.batchMesh._matricesTexture;
  11873. const size = int( textureSize( textureLoad( matricesTexture ), 0 ).x ).toConst();
  11874. const j = float( indirectId ).mul( 4 ).toInt().toConst();
  11875. const x = j.mod( size ).toConst();
  11876. const y = j.div( size ).toConst();
  11877. const batchingMatrix = mat4(
  11878. textureLoad( matricesTexture, ivec2( x, y ) ),
  11879. textureLoad( matricesTexture, ivec2( x.add( 1 ), y ) ),
  11880. textureLoad( matricesTexture, ivec2( x.add( 2 ), y ) ),
  11881. textureLoad( matricesTexture, ivec2( x.add( 3 ), y ) )
  11882. );
  11883. const colorsTexture = this.batchMesh._colorsTexture;
  11884. if ( colorsTexture !== null ) {
  11885. const getBatchingColor = Fn( ( [ id ] ) => {
  11886. const size = int( textureSize( textureLoad( colorsTexture ), 0 ).x ).toConst();
  11887. const j = id;
  11888. const x = j.mod( size ).toConst();
  11889. const y = j.div( size ).toConst();
  11890. return textureLoad( colorsTexture, ivec2( x, y ) ).rgb;
  11891. } ).setLayout( {
  11892. name: 'getBatchingColor',
  11893. type: 'vec3',
  11894. inputs: [
  11895. { name: 'id', type: 'int' }
  11896. ]
  11897. } );
  11898. const color = getBatchingColor( indirectId );
  11899. varyingProperty( 'vec3', 'vBatchColor' ).assign( color );
  11900. }
  11901. const bm = mat3( batchingMatrix );
  11902. positionLocal.assign( batchingMatrix.mul( positionLocal ) );
  11903. const transformedNormal = normalLocal.div( vec3( bm[ 0 ].dot( bm[ 0 ] ), bm[ 1 ].dot( bm[ 1 ] ), bm[ 2 ].dot( bm[ 2 ] ) ) );
  11904. const batchingNormal = bm.mul( transformedNormal ).xyz;
  11905. normalLocal.assign( batchingNormal );
  11906. if ( builder.hasGeometryAttribute( 'tangent' ) ) {
  11907. tangentLocal.mulAssign( bm );
  11908. }
  11909. }
  11910. }
  11911. /**
  11912. * TSL function for creating a batch node.
  11913. *
  11914. * @tsl
  11915. * @function
  11916. * @param {BatchedMesh} batchMesh - A reference to batched mesh.
  11917. * @returns {BatchNode}
  11918. */
  11919. const batch = /*@__PURE__*/ nodeProxy( BatchNode ).setParameterLength( 1 );
  11920. /**
  11921. * This class enables element access on instances of {@link StorageBufferNode}.
  11922. * In most cases, it is indirectly used when accessing elements with the
  11923. * {@link StorageBufferNode#element} method.
  11924. *
  11925. * ```js
  11926. * const position = positionStorage.element( instanceIndex );
  11927. * ```
  11928. *
  11929. * @augments ArrayElementNode
  11930. */
  11931. class StorageArrayElementNode extends ArrayElementNode {
  11932. static get type() {
  11933. return 'StorageArrayElementNode';
  11934. }
  11935. /**
  11936. * Constructs storage buffer element node.
  11937. *
  11938. * @param {StorageBufferNode} storageBufferNode - The storage buffer node.
  11939. * @param {Node} indexNode - The index node that defines the element access.
  11940. */
  11941. constructor( storageBufferNode, indexNode ) {
  11942. super( storageBufferNode, indexNode );
  11943. /**
  11944. * This flag can be used for type testing.
  11945. *
  11946. * @type {boolean}
  11947. * @readonly
  11948. * @default true
  11949. */
  11950. this.isStorageArrayElementNode = true;
  11951. }
  11952. /**
  11953. * The storage buffer node.
  11954. *
  11955. * @param {Node} value
  11956. * @type {StorageBufferNode}
  11957. */
  11958. set storageBufferNode( value ) {
  11959. this.node = value;
  11960. }
  11961. get storageBufferNode() {
  11962. return this.node;
  11963. }
  11964. getMemberType( builder, name ) {
  11965. const structTypeNode = this.storageBufferNode.structTypeNode;
  11966. if ( structTypeNode ) {
  11967. return structTypeNode.getMemberType( builder, name );
  11968. }
  11969. return 'void';
  11970. }
  11971. setup( builder ) {
  11972. if ( builder.isAvailable( 'storageBuffer' ) === false ) {
  11973. if ( this.node.isPBO === true ) {
  11974. builder.setupPBO( this.node );
  11975. }
  11976. }
  11977. return super.setup( builder );
  11978. }
  11979. generate( builder, output ) {
  11980. let snippet;
  11981. const isAssignContext = builder.context.assign;
  11982. //
  11983. if ( builder.isAvailable( 'storageBuffer' ) === false ) {
  11984. if ( this.node.isPBO === true && isAssignContext !== true && ( this.node.value.isInstancedBufferAttribute || builder.shaderStage !== 'compute' ) ) {
  11985. snippet = builder.generatePBO( this );
  11986. } else {
  11987. snippet = this.node.build( builder );
  11988. }
  11989. } else {
  11990. snippet = super.generate( builder );
  11991. }
  11992. if ( isAssignContext !== true ) {
  11993. const type = this.getNodeType( builder );
  11994. snippet = builder.format( snippet, type, output );
  11995. }
  11996. return snippet;
  11997. }
  11998. }
  11999. /**
  12000. * TSL function for creating a storage element node.
  12001. *
  12002. * @tsl
  12003. * @function
  12004. * @param {StorageBufferNode} storageBufferNode - The storage buffer node.
  12005. * @param {Node} indexNode - The index node that defines the element access.
  12006. * @returns {StorageArrayElementNode}
  12007. */
  12008. const storageElement = /*@__PURE__*/ nodeProxy( StorageArrayElementNode ).setParameterLength( 2 );
  12009. /**
  12010. * This node is used in context of compute shaders and allows to define a
  12011. * storage buffer for data. A typical workflow is to create instances of
  12012. * this node with the convenience functions `attributeArray()` or `instancedArray()`,
  12013. * setup up a compute shader that writes into the buffers and then convert
  12014. * the storage buffers to attribute nodes for rendering.
  12015. *
  12016. * ```js
  12017. * const positionBuffer = instancedArray( particleCount, 'vec3' ); // the storage buffer node
  12018. *
  12019. * const computeInit = Fn( () => { // the compute shader
  12020. *
  12021. * const position = positionBuffer.element( instanceIndex );
  12022. *
  12023. * // compute position data
  12024. *
  12025. * position.x = 1;
  12026. * position.y = 1;
  12027. * position.z = 1;
  12028. *
  12029. * } )().compute( particleCount );
  12030. *
  12031. * const particleMaterial = new THREE.SpriteNodeMaterial();
  12032. * particleMaterial.positionNode = positionBuffer.toAttribute();
  12033. *
  12034. * renderer.computeAsync( computeInit );
  12035. *
  12036. * ```
  12037. *
  12038. * @augments BufferNode
  12039. */
  12040. class StorageBufferNode extends BufferNode {
  12041. static get type() {
  12042. return 'StorageBufferNode';
  12043. }
  12044. /**
  12045. * Constructs a new storage buffer node.
  12046. *
  12047. * @param {StorageBufferAttribute|StorageInstancedBufferAttribute|BufferAttribute} value - The buffer data.
  12048. * @param {?(string|Struct)} [bufferType=null] - The buffer type (e.g. `'vec3'`).
  12049. * @param {number} [bufferCount=0] - The buffer count.
  12050. */
  12051. constructor( value, bufferType = null, bufferCount = 0 ) {
  12052. let nodeType, structTypeNode = null;
  12053. if ( bufferType && bufferType.isStruct ) {
  12054. nodeType = 'struct';
  12055. structTypeNode = bufferType.layout;
  12056. if ( value.isStorageBufferAttribute || value.isStorageInstancedBufferAttribute ) {
  12057. bufferCount = value.count;
  12058. }
  12059. } else if ( bufferType === null && ( value.isStorageBufferAttribute || value.isStorageInstancedBufferAttribute ) ) {
  12060. nodeType = getTypeFromLength( value.itemSize );
  12061. bufferCount = value.count;
  12062. } else {
  12063. nodeType = bufferType;
  12064. }
  12065. super( value, nodeType, bufferCount );
  12066. /**
  12067. * This flag can be used for type testing.
  12068. *
  12069. * @type {boolean}
  12070. * @readonly
  12071. * @default true
  12072. */
  12073. this.isStorageBufferNode = true;
  12074. /**
  12075. * The buffer struct type.
  12076. *
  12077. * @type {?StructTypeNode}
  12078. * @default null
  12079. */
  12080. this.structTypeNode = structTypeNode;
  12081. /**
  12082. * The access type of the texture node.
  12083. *
  12084. * @type {string}
  12085. * @default 'readWrite'
  12086. */
  12087. this.access = NodeAccess.READ_WRITE;
  12088. /**
  12089. * Whether the node is atomic or not.
  12090. *
  12091. * @type {boolean}
  12092. * @default false
  12093. */
  12094. this.isAtomic = false;
  12095. /**
  12096. * Whether the node represents a PBO or not.
  12097. * Only relevant for WebGL.
  12098. *
  12099. * @type {boolean}
  12100. * @default false
  12101. */
  12102. this.isPBO = false;
  12103. /**
  12104. * A reference to the internal buffer attribute node.
  12105. *
  12106. * @private
  12107. * @type {?BufferAttributeNode}
  12108. * @default null
  12109. */
  12110. this._attribute = null;
  12111. /**
  12112. * A reference to the internal varying node.
  12113. *
  12114. * @private
  12115. * @type {?VaryingNode}
  12116. * @default null
  12117. */
  12118. this._varying = null;
  12119. /**
  12120. * `StorageBufferNode` sets this property to `true` by default.
  12121. *
  12122. * @type {boolean}
  12123. * @default true
  12124. */
  12125. this.global = true;
  12126. if ( value.isStorageBufferAttribute !== true && value.isStorageInstancedBufferAttribute !== true ) {
  12127. // TODO: Improve it, possibly adding a new property to the BufferAttribute to identify it as a storage buffer read-only attribute in Renderer
  12128. if ( value.isInstancedBufferAttribute ) value.isStorageInstancedBufferAttribute = true;
  12129. else value.isStorageBufferAttribute = true;
  12130. }
  12131. }
  12132. /**
  12133. * This method is overwritten since the buffer data might be shared
  12134. * and thus the hash should be shared as well.
  12135. *
  12136. * @param {NodeBuilder} builder - The current node builder.
  12137. * @return {string} The hash.
  12138. */
  12139. getHash( builder ) {
  12140. if ( this.bufferCount === 0 ) {
  12141. let bufferData = builder.globalCache.getData( this.value );
  12142. if ( bufferData === undefined ) {
  12143. bufferData = {
  12144. node: this
  12145. };
  12146. builder.globalCache.setData( this.value, bufferData );
  12147. }
  12148. return bufferData.node.uuid;
  12149. }
  12150. return this.uuid;
  12151. }
  12152. /**
  12153. * Overwrites the default implementation to return a fixed value `'indirectStorageBuffer'` or `'storageBuffer'`.
  12154. *
  12155. * @param {NodeBuilder} builder - The current node builder.
  12156. * @return {string} The input type.
  12157. */
  12158. getInputType( /*builder*/ ) {
  12159. return this.value.isIndirectStorageBufferAttribute ? 'indirectStorageBuffer' : 'storageBuffer';
  12160. }
  12161. /**
  12162. * Enables element access with the given index node.
  12163. *
  12164. * @param {IndexNode} indexNode - The index node.
  12165. * @return {StorageArrayElementNode} A node representing the element access.
  12166. */
  12167. element( indexNode ) {
  12168. return storageElement( this, indexNode );
  12169. }
  12170. /**
  12171. * Defines whether this node is a PBO or not. Only relevant for WebGL.
  12172. *
  12173. * @param {boolean} value - The value so set.
  12174. * @return {StorageBufferNode} A reference to this node.
  12175. */
  12176. setPBO( value ) {
  12177. this.isPBO = value;
  12178. return this;
  12179. }
  12180. /**
  12181. * Returns the `isPBO` value.
  12182. *
  12183. * @return {boolean} Whether the node represents a PBO or not.
  12184. */
  12185. getPBO() {
  12186. return this.isPBO;
  12187. }
  12188. /**
  12189. * Defines the node access.
  12190. *
  12191. * @param {string} value - The node access.
  12192. * @return {StorageBufferNode} A reference to this node.
  12193. */
  12194. setAccess( value ) {
  12195. this.access = value;
  12196. return this;
  12197. }
  12198. /**
  12199. * Convenience method for configuring a read-only node access.
  12200. *
  12201. * @return {StorageBufferNode} A reference to this node.
  12202. */
  12203. toReadOnly() {
  12204. return this.setAccess( NodeAccess.READ_ONLY );
  12205. }
  12206. /**
  12207. * Defines whether the node is atomic or not.
  12208. *
  12209. * @param {boolean} value - The atomic flag.
  12210. * @return {StorageBufferNode} A reference to this node.
  12211. */
  12212. setAtomic( value ) {
  12213. this.isAtomic = value;
  12214. return this;
  12215. }
  12216. /**
  12217. * Convenience method for making this node atomic.
  12218. *
  12219. * @return {StorageBufferNode} A reference to this node.
  12220. */
  12221. toAtomic() {
  12222. return this.setAtomic( true );
  12223. }
  12224. /**
  12225. * Returns attribute data for this storage buffer node.
  12226. *
  12227. * @return {{attribute: BufferAttributeNode, varying: VaryingNode}} The attribute data.
  12228. */
  12229. getAttributeData() {
  12230. if ( this._attribute === null ) {
  12231. this._attribute = bufferAttribute( this.value );
  12232. this._varying = varying( this._attribute );
  12233. }
  12234. return {
  12235. attribute: this._attribute,
  12236. varying: this._varying
  12237. };
  12238. }
  12239. /**
  12240. * This method is overwritten since the node type from the availability of storage buffers
  12241. * and the attribute data.
  12242. *
  12243. * @param {NodeBuilder} builder - The current node builder.
  12244. * @return {string} The node type.
  12245. */
  12246. getNodeType( builder ) {
  12247. if ( this.structTypeNode !== null ) {
  12248. return this.structTypeNode.getNodeType( builder );
  12249. }
  12250. if ( builder.isAvailable( 'storageBuffer' ) || builder.isAvailable( 'indirectStorageBuffer' ) ) {
  12251. return super.getNodeType( builder );
  12252. }
  12253. const { attribute } = this.getAttributeData();
  12254. return attribute.getNodeType( builder );
  12255. }
  12256. /**
  12257. * Returns the type of a member of the struct.
  12258. *
  12259. * @param {NodeBuilder} builder - The current node builder.
  12260. * @param {string} name - The name of the member.
  12261. * @return {string} The type of the member.
  12262. */
  12263. getMemberType( builder, name ) {
  12264. if ( this.structTypeNode !== null ) {
  12265. return this.structTypeNode.getMemberType( builder, name );
  12266. }
  12267. return 'void';
  12268. }
  12269. /**
  12270. * Generates the code snippet of the storage buffer node.
  12271. *
  12272. * @param {NodeBuilder} builder - The current node builder.
  12273. * @return {string} The generated code snippet.
  12274. */
  12275. generate( builder ) {
  12276. if ( this.structTypeNode !== null ) this.structTypeNode.build( builder );
  12277. if ( builder.isAvailable( 'storageBuffer' ) || builder.isAvailable( 'indirectStorageBuffer' ) ) {
  12278. return super.generate( builder );
  12279. }
  12280. const { attribute, varying } = this.getAttributeData();
  12281. const output = varying.build( builder );
  12282. builder.registerTransform( output, attribute );
  12283. return output;
  12284. }
  12285. }
  12286. /**
  12287. * TSL function for creating a storage buffer node.
  12288. *
  12289. * @tsl
  12290. * @function
  12291. * @param {StorageBufferAttribute|StorageInstancedBufferAttribute|BufferAttribute} value - The buffer data.
  12292. * @param {?(string|Struct)} [type=null] - The buffer type (e.g. `'vec3'`).
  12293. * @param {number} [count=0] - The buffer count.
  12294. * @returns {StorageBufferNode}
  12295. */
  12296. const storage = ( value, type = null, count = 0 ) => nodeObject( new StorageBufferNode( value, type, count ) );
  12297. /**
  12298. * @tsl
  12299. * @function
  12300. * @deprecated since r171. Use `storage().setPBO( true )` instead.
  12301. *
  12302. * @param {StorageBufferAttribute|StorageInstancedBufferAttribute|BufferAttribute} value - The buffer data.
  12303. * @param {?string} type - The buffer type (e.g. `'vec3'`).
  12304. * @param {number} count - The buffer count.
  12305. * @returns {StorageBufferNode}
  12306. */
  12307. const storageObject = ( value, type, count ) => { // @deprecated, r171
  12308. warn( 'TSL: "storageObject()" is deprecated. Use "storage().setPBO( true )" instead.' );
  12309. return storage( value, type, count ).setPBO( true );
  12310. };
  12311. const _frameId = new WeakMap();
  12312. /**
  12313. * This node implements the vertex transformation shader logic which is required
  12314. * for skinning/skeletal animation.
  12315. *
  12316. * @augments Node
  12317. */
  12318. class SkinningNode extends Node {
  12319. static get type() {
  12320. return 'SkinningNode';
  12321. }
  12322. /**
  12323. * Constructs a new skinning node.
  12324. *
  12325. * @param {SkinnedMesh} skinnedMesh - The skinned mesh.
  12326. */
  12327. constructor( skinnedMesh ) {
  12328. super( 'void' );
  12329. /**
  12330. * The skinned mesh.
  12331. *
  12332. * @type {SkinnedMesh}
  12333. */
  12334. this.skinnedMesh = skinnedMesh;
  12335. /**
  12336. * The update type overwritten since skinning nodes are updated per object.
  12337. *
  12338. * @type {string}
  12339. */
  12340. this.updateType = NodeUpdateType.OBJECT;
  12341. //
  12342. /**
  12343. * The skin index attribute.
  12344. *
  12345. * @type {AttributeNode}
  12346. */
  12347. this.skinIndexNode = attribute( 'skinIndex', 'uvec4' );
  12348. /**
  12349. * The skin weight attribute.
  12350. *
  12351. * @type {AttributeNode}
  12352. */
  12353. this.skinWeightNode = attribute( 'skinWeight', 'vec4' );
  12354. /**
  12355. * The bind matrix node.
  12356. *
  12357. * @type {Node<mat4>}
  12358. */
  12359. this.bindMatrixNode = reference( 'bindMatrix', 'mat4' );
  12360. /**
  12361. * The bind matrix inverse node.
  12362. *
  12363. * @type {Node<mat4>}
  12364. */
  12365. this.bindMatrixInverseNode = reference( 'bindMatrixInverse', 'mat4' );
  12366. /**
  12367. * The bind matrices as a uniform buffer node.
  12368. *
  12369. * @type {Node}
  12370. */
  12371. this.boneMatricesNode = referenceBuffer( 'skeleton.boneMatrices', 'mat4', skinnedMesh.skeleton.bones.length );
  12372. /**
  12373. * The current vertex position in local space.
  12374. *
  12375. * @type {Node<vec3>}
  12376. */
  12377. this.positionNode = positionLocal;
  12378. /**
  12379. * The result of vertex position in local space.
  12380. *
  12381. * @type {Node<vec3>}
  12382. */
  12383. this.toPositionNode = positionLocal;
  12384. /**
  12385. * The previous bind matrices as a uniform buffer node.
  12386. * Required for computing motion vectors.
  12387. *
  12388. * @type {?Node}
  12389. * @default null
  12390. */
  12391. this.previousBoneMatricesNode = null;
  12392. }
  12393. /**
  12394. * Transforms the given vertex position via skinning.
  12395. *
  12396. * @param {Node} [boneMatrices=this.boneMatricesNode] - The bone matrices
  12397. * @param {Node<vec3>} [position=this.positionNode] - The vertex position in local space.
  12398. * @return {Node<vec3>} The transformed vertex position.
  12399. */
  12400. getSkinnedPosition( boneMatrices = this.boneMatricesNode, position = this.positionNode ) {
  12401. const { skinIndexNode, skinWeightNode, bindMatrixNode, bindMatrixInverseNode } = this;
  12402. const boneMatX = boneMatrices.element( skinIndexNode.x );
  12403. const boneMatY = boneMatrices.element( skinIndexNode.y );
  12404. const boneMatZ = boneMatrices.element( skinIndexNode.z );
  12405. const boneMatW = boneMatrices.element( skinIndexNode.w );
  12406. // POSITION
  12407. const skinVertex = bindMatrixNode.mul( position );
  12408. const skinned = add(
  12409. boneMatX.mul( skinWeightNode.x ).mul( skinVertex ),
  12410. boneMatY.mul( skinWeightNode.y ).mul( skinVertex ),
  12411. boneMatZ.mul( skinWeightNode.z ).mul( skinVertex ),
  12412. boneMatW.mul( skinWeightNode.w ).mul( skinVertex )
  12413. );
  12414. return bindMatrixInverseNode.mul( skinned ).xyz;
  12415. }
  12416. /**
  12417. * Transforms the given vertex normal via skinning.
  12418. *
  12419. * @param {Node} [boneMatrices=this.boneMatricesNode] - The bone matrices
  12420. * @param {Node<vec3>} [normal=normalLocal] - The vertex normal in local space.
  12421. * @return {Node<vec3>} The transformed vertex normal.
  12422. */
  12423. getSkinnedNormal( boneMatrices = this.boneMatricesNode, normal = normalLocal ) {
  12424. const { skinIndexNode, skinWeightNode, bindMatrixNode, bindMatrixInverseNode } = this;
  12425. const boneMatX = boneMatrices.element( skinIndexNode.x );
  12426. const boneMatY = boneMatrices.element( skinIndexNode.y );
  12427. const boneMatZ = boneMatrices.element( skinIndexNode.z );
  12428. const boneMatW = boneMatrices.element( skinIndexNode.w );
  12429. // NORMAL
  12430. let skinMatrix = add(
  12431. skinWeightNode.x.mul( boneMatX ),
  12432. skinWeightNode.y.mul( boneMatY ),
  12433. skinWeightNode.z.mul( boneMatZ ),
  12434. skinWeightNode.w.mul( boneMatW )
  12435. );
  12436. skinMatrix = bindMatrixInverseNode.mul( skinMatrix ).mul( bindMatrixNode );
  12437. return skinMatrix.transformDirection( normal ).xyz;
  12438. }
  12439. /**
  12440. * Computes the transformed/skinned vertex position of the previous frame.
  12441. *
  12442. * @param {NodeBuilder} builder - The current node builder.
  12443. * @return {Node<vec3>} The skinned position from the previous frame.
  12444. */
  12445. getPreviousSkinnedPosition( builder ) {
  12446. const skinnedMesh = builder.object;
  12447. if ( this.previousBoneMatricesNode === null ) {
  12448. skinnedMesh.skeleton.previousBoneMatrices = new Float32Array( skinnedMesh.skeleton.boneMatrices );
  12449. this.previousBoneMatricesNode = referenceBuffer( 'skeleton.previousBoneMatrices', 'mat4', skinnedMesh.skeleton.bones.length );
  12450. }
  12451. return this.getSkinnedPosition( this.previousBoneMatricesNode, positionPrevious );
  12452. }
  12453. /**
  12454. * Returns `true` if bone matrices from the previous frame are required. Relevant
  12455. * when computing motion vectors with {@link VelocityNode}.
  12456. *
  12457. * @param {NodeBuilder} builder - The current node builder.
  12458. * @return {boolean} Whether bone matrices from the previous frame are required or not.
  12459. */
  12460. needsPreviousBoneMatrices( builder ) {
  12461. const mrt = builder.renderer.getMRT();
  12462. return ( mrt && mrt.has( 'velocity' ) ) || getDataFromObject( builder.object ).useVelocity === true;
  12463. }
  12464. /**
  12465. * Setups the skinning node by assigning the transformed vertex data to predefined node variables.
  12466. *
  12467. * @param {NodeBuilder} builder - The current node builder.
  12468. * @return {Node<vec3>} The transformed vertex position.
  12469. */
  12470. setup( builder ) {
  12471. if ( this.needsPreviousBoneMatrices( builder ) ) {
  12472. positionPrevious.assign( this.getPreviousSkinnedPosition( builder ) );
  12473. }
  12474. const skinPosition = this.getSkinnedPosition();
  12475. if ( this.toPositionNode ) this.toPositionNode.assign( skinPosition );
  12476. //
  12477. if ( builder.hasGeometryAttribute( 'normal' ) ) {
  12478. const skinNormal = this.getSkinnedNormal();
  12479. normalLocal.assign( skinNormal );
  12480. if ( builder.hasGeometryAttribute( 'tangent' ) ) {
  12481. tangentLocal.assign( skinNormal );
  12482. }
  12483. }
  12484. return skinPosition;
  12485. }
  12486. /**
  12487. * Generates the code snippet of the skinning node.
  12488. *
  12489. * @param {NodeBuilder} builder - The current node builder.
  12490. * @param {string} output - The current output.
  12491. * @return {string} The generated code snippet.
  12492. */
  12493. generate( builder, output ) {
  12494. if ( output !== 'void' ) {
  12495. return super.generate( builder, output );
  12496. }
  12497. }
  12498. /**
  12499. * Updates the state of the skinned mesh by updating the skeleton once per frame.
  12500. *
  12501. * @param {NodeFrame} frame - The current node frame.
  12502. */
  12503. update( frame ) {
  12504. const skeleton = frame.object && frame.object.skeleton ? frame.object.skeleton : this.skinnedMesh.skeleton;
  12505. if ( _frameId.get( skeleton ) === frame.frameId ) return;
  12506. _frameId.set( skeleton, frame.frameId );
  12507. if ( this.previousBoneMatricesNode !== null ) skeleton.previousBoneMatrices.set( skeleton.boneMatrices );
  12508. skeleton.update();
  12509. }
  12510. }
  12511. /**
  12512. * TSL function for creating a skinning node.
  12513. *
  12514. * @tsl
  12515. * @function
  12516. * @param {SkinnedMesh} skinnedMesh - The skinned mesh.
  12517. * @returns {SkinningNode}
  12518. */
  12519. const skinning = ( skinnedMesh ) => nodeObject( new SkinningNode( skinnedMesh ) );
  12520. /**
  12521. * TSL function for computing skinning.
  12522. *
  12523. * @tsl
  12524. * @function
  12525. * @param {SkinnedMesh} skinnedMesh - The skinned mesh.
  12526. * @param {Node<vec3>} [toPosition=null] - The target position.
  12527. * @returns {SkinningNode}
  12528. */
  12529. const computeSkinning = ( skinnedMesh, toPosition = null ) => {
  12530. const node = new SkinningNode( skinnedMesh );
  12531. node.positionNode = storage( new InstancedBufferAttribute( skinnedMesh.geometry.getAttribute( 'position' ).array, 3 ), 'vec3' ).setPBO( true ).toReadOnly().element( instanceIndex ).toVar();
  12532. node.skinIndexNode = storage( new InstancedBufferAttribute( new Uint32Array( skinnedMesh.geometry.getAttribute( 'skinIndex' ).array ), 4 ), 'uvec4' ).setPBO( true ).toReadOnly().element( instanceIndex ).toVar();
  12533. node.skinWeightNode = storage( new InstancedBufferAttribute( skinnedMesh.geometry.getAttribute( 'skinWeight' ).array, 4 ), 'vec4' ).setPBO( true ).toReadOnly().element( instanceIndex ).toVar();
  12534. node.bindMatrixNode = uniform( skinnedMesh.bindMatrix, 'mat4' );
  12535. node.bindMatrixInverseNode = uniform( skinnedMesh.bindMatrixInverse, 'mat4' );
  12536. node.boneMatricesNode = buffer( skinnedMesh.skeleton.boneMatrices, 'mat4', skinnedMesh.skeleton.bones.length );
  12537. node.toPositionNode = toPosition;
  12538. return nodeObject( node );
  12539. };
  12540. /**
  12541. * This module offers a variety of ways to implement loops in TSL. In it's basic form it's:
  12542. * ```js
  12543. * Loop( count, ( { i } ) => {
  12544. *
  12545. * } );
  12546. * ```
  12547. * However, it is also possible to define a start and end ranges, data types and loop conditions:
  12548. * ```js
  12549. * Loop( { start: int( 0 ), end: int( 10 ), type: 'int', condition: '<' }, ( { i } ) => {
  12550. *
  12551. * } );
  12552. *```
  12553. * Nested loops can be defined in a compacted form:
  12554. * ```js
  12555. * Loop( 10, 5, ( { i, j } ) => {
  12556. *
  12557. * } );
  12558. * ```
  12559. * Loops that should run backwards can be defined like so:
  12560. * ```js
  12561. * Loop( { start: 10 }, () => {} );
  12562. * ```
  12563. * It is possible to execute with boolean values, similar to the `while` syntax.
  12564. * ```js
  12565. * const value = float( 0 ).toVar();
  12566. *
  12567. * Loop( value.lessThan( 10 ), () => {
  12568. *
  12569. * value.addAssign( 1 );
  12570. *
  12571. * } );
  12572. * ```
  12573. * The module also provides `Break()` and `Continue()` TSL expression for loop control.
  12574. * @augments Node
  12575. */
  12576. class LoopNode extends Node {
  12577. static get type() {
  12578. return 'LoopNode';
  12579. }
  12580. /**
  12581. * Constructs a new loop node.
  12582. *
  12583. * @param {Array<any>} params - Depending on the loop type, array holds different parameterization values for the loop.
  12584. */
  12585. constructor( params = [] ) {
  12586. super( 'void' );
  12587. this.params = params;
  12588. }
  12589. /**
  12590. * Returns a loop variable name based on an index. The pattern is
  12591. * `0` = `i`, `1`= `j`, `2`= `k` and so on.
  12592. *
  12593. * @param {number} index - The index.
  12594. * @return {string} The loop variable name.
  12595. */
  12596. getVarName( index ) {
  12597. return String.fromCharCode( 'i'.charCodeAt( 0 ) + index );
  12598. }
  12599. /**
  12600. * Returns properties about this node.
  12601. *
  12602. * @param {NodeBuilder} builder - The current node builder.
  12603. * @return {Object} The node properties.
  12604. */
  12605. getProperties( builder ) {
  12606. const properties = builder.getNodeProperties( this );
  12607. if ( properties.stackNode !== undefined ) return properties;
  12608. //
  12609. const inputs = {};
  12610. for ( let i = 0, l = this.params.length - 1; i < l; i ++ ) {
  12611. const param = this.params[ i ];
  12612. const name = ( param.isNode !== true && param.name ) || this.getVarName( i );
  12613. const type = ( param.isNode !== true && param.type ) || 'int';
  12614. inputs[ name ] = expression( name, type );
  12615. }
  12616. const stack = builder.addStack();
  12617. const fnCall = this.params[ this.params.length - 1 ]( inputs );
  12618. properties.returnsNode = fnCall.context( { nodeLoop: fnCall } );
  12619. properties.stackNode = stack;
  12620. const baseParam = this.params[ 0 ];
  12621. if ( baseParam.isNode !== true && typeof baseParam.update === 'function' ) {
  12622. const fnUpdateCall = Fn( this.params[ 0 ].update )( inputs );
  12623. properties.updateNode = fnUpdateCall.context( { nodeLoop: fnUpdateCall } );
  12624. }
  12625. builder.removeStack();
  12626. return properties;
  12627. }
  12628. setup( builder ) {
  12629. // setup properties
  12630. this.getProperties( builder );
  12631. if ( builder.fnCall ) {
  12632. const shaderNodeData = builder.getDataFromNode( builder.fnCall.shaderNode );
  12633. shaderNodeData.hasLoop = true;
  12634. }
  12635. }
  12636. generate( builder ) {
  12637. const properties = this.getProperties( builder );
  12638. const params = this.params;
  12639. const stackNode = properties.stackNode;
  12640. for ( let i = 0, l = params.length - 1; i < l; i ++ ) {
  12641. const param = params[ i ];
  12642. let isWhile = false, start = null, end = null, name = null, type = null, condition = null, update = null;
  12643. if ( param.isNode ) {
  12644. if ( param.getNodeType( builder ) === 'bool' ) {
  12645. isWhile = true;
  12646. type = 'bool';
  12647. end = param.build( builder, type );
  12648. } else {
  12649. type = 'int';
  12650. name = this.getVarName( i );
  12651. start = '0';
  12652. end = param.build( builder, type );
  12653. condition = '<';
  12654. }
  12655. } else {
  12656. type = param.type || 'int';
  12657. name = param.name || this.getVarName( i );
  12658. start = param.start;
  12659. end = param.end;
  12660. condition = param.condition;
  12661. update = param.update;
  12662. if ( typeof start === 'number' ) start = builder.generateConst( type, start );
  12663. else if ( start && start.isNode ) start = start.build( builder, type );
  12664. if ( typeof end === 'number' ) end = builder.generateConst( type, end );
  12665. else if ( end && end.isNode ) end = end.build( builder, type );
  12666. if ( start !== undefined && end === undefined ) {
  12667. start = start + ' - 1';
  12668. end = '0';
  12669. condition = '>=';
  12670. } else if ( end !== undefined && start === undefined ) {
  12671. start = '0';
  12672. condition = '<';
  12673. }
  12674. if ( condition === undefined ) {
  12675. if ( Number( start ) > Number( end ) ) {
  12676. condition = '>=';
  12677. } else {
  12678. condition = '<';
  12679. }
  12680. }
  12681. }
  12682. let loopSnippet;
  12683. if ( isWhile ) {
  12684. loopSnippet = `while ( ${ end } )`;
  12685. } else {
  12686. const internalParam = { start, end};
  12687. //
  12688. const startSnippet = internalParam.start;
  12689. const endSnippet = internalParam.end;
  12690. let updateSnippet;
  12691. const deltaOperator = () => condition.includes( '<' ) ? '+=' : '-=';
  12692. if ( update !== undefined && update !== null ) {
  12693. switch ( typeof update ) {
  12694. case 'function':
  12695. const flow = builder.flowStagesNode( properties.updateNode, 'void' );
  12696. const snippet = flow.code.replace( /\t|;/g, '' );
  12697. updateSnippet = snippet;
  12698. break;
  12699. case 'number':
  12700. updateSnippet = name + ' ' + deltaOperator() + ' ' + builder.generateConst( type, update );
  12701. break;
  12702. case 'string':
  12703. updateSnippet = name + ' ' + update;
  12704. break;
  12705. default:
  12706. if ( update.isNode ) {
  12707. updateSnippet = name + ' ' + deltaOperator() + ' ' + update.build( builder );
  12708. } else {
  12709. error( 'TSL: \'Loop( { update: ... } )\' is not a function, string or number.' );
  12710. updateSnippet = 'break /* invalid update */';
  12711. }
  12712. }
  12713. } else {
  12714. if ( type === 'int' || type === 'uint' ) {
  12715. update = condition.includes( '<' ) ? '++' : '--';
  12716. } else {
  12717. update = deltaOperator() + ' 1.';
  12718. }
  12719. updateSnippet = name + ' ' + update;
  12720. }
  12721. const declarationSnippet = builder.getVar( type, name ) + ' = ' + startSnippet;
  12722. const conditionalSnippet = name + ' ' + condition + ' ' + endSnippet;
  12723. loopSnippet = `for ( ${ declarationSnippet }; ${ conditionalSnippet }; ${ updateSnippet } )`;
  12724. }
  12725. builder.addFlowCode( ( i === 0 ? '\n' : '' ) + builder.tab + loopSnippet + ' {\n\n' ).addFlowTab();
  12726. }
  12727. const stackSnippet = stackNode.build( builder, 'void' );
  12728. properties.returnsNode.build( builder, 'void' );
  12729. builder.removeFlowTab().addFlowCode( '\n' + builder.tab + stackSnippet );
  12730. for ( let i = 0, l = this.params.length - 1; i < l; i ++ ) {
  12731. builder.addFlowCode( ( i === 0 ? '' : builder.tab ) + '}\n\n' ).removeFlowTab();
  12732. }
  12733. builder.addFlowTab();
  12734. }
  12735. }
  12736. /**
  12737. * TSL function for creating a loop node.
  12738. *
  12739. * @tsl
  12740. * @function
  12741. * @param {...any} params - A list of parameters.
  12742. * @returns {LoopNode}
  12743. */
  12744. const Loop = ( ...params ) => new LoopNode( nodeArray( params, 'int' ) ).toStack();
  12745. /**
  12746. * TSL function for creating a `Continue()` expression.
  12747. *
  12748. * @tsl
  12749. * @function
  12750. * @returns {ExpressionNode}
  12751. */
  12752. const Continue = () => expression( 'continue' ).toStack();
  12753. /**
  12754. * TSL function for creating a `Break()` expression.
  12755. *
  12756. * @tsl
  12757. * @function
  12758. * @returns {ExpressionNode}
  12759. */
  12760. const Break = () => expression( 'break' ).toStack();
  12761. const _morphTextures = /*@__PURE__*/ new WeakMap();
  12762. const _morphVec4 = /*@__PURE__*/ new Vector4();
  12763. const getMorph = /*@__PURE__*/ Fn( ( { bufferMap, influence, stride, width, depth, offset } ) => {
  12764. const texelIndex = int( vertexIndex ).mul( stride ).add( offset );
  12765. const y = texelIndex.div( width );
  12766. const x = texelIndex.sub( y.mul( width ) );
  12767. const bufferAttrib = textureLoad( bufferMap, ivec2( x, y ) ).depth( depth ).xyz;
  12768. return bufferAttrib.mul( influence );
  12769. } );
  12770. function getEntry( geometry ) {
  12771. const hasMorphPosition = geometry.morphAttributes.position !== undefined;
  12772. const hasMorphNormals = geometry.morphAttributes.normal !== undefined;
  12773. const hasMorphColors = geometry.morphAttributes.color !== undefined;
  12774. // instead of using attributes, the WebGL 2 code path encodes morph targets
  12775. // into an array of data textures. Each layer represents a single morph target.
  12776. const morphAttribute = geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color;
  12777. const morphTargetsCount = ( morphAttribute !== undefined ) ? morphAttribute.length : 0;
  12778. let entry = _morphTextures.get( geometry );
  12779. if ( entry === undefined || entry.count !== morphTargetsCount ) {
  12780. if ( entry !== undefined ) entry.texture.dispose();
  12781. const morphTargets = geometry.morphAttributes.position || [];
  12782. const morphNormals = geometry.morphAttributes.normal || [];
  12783. const morphColors = geometry.morphAttributes.color || [];
  12784. let vertexDataCount = 0;
  12785. if ( hasMorphPosition === true ) vertexDataCount = 1;
  12786. if ( hasMorphNormals === true ) vertexDataCount = 2;
  12787. if ( hasMorphColors === true ) vertexDataCount = 3;
  12788. let width = geometry.attributes.position.count * vertexDataCount;
  12789. let height = 1;
  12790. const maxTextureSize = 4096; // @TODO: Use 'capabilities.maxTextureSize'
  12791. if ( width > maxTextureSize ) {
  12792. height = Math.ceil( width / maxTextureSize );
  12793. width = maxTextureSize;
  12794. }
  12795. const buffer = new Float32Array( width * height * 4 * morphTargetsCount );
  12796. const bufferTexture = new DataArrayTexture( buffer, width, height, morphTargetsCount );
  12797. bufferTexture.type = FloatType;
  12798. bufferTexture.needsUpdate = true;
  12799. // fill buffer
  12800. const vertexDataStride = vertexDataCount * 4;
  12801. for ( let i = 0; i < morphTargetsCount; i ++ ) {
  12802. const morphTarget = morphTargets[ i ];
  12803. const morphNormal = morphNormals[ i ];
  12804. const morphColor = morphColors[ i ];
  12805. const offset = width * height * 4 * i;
  12806. for ( let j = 0; j < morphTarget.count; j ++ ) {
  12807. const stride = j * vertexDataStride;
  12808. if ( hasMorphPosition === true ) {
  12809. _morphVec4.fromBufferAttribute( morphTarget, j );
  12810. buffer[ offset + stride + 0 ] = _morphVec4.x;
  12811. buffer[ offset + stride + 1 ] = _morphVec4.y;
  12812. buffer[ offset + stride + 2 ] = _morphVec4.z;
  12813. buffer[ offset + stride + 3 ] = 0;
  12814. }
  12815. if ( hasMorphNormals === true ) {
  12816. _morphVec4.fromBufferAttribute( morphNormal, j );
  12817. buffer[ offset + stride + 4 ] = _morphVec4.x;
  12818. buffer[ offset + stride + 5 ] = _morphVec4.y;
  12819. buffer[ offset + stride + 6 ] = _morphVec4.z;
  12820. buffer[ offset + stride + 7 ] = 0;
  12821. }
  12822. if ( hasMorphColors === true ) {
  12823. _morphVec4.fromBufferAttribute( morphColor, j );
  12824. buffer[ offset + stride + 8 ] = _morphVec4.x;
  12825. buffer[ offset + stride + 9 ] = _morphVec4.y;
  12826. buffer[ offset + stride + 10 ] = _morphVec4.z;
  12827. buffer[ offset + stride + 11 ] = ( morphColor.itemSize === 4 ) ? _morphVec4.w : 1;
  12828. }
  12829. }
  12830. }
  12831. entry = {
  12832. count: morphTargetsCount,
  12833. texture: bufferTexture,
  12834. stride: vertexDataCount,
  12835. size: new Vector2( width, height )
  12836. };
  12837. _morphTextures.set( geometry, entry );
  12838. function disposeTexture() {
  12839. bufferTexture.dispose();
  12840. _morphTextures.delete( geometry );
  12841. geometry.removeEventListener( 'dispose', disposeTexture );
  12842. }
  12843. geometry.addEventListener( 'dispose', disposeTexture );
  12844. }
  12845. return entry;
  12846. }
  12847. /**
  12848. * This node implements the vertex transformation shader logic which is required
  12849. * for morph target animation.
  12850. *
  12851. * @augments Node
  12852. */
  12853. class MorphNode extends Node {
  12854. static get type() {
  12855. return 'MorphNode';
  12856. }
  12857. /**
  12858. * Constructs a new morph node.
  12859. *
  12860. * @param {Mesh} mesh - The mesh holding the morph targets.
  12861. */
  12862. constructor( mesh ) {
  12863. super( 'void' );
  12864. /**
  12865. * The mesh holding the morph targets.
  12866. *
  12867. * @type {Mesh}
  12868. */
  12869. this.mesh = mesh;
  12870. /**
  12871. * A uniform node which represents the morph base influence value.
  12872. *
  12873. * @type {UniformNode<float>}
  12874. */
  12875. this.morphBaseInfluence = uniform( 1 );
  12876. /**
  12877. * The update type overwritten since morph nodes are updated per object.
  12878. *
  12879. * @type {string}
  12880. */
  12881. this.updateType = NodeUpdateType.OBJECT;
  12882. }
  12883. /**
  12884. * Setups the morph node by assigning the transformed vertex data to predefined node variables.
  12885. *
  12886. * @param {NodeBuilder} builder - The current node builder.
  12887. */
  12888. setup( builder ) {
  12889. const { geometry } = builder;
  12890. const hasMorphPosition = geometry.morphAttributes.position !== undefined;
  12891. const hasMorphNormals = geometry.hasAttribute( 'normal' ) && geometry.morphAttributes.normal !== undefined;
  12892. const morphAttribute = geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color;
  12893. const morphTargetsCount = ( morphAttribute !== undefined ) ? morphAttribute.length : 0;
  12894. // nodes
  12895. const { texture: bufferMap, stride, size } = getEntry( geometry );
  12896. if ( hasMorphPosition === true ) positionLocal.mulAssign( this.morphBaseInfluence );
  12897. if ( hasMorphNormals === true ) normalLocal.mulAssign( this.morphBaseInfluence );
  12898. const width = int( size.width );
  12899. Loop( morphTargetsCount, ( { i } ) => {
  12900. const influence = float( 0 ).toVar();
  12901. if ( this.mesh.count > 1 && ( this.mesh.morphTexture !== null && this.mesh.morphTexture !== undefined ) ) {
  12902. influence.assign( textureLoad( this.mesh.morphTexture, ivec2( int( i ).add( 1 ), int( instanceIndex ) ) ).r );
  12903. } else {
  12904. influence.assign( reference( 'morphTargetInfluences', 'float' ).element( i ).toVar() );
  12905. }
  12906. If( influence.notEqual( 0 ), () => {
  12907. if ( hasMorphPosition === true ) {
  12908. positionLocal.addAssign( getMorph( {
  12909. bufferMap,
  12910. influence,
  12911. stride,
  12912. width,
  12913. depth: i,
  12914. offset: int( 0 )
  12915. } ) );
  12916. }
  12917. if ( hasMorphNormals === true ) {
  12918. normalLocal.addAssign( getMorph( {
  12919. bufferMap,
  12920. influence,
  12921. stride,
  12922. width,
  12923. depth: i,
  12924. offset: int( 1 )
  12925. } ) );
  12926. }
  12927. } );
  12928. } );
  12929. }
  12930. /**
  12931. * Updates the state of the morphed mesh by updating the base influence.
  12932. *
  12933. * @param {NodeFrame} frame - The current node frame.
  12934. */
  12935. update( /*frame*/ ) {
  12936. const morphBaseInfluence = this.morphBaseInfluence;
  12937. if ( this.mesh.geometry.morphTargetsRelative ) {
  12938. morphBaseInfluence.value = 1;
  12939. } else {
  12940. morphBaseInfluence.value = 1 - this.mesh.morphTargetInfluences.reduce( ( a, b ) => a + b, 0 );
  12941. }
  12942. }
  12943. }
  12944. /**
  12945. * TSL function for creating a morph node.
  12946. *
  12947. * @tsl
  12948. * @function
  12949. * @param {Mesh} mesh - The mesh holding the morph targets.
  12950. * @returns {MorphNode}
  12951. */
  12952. const morphReference = /*@__PURE__*/ nodeProxy( MorphNode ).setParameterLength( 1 );
  12953. /**
  12954. * Base class for lighting nodes.
  12955. *
  12956. * @augments Node
  12957. */
  12958. class LightingNode extends Node {
  12959. static get type() {
  12960. return 'LightingNode';
  12961. }
  12962. /**
  12963. * Constructs a new lighting node.
  12964. */
  12965. constructor() {
  12966. super( 'vec3' );
  12967. /**
  12968. * This flag can be used for type testing.
  12969. *
  12970. * @type {boolean}
  12971. * @readonly
  12972. * @default true
  12973. */
  12974. this.isLightingNode = true;
  12975. }
  12976. }
  12977. /**
  12978. * A generic class that can be used by nodes which contribute
  12979. * ambient occlusion to the scene. E.g. an ambient occlusion map
  12980. * node can be used as input for this module. Used in {@link NodeMaterial}.
  12981. *
  12982. * @augments LightingNode
  12983. */
  12984. class AONode extends LightingNode {
  12985. static get type() {
  12986. return 'AONode';
  12987. }
  12988. /**
  12989. * Constructs a new AO node.
  12990. *
  12991. * @param {?Node<float>} [aoNode=null] - The ambient occlusion node.
  12992. */
  12993. constructor( aoNode = null ) {
  12994. super();
  12995. /**
  12996. * The ambient occlusion node.
  12997. *
  12998. * @type {?Node<float>}
  12999. * @default null
  13000. */
  13001. this.aoNode = aoNode;
  13002. }
  13003. setup( builder ) {
  13004. builder.context.ambientOcclusion.mulAssign( this.aoNode );
  13005. }
  13006. }
  13007. /**
  13008. * `LightingContextNode` represents an extension of the {@link ContextNode} module
  13009. * by adding lighting specific context data. It represents the runtime context of
  13010. * {@link LightsNode}.
  13011. *
  13012. * @augments ContextNode
  13013. */
  13014. class LightingContextNode extends ContextNode {
  13015. static get type() {
  13016. return 'LightingContextNode';
  13017. }
  13018. /**
  13019. * Constructs a new lighting context node.
  13020. *
  13021. * @param {LightsNode} lightsNode - The lights node.
  13022. * @param {?LightingModel} [lightingModel=null] - The current lighting model.
  13023. * @param {?Node<vec3>} [backdropNode=null] - A backdrop node.
  13024. * @param {?Node<float>} [backdropAlphaNode=null] - A backdrop alpha node.
  13025. */
  13026. constructor( lightsNode, lightingModel = null, backdropNode = null, backdropAlphaNode = null ) {
  13027. super( lightsNode );
  13028. /**
  13029. * The current lighting model.
  13030. *
  13031. * @type {?LightingModel}
  13032. * @default null
  13033. */
  13034. this.lightingModel = lightingModel;
  13035. /**
  13036. * A backdrop node.
  13037. *
  13038. * @type {?Node<vec3>}
  13039. * @default null
  13040. */
  13041. this.backdropNode = backdropNode;
  13042. /**
  13043. * A backdrop alpha node.
  13044. *
  13045. * @type {?Node<float>}
  13046. * @default null
  13047. */
  13048. this.backdropAlphaNode = backdropAlphaNode;
  13049. this._value = null;
  13050. }
  13051. /**
  13052. * Returns a lighting context object.
  13053. *
  13054. * @return {{
  13055. * radiance: Node<vec3>,
  13056. * irradiance: Node<vec3>,
  13057. * iblIrradiance: Node<vec3>,
  13058. * ambientOcclusion: Node<float>,
  13059. * reflectedLight: {directDiffuse: Node<vec3>, directSpecular: Node<vec3>, indirectDiffuse: Node<vec3>, indirectSpecular: Node<vec3>},
  13060. * backdrop: Node<vec3>,
  13061. * backdropAlpha: Node<float>
  13062. * }} The lighting context object.
  13063. */
  13064. getContext() {
  13065. const { backdropNode, backdropAlphaNode } = this;
  13066. const directDiffuse = vec3().toVar( 'directDiffuse' ),
  13067. directSpecular = vec3().toVar( 'directSpecular' ),
  13068. indirectDiffuse = vec3().toVar( 'indirectDiffuse' ),
  13069. indirectSpecular = vec3().toVar( 'indirectSpecular' );
  13070. const reflectedLight = {
  13071. directDiffuse,
  13072. directSpecular,
  13073. indirectDiffuse,
  13074. indirectSpecular
  13075. };
  13076. const context = {
  13077. radiance: vec3().toVar( 'radiance' ),
  13078. irradiance: vec3().toVar( 'irradiance' ),
  13079. iblIrradiance: vec3().toVar( 'iblIrradiance' ),
  13080. ambientOcclusion: float( 1 ).toVar( 'ambientOcclusion' ),
  13081. reflectedLight,
  13082. backdrop: backdropNode,
  13083. backdropAlpha: backdropAlphaNode
  13084. };
  13085. return context;
  13086. }
  13087. setup( builder ) {
  13088. this.value = this._value || ( this._value = this.getContext() );
  13089. this.value.lightingModel = this.lightingModel || builder.context.lightingModel;
  13090. return super.setup( builder );
  13091. }
  13092. }
  13093. const lightingContext = /*@__PURE__*/ nodeProxy( LightingContextNode );
  13094. /**
  13095. * A generic class that can be used by nodes which contribute
  13096. * irradiance to the scene. E.g. a light map node can be used
  13097. * as input for this module. Used in {@link NodeMaterial}.
  13098. *
  13099. * @augments LightingNode
  13100. */
  13101. class IrradianceNode extends LightingNode {
  13102. static get type() {
  13103. return 'IrradianceNode';
  13104. }
  13105. /**
  13106. * Constructs a new irradiance node.
  13107. *
  13108. * @param {Node<vec3>} node - A node contributing irradiance.
  13109. */
  13110. constructor( node ) {
  13111. super();
  13112. /**
  13113. * A node contributing irradiance.
  13114. *
  13115. * @type {Node<vec3>}
  13116. */
  13117. this.node = node;
  13118. }
  13119. setup( builder ) {
  13120. builder.context.irradiance.addAssign( this.node );
  13121. }
  13122. }
  13123. const _size$5 = /*@__PURE__*/ new Vector2();
  13124. /**
  13125. * A special type of texture node which represents the data of the current viewport
  13126. * as a texture. The module extracts data from the current bound framebuffer with
  13127. * a copy operation so no extra render pass is required to produce the texture data
  13128. * (which is good for performance). `ViewportTextureNode` can be used as an input for a
  13129. * variety of effects like refractive or transmissive materials.
  13130. *
  13131. * @augments TextureNode
  13132. */
  13133. class ViewportTextureNode extends TextureNode {
  13134. static get type() {
  13135. return 'ViewportTextureNode';
  13136. }
  13137. /**
  13138. * Constructs a new viewport texture node.
  13139. *
  13140. * @param {Node} [uvNode=screenUV] - The uv node.
  13141. * @param {?Node} [levelNode=null] - The level node.
  13142. * @param {?Texture} [framebufferTexture=null] - A framebuffer texture holding the viewport data. If not provided, a framebuffer texture is created automatically.
  13143. */
  13144. constructor( uvNode = screenUV, levelNode = null, framebufferTexture = null ) {
  13145. let defaultFramebuffer = null;
  13146. if ( framebufferTexture === null ) {
  13147. defaultFramebuffer = new FramebufferTexture();
  13148. defaultFramebuffer.minFilter = LinearMipmapLinearFilter;
  13149. framebufferTexture = defaultFramebuffer;
  13150. } else {
  13151. defaultFramebuffer = framebufferTexture;
  13152. }
  13153. super( framebufferTexture, uvNode, levelNode );
  13154. /**
  13155. * Whether to generate mipmaps or not.
  13156. *
  13157. * @type {boolean}
  13158. * @default false
  13159. */
  13160. this.generateMipmaps = false;
  13161. /**
  13162. * The reference framebuffer texture. This is used to store the framebuffer texture
  13163. * for the current render target. If the render target changes, a new framebuffer texture
  13164. * is created automatically.
  13165. *
  13166. * @type {FramebufferTexture}
  13167. * @default null
  13168. */
  13169. this.defaultFramebuffer = defaultFramebuffer;
  13170. /**
  13171. * This flag can be used for type testing.
  13172. *
  13173. * @type {boolean}
  13174. * @readonly
  13175. * @default true
  13176. */
  13177. this.isOutputTextureNode = true;
  13178. /**
  13179. * The `updateBeforeType` is set to `NodeUpdateType.FRAME` since the node renders the
  13180. * scene once per frame in its {@link ViewportTextureNode#updateBefore} method.
  13181. *
  13182. * @type {string}
  13183. * @default 'frame'
  13184. */
  13185. this.updateBeforeType = NodeUpdateType.FRAME;
  13186. /**
  13187. * The framebuffer texture for the current renderer context.
  13188. *
  13189. * @type {WeakMap<RenderTarget, FramebufferTexture>}
  13190. * @private
  13191. */
  13192. this._cacheTextures = new WeakMap();
  13193. }
  13194. /**
  13195. * This methods returns a texture for the given render target reference.
  13196. *
  13197. * To avoid rendering errors, `ViewportTextureNode` must use unique framebuffer textures
  13198. * for different render contexts.
  13199. *
  13200. * @param {?RenderTarget} [reference=null] - The render target reference.
  13201. * @return {Texture} The framebuffer texture.
  13202. */
  13203. getTextureForReference( reference = null ) {
  13204. let defaultFramebuffer;
  13205. let cacheTextures;
  13206. if ( this.referenceNode ) {
  13207. defaultFramebuffer = this.referenceNode.defaultFramebuffer;
  13208. cacheTextures = this.referenceNode._cacheTextures;
  13209. } else {
  13210. defaultFramebuffer = this.defaultFramebuffer;
  13211. cacheTextures = this._cacheTextures;
  13212. }
  13213. if ( reference === null ) {
  13214. return defaultFramebuffer;
  13215. }
  13216. if ( cacheTextures.has( reference ) === false ) {
  13217. const framebufferTexture = defaultFramebuffer.clone();
  13218. cacheTextures.set( reference, framebufferTexture );
  13219. }
  13220. return cacheTextures.get( reference );
  13221. }
  13222. updateReference( frame ) {
  13223. const renderTarget = frame.renderer.getRenderTarget();
  13224. this.value = this.getTextureForReference( renderTarget );
  13225. return this.value;
  13226. }
  13227. updateBefore( frame ) {
  13228. const renderer = frame.renderer;
  13229. const renderTarget = renderer.getRenderTarget();
  13230. if ( renderTarget === null ) {
  13231. renderer.getDrawingBufferSize( _size$5 );
  13232. } else {
  13233. _size$5.set( renderTarget.width, renderTarget.height );
  13234. }
  13235. //
  13236. const framebufferTexture = this.getTextureForReference( renderTarget );
  13237. if ( framebufferTexture.image.width !== _size$5.width || framebufferTexture.image.height !== _size$5.height ) {
  13238. framebufferTexture.image.width = _size$5.width;
  13239. framebufferTexture.image.height = _size$5.height;
  13240. framebufferTexture.needsUpdate = true;
  13241. }
  13242. //
  13243. const currentGenerateMipmaps = framebufferTexture.generateMipmaps;
  13244. framebufferTexture.generateMipmaps = this.generateMipmaps;
  13245. renderer.copyFramebufferToTexture( framebufferTexture );
  13246. framebufferTexture.generateMipmaps = currentGenerateMipmaps;
  13247. }
  13248. clone() {
  13249. const viewportTextureNode = new this.constructor( this.uvNode, this.levelNode, this.value );
  13250. viewportTextureNode.generateMipmaps = this.generateMipmaps;
  13251. return viewportTextureNode;
  13252. }
  13253. }
  13254. /**
  13255. * TSL function for creating a viewport texture node.
  13256. *
  13257. * @tsl
  13258. * @function
  13259. * @param {?Node} [uvNode=screenUV] - The uv node.
  13260. * @param {?Node} [levelNode=null] - The level node.
  13261. * @param {?Texture} [framebufferTexture=null] - A framebuffer texture holding the viewport data. If not provided, a framebuffer texture is created automatically.
  13262. * @returns {ViewportTextureNode}
  13263. */
  13264. const viewportTexture = /*@__PURE__*/ nodeProxy( ViewportTextureNode ).setParameterLength( 0, 3 );
  13265. /**
  13266. * TSL function for creating a viewport texture node with enabled mipmap generation.
  13267. *
  13268. * @tsl
  13269. * @function
  13270. * @param {?Node} [uvNode=screenUV] - The uv node.
  13271. * @param {?Node} [levelNode=null] - The level node.
  13272. * @param {?Texture} [framebufferTexture=null] - A framebuffer texture holding the viewport data. If not provided, a framebuffer texture is created automatically.
  13273. * @returns {ViewportTextureNode}
  13274. */
  13275. const viewportMipTexture = /*@__PURE__*/ nodeProxy( ViewportTextureNode, null, null, { generateMipmaps: true } ).setParameterLength( 0, 3 );
  13276. let _sharedDepthbuffer = null;
  13277. /**
  13278. * Represents the depth of the current viewport as a texture. This module
  13279. * can be used in combination with viewport texture to achieve effects
  13280. * that require depth evaluation.
  13281. *
  13282. * @augments ViewportTextureNode
  13283. */
  13284. class ViewportDepthTextureNode extends ViewportTextureNode {
  13285. static get type() {
  13286. return 'ViewportDepthTextureNode';
  13287. }
  13288. /**
  13289. * Constructs a new viewport depth texture node.
  13290. *
  13291. * @param {Node} [uvNode=screenUV] - The uv node.
  13292. * @param {?Node} [levelNode=null] - The level node.
  13293. */
  13294. constructor( uvNode = screenUV, levelNode = null ) {
  13295. if ( _sharedDepthbuffer === null ) {
  13296. _sharedDepthbuffer = new DepthTexture();
  13297. }
  13298. super( uvNode, levelNode, _sharedDepthbuffer );
  13299. }
  13300. /**
  13301. * Overwritten so the method always returns the unique shared
  13302. * depth texture.
  13303. *
  13304. * @return {DepthTexture} The shared depth texture.
  13305. */
  13306. getTextureForReference() {
  13307. return _sharedDepthbuffer;
  13308. }
  13309. }
  13310. /**
  13311. * TSL function for a viewport depth texture node.
  13312. *
  13313. * @tsl
  13314. * @function
  13315. * @param {?Node} [uvNode=screenUV] - The uv node.
  13316. * @param {?Node} [levelNode=null] - The level node.
  13317. * @returns {ViewportDepthTextureNode}
  13318. */
  13319. const viewportDepthTexture = /*@__PURE__*/ nodeProxy( ViewportDepthTextureNode ).setParameterLength( 0, 2 );
  13320. /**
  13321. * This node offers a collection of features in context of the depth logic in the fragment shader.
  13322. * Depending on {@link ViewportDepthNode#scope}, it can be used to define a depth value for the current
  13323. * fragment or for depth evaluation purposes.
  13324. *
  13325. * @augments Node
  13326. */
  13327. class ViewportDepthNode extends Node {
  13328. static get type() {
  13329. return 'ViewportDepthNode';
  13330. }
  13331. /**
  13332. * Constructs a new viewport depth node.
  13333. *
  13334. * @param {('depth'|'depthBase'|'linearDepth')} scope - The node's scope.
  13335. * @param {?Node} [valueNode=null] - The value node.
  13336. */
  13337. constructor( scope, valueNode = null ) {
  13338. super( 'float' );
  13339. /**
  13340. * The node behaves differently depending on which scope is selected.
  13341. *
  13342. * - `ViewportDepthNode.DEPTH_BASE`: Allows to define a value for the current fragment's depth.
  13343. * - `ViewportDepthNode.DEPTH`: Represents the depth value for the current fragment (`valueNode` is ignored).
  13344. * - `ViewportDepthNode.LINEAR_DEPTH`: Represents the linear (orthographic) depth value of the current fragment.
  13345. * If a `valueNode` is set, the scope can be used to convert perspective depth data to linear data.
  13346. *
  13347. * @type {('depth'|'depthBase'|'linearDepth')}
  13348. */
  13349. this.scope = scope;
  13350. /**
  13351. * Can be used to define a custom depth value.
  13352. * The property is ignored in the `ViewportDepthNode.DEPTH` scope.
  13353. *
  13354. * @type {?Node}
  13355. * @default null
  13356. */
  13357. this.valueNode = valueNode;
  13358. /**
  13359. * This flag can be used for type testing.
  13360. *
  13361. * @type {boolean}
  13362. * @readonly
  13363. * @default true
  13364. */
  13365. this.isViewportDepthNode = true;
  13366. }
  13367. generate( builder ) {
  13368. const { scope } = this;
  13369. if ( scope === ViewportDepthNode.DEPTH_BASE ) {
  13370. return builder.getFragDepth();
  13371. }
  13372. return super.generate( builder );
  13373. }
  13374. setup( { camera } ) {
  13375. const { scope } = this;
  13376. const value = this.valueNode;
  13377. let node = null;
  13378. if ( scope === ViewportDepthNode.DEPTH_BASE ) {
  13379. if ( value !== null ) {
  13380. node = depthBase().assign( value );
  13381. }
  13382. } else if ( scope === ViewportDepthNode.DEPTH ) {
  13383. if ( camera.isPerspectiveCamera ) {
  13384. node = viewZToPerspectiveDepth( positionView.z, cameraNear, cameraFar );
  13385. } else {
  13386. node = viewZToOrthographicDepth( positionView.z, cameraNear, cameraFar );
  13387. }
  13388. } else if ( scope === ViewportDepthNode.LINEAR_DEPTH ) {
  13389. if ( value !== null ) {
  13390. if ( camera.isPerspectiveCamera ) {
  13391. const viewZ = perspectiveDepthToViewZ( value, cameraNear, cameraFar );
  13392. node = viewZToOrthographicDepth( viewZ, cameraNear, cameraFar );
  13393. } else {
  13394. node = value;
  13395. }
  13396. } else {
  13397. node = viewZToOrthographicDepth( positionView.z, cameraNear, cameraFar );
  13398. }
  13399. }
  13400. return node;
  13401. }
  13402. }
  13403. ViewportDepthNode.DEPTH_BASE = 'depthBase';
  13404. ViewportDepthNode.DEPTH = 'depth';
  13405. ViewportDepthNode.LINEAR_DEPTH = 'linearDepth';
  13406. // NOTE: viewZ, the z-coordinate in camera space, is negative for points in front of the camera
  13407. /**
  13408. * TSL function for converting a viewZ value to an orthographic depth value.
  13409. *
  13410. * @tsl
  13411. * @function
  13412. * @param {Node<float>} viewZ - The viewZ node.
  13413. * @param {Node<float>} near - The camera's near value.
  13414. * @param {Node<float>} far - The camera's far value.
  13415. * @returns {Node<float>}
  13416. */
  13417. const viewZToOrthographicDepth = ( viewZ, near, far ) => viewZ.add( near ).div( near.sub( far ) );
  13418. /**
  13419. * TSL function for converting an orthographic depth value to a viewZ value.
  13420. *
  13421. * @tsl
  13422. * @function
  13423. * @param {Node<float>} depth - The orthographic depth.
  13424. * @param {Node<float>} near - The camera's near value.
  13425. * @param {Node<float>} far - The camera's far value.
  13426. * @returns {Node<float>}
  13427. */
  13428. const orthographicDepthToViewZ = ( depth, near, far ) => near.sub( far ).mul( depth ).sub( near );
  13429. /**
  13430. * TSL function for converting a viewZ value to a perspective depth value.
  13431. *
  13432. * Note: {link https://twitter.com/gonnavis/status/1377183786949959682}.
  13433. *
  13434. * @tsl
  13435. * @function
  13436. * @param {Node<float>} viewZ - The viewZ node.
  13437. * @param {Node<float>} near - The camera's near value.
  13438. * @param {Node<float>} far - The camera's far value.
  13439. * @returns {Node<float>}
  13440. */
  13441. const viewZToPerspectiveDepth = ( viewZ, near, far ) => near.add( viewZ ).mul( far ).div( far.sub( near ).mul( viewZ ) );
  13442. /**
  13443. * TSL function for converting a perspective depth value to a viewZ value.
  13444. *
  13445. * @tsl
  13446. * @function
  13447. * @param {Node<float>} depth - The perspective depth.
  13448. * @param {Node<float>} near - The camera's near value.
  13449. * @param {Node<float>} far - The camera's far value.
  13450. * @returns {Node<float>}
  13451. */
  13452. const perspectiveDepthToViewZ = ( depth, near, far ) => near.mul( far ).div( far.sub( near ).mul( depth ).sub( far ) );
  13453. /**
  13454. * TSL function for converting a viewZ value to a logarithmic depth value.
  13455. *
  13456. * @tsl
  13457. * @function
  13458. * @param {Node<float>} viewZ - The viewZ node.
  13459. * @param {Node<float>} near - The camera's near value.
  13460. * @param {Node<float>} far - The camera's far value.
  13461. * @returns {Node<float>}
  13462. */
  13463. const viewZToLogarithmicDepth = ( viewZ, near, far ) => {
  13464. // NOTE: viewZ must be negative--see explanation at the end of this comment block.
  13465. // The final logarithmic depth formula used here is adapted from one described in an
  13466. // article by Thatcher Ulrich (see http://tulrich.com/geekstuff/log_depth_buffer.txt),
  13467. // which was an improvement upon an earlier formula one described in an
  13468. // Outerra article (https://outerra.blogspot.com/2009/08/logarithmic-z-buffer.html).
  13469. // Ulrich's formula is the following:
  13470. // z = K * log( w / cameraNear ) / log( cameraFar / cameraNear )
  13471. // where K = 2^k - 1, and k is the number of bits in the depth buffer.
  13472. // The Outerra variant ignored the camera near plane (it assumed it was 0) and instead
  13473. // opted for a "C-constant" for resolution adjustment of objects near the camera.
  13474. // Outerra states: "Notice that the 'C' variant doesn’t use a near plane distance, it has it
  13475. // set at 0" (quote from https://outerra.blogspot.com/2012/11/maximizing-depth-buffer-range-and.html).
  13476. // Ulrich's variant has the benefit of constant relative precision over the whole near-far range.
  13477. // It was debated here whether Outerra's "C-constant" or Ulrich's "near plane" variant should
  13478. // be used, and ultimately Ulrich's "near plane" version was chosen.
  13479. // Outerra eventually made another improvement to their original "C-constant" variant,
  13480. // but it still does not incorporate the camera near plane (for this version,
  13481. // see https://outerra.blogspot.com/2013/07/logarithmic-depth-buffer-optimizations.html).
  13482. // Here we make 4 changes to Ulrich's formula:
  13483. // 1. Clamp the camera near plane so we don't divide by 0.
  13484. // 2. Use log2 instead of log to avoid an extra multiply (shaders implement log using log2).
  13485. // 3. Assume K is 1 (K = maximum value in depth buffer; see Ulrich's formula above).
  13486. // 4. To maintain consistency with the functions "viewZToOrthographicDepth" and "viewZToPerspectiveDepth",
  13487. // we modify the formula here to use 'viewZ' instead of 'w'. The other functions expect a negative viewZ,
  13488. // so we do the same here, hence the 'viewZ.negate()' call.
  13489. // For visual representation of this depth curve, see https://www.desmos.com/calculator/uyqk0vex1u
  13490. near = near.max( 1e-6 ).toVar();
  13491. const numerator = log2( viewZ.negate().div( near ) );
  13492. const denominator = log2( far.div( near ) );
  13493. return numerator.div( denominator );
  13494. };
  13495. /**
  13496. * TSL function for converting a logarithmic depth value to a viewZ value.
  13497. *
  13498. * @tsl
  13499. * @function
  13500. * @param {Node<float>} depth - The logarithmic depth.
  13501. * @param {Node<float>} near - The camera's near value.
  13502. * @param {Node<float>} far - The camera's far value.
  13503. * @returns {Node<float>}
  13504. */
  13505. const logarithmicDepthToViewZ = ( depth, near, far ) => {
  13506. // NOTE: we add a 'negate()' call to the return value here to maintain consistency with
  13507. // the functions "orthographicDepthToViewZ" and "perspectiveDepthToViewZ" (they return
  13508. // a negative viewZ).
  13509. const exponent = depth.mul( log( far.div( near ) ) );
  13510. return float( Math.E ).pow( exponent ).mul( near ).negate();
  13511. };
  13512. /**
  13513. * TSL function for defining a value for the current fragment's depth.
  13514. *
  13515. * @tsl
  13516. * @function
  13517. * @param {Node<float>} value - The depth value to set.
  13518. * @returns {ViewportDepthNode<float>}
  13519. */
  13520. const depthBase = /*@__PURE__*/ nodeProxy( ViewportDepthNode, ViewportDepthNode.DEPTH_BASE );
  13521. /**
  13522. * TSL object that represents the depth value for the current fragment.
  13523. *
  13524. * @tsl
  13525. * @type {ViewportDepthNode}
  13526. */
  13527. const depth = /*@__PURE__*/ nodeImmutable( ViewportDepthNode, ViewportDepthNode.DEPTH );
  13528. /**
  13529. * TSL function for converting a perspective depth value to linear depth.
  13530. *
  13531. * @tsl
  13532. * @function
  13533. * @param {?Node<float>} [value=null] - The perspective depth. If `null` is provided, the current fragment's depth is used.
  13534. * @returns {ViewportDepthNode<float>}
  13535. */
  13536. const linearDepth = /*@__PURE__*/ nodeProxy( ViewportDepthNode, ViewportDepthNode.LINEAR_DEPTH ).setParameterLength( 0, 1 );
  13537. /**
  13538. * TSL object that represents the linear (orthographic) depth value of the current fragment
  13539. *
  13540. * @tsl
  13541. * @type {ViewportDepthNode}
  13542. */
  13543. const viewportLinearDepth = /*@__PURE__*/ linearDepth( viewportDepthTexture() );
  13544. depth.assign = ( value ) => depthBase( value );
  13545. /**
  13546. * This node is used in {@link NodeMaterial} to setup the clipping
  13547. * which can happen hardware-accelerated (if supported) and optionally
  13548. * use alpha-to-coverage for anti-aliasing clipped edges.
  13549. *
  13550. * @augments Node
  13551. */
  13552. class ClippingNode extends Node {
  13553. static get type() {
  13554. return 'ClippingNode';
  13555. }
  13556. /**
  13557. * Constructs a new clipping node.
  13558. *
  13559. * @param {('default'|'hardware'|'alphaToCoverage')} [scope='default'] - The node's scope. Similar to other nodes,
  13560. * the selected scope influences the behavior of the node and what type of code is generated.
  13561. */
  13562. constructor( scope = ClippingNode.DEFAULT ) {
  13563. super();
  13564. /**
  13565. * The node's scope. Similar to other nodes, the selected scope influences
  13566. * the behavior of the node and what type of code is generated.
  13567. *
  13568. * @type {('default'|'hardware'|'alphaToCoverage')}
  13569. */
  13570. this.scope = scope;
  13571. }
  13572. /**
  13573. * Setups the node depending on the selected scope.
  13574. *
  13575. * @param {NodeBuilder} builder - The current node builder.
  13576. * @return {Node} The result node.
  13577. */
  13578. setup( builder ) {
  13579. super.setup( builder );
  13580. const clippingContext = builder.clippingContext;
  13581. const { intersectionPlanes, unionPlanes } = clippingContext;
  13582. this.hardwareClipping = builder.material.hardwareClipping;
  13583. if ( this.scope === ClippingNode.ALPHA_TO_COVERAGE ) {
  13584. return this.setupAlphaToCoverage( intersectionPlanes, unionPlanes );
  13585. } else if ( this.scope === ClippingNode.HARDWARE ) {
  13586. return this.setupHardwareClipping( unionPlanes, builder );
  13587. } else {
  13588. return this.setupDefault( intersectionPlanes, unionPlanes );
  13589. }
  13590. }
  13591. /**
  13592. * Setups alpha to coverage.
  13593. *
  13594. * @param {Array<Vector4>} intersectionPlanes - The intersection planes.
  13595. * @param {Array<Vector4>} unionPlanes - The union planes.
  13596. * @return {Node} The result node.
  13597. */
  13598. setupAlphaToCoverage( intersectionPlanes, unionPlanes ) {
  13599. return Fn( () => {
  13600. const distanceToPlane = float().toVar( 'distanceToPlane' );
  13601. const distanceGradient = float().toVar( 'distanceToGradient' );
  13602. const clipOpacity = float( 1 ).toVar( 'clipOpacity' );
  13603. const numUnionPlanes = unionPlanes.length;
  13604. if ( this.hardwareClipping === false && numUnionPlanes > 0 ) {
  13605. const clippingPlanes = uniformArray( unionPlanes ).setGroup( renderGroup );
  13606. Loop( numUnionPlanes, ( { i } ) => {
  13607. const plane = clippingPlanes.element( i );
  13608. distanceToPlane.assign( positionView.dot( plane.xyz ).negate().add( plane.w ) );
  13609. distanceGradient.assign( distanceToPlane.fwidth().div( 2.0 ) );
  13610. clipOpacity.mulAssign( smoothstep( distanceGradient.negate(), distanceGradient, distanceToPlane ) );
  13611. } );
  13612. }
  13613. const numIntersectionPlanes = intersectionPlanes.length;
  13614. if ( numIntersectionPlanes > 0 ) {
  13615. const clippingPlanes = uniformArray( intersectionPlanes ).setGroup( renderGroup );
  13616. const intersectionClipOpacity = float( 1 ).toVar( 'intersectionClipOpacity' );
  13617. Loop( numIntersectionPlanes, ( { i } ) => {
  13618. const plane = clippingPlanes.element( i );
  13619. distanceToPlane.assign( positionView.dot( plane.xyz ).negate().add( plane.w ) );
  13620. distanceGradient.assign( distanceToPlane.fwidth().div( 2.0 ) );
  13621. intersectionClipOpacity.mulAssign( smoothstep( distanceGradient.negate(), distanceGradient, distanceToPlane ).oneMinus() );
  13622. } );
  13623. clipOpacity.mulAssign( intersectionClipOpacity.oneMinus() );
  13624. }
  13625. diffuseColor.a.mulAssign( clipOpacity );
  13626. diffuseColor.a.equal( 0.0 ).discard();
  13627. } )();
  13628. }
  13629. /**
  13630. * Setups the default clipping.
  13631. *
  13632. * @param {Array<Vector4>} intersectionPlanes - The intersection planes.
  13633. * @param {Array<Vector4>} unionPlanes - The union planes.
  13634. * @return {Node} The result node.
  13635. */
  13636. setupDefault( intersectionPlanes, unionPlanes ) {
  13637. return Fn( () => {
  13638. const numUnionPlanes = unionPlanes.length;
  13639. if ( this.hardwareClipping === false && numUnionPlanes > 0 ) {
  13640. const clippingPlanes = uniformArray( unionPlanes ).setGroup( renderGroup );
  13641. Loop( numUnionPlanes, ( { i } ) => {
  13642. const plane = clippingPlanes.element( i );
  13643. positionView.dot( plane.xyz ).greaterThan( plane.w ).discard();
  13644. } );
  13645. }
  13646. const numIntersectionPlanes = intersectionPlanes.length;
  13647. if ( numIntersectionPlanes > 0 ) {
  13648. const clippingPlanes = uniformArray( intersectionPlanes ).setGroup( renderGroup );
  13649. const clipped = bool( true ).toVar( 'clipped' );
  13650. Loop( numIntersectionPlanes, ( { i } ) => {
  13651. const plane = clippingPlanes.element( i );
  13652. clipped.assign( positionView.dot( plane.xyz ).greaterThan( plane.w ).and( clipped ) );
  13653. } );
  13654. clipped.discard();
  13655. }
  13656. } )();
  13657. }
  13658. /**
  13659. * Setups hardware clipping.
  13660. *
  13661. * @param {Array<Vector4>} unionPlanes - The union planes.
  13662. * @param {NodeBuilder} builder - The current node builder.
  13663. * @return {Node} The result node.
  13664. */
  13665. setupHardwareClipping( unionPlanes, builder ) {
  13666. const numUnionPlanes = unionPlanes.length;
  13667. builder.enableHardwareClipping( numUnionPlanes );
  13668. return Fn( () => {
  13669. const clippingPlanes = uniformArray( unionPlanes ).setGroup( renderGroup );
  13670. const hw_clip_distances = builtin( builder.getClipDistance() );
  13671. Loop( numUnionPlanes, ( { i } ) => {
  13672. const plane = clippingPlanes.element( i );
  13673. const distance = positionView.dot( plane.xyz ).sub( plane.w ).negate();
  13674. hw_clip_distances.element( i ).assign( distance );
  13675. } );
  13676. } )();
  13677. }
  13678. }
  13679. ClippingNode.ALPHA_TO_COVERAGE = 'alphaToCoverage';
  13680. ClippingNode.DEFAULT = 'default';
  13681. ClippingNode.HARDWARE = 'hardware';
  13682. /**
  13683. * TSL function for setting up the default clipping logic.
  13684. *
  13685. * @tsl
  13686. * @function
  13687. * @returns {ClippingNode}
  13688. */
  13689. const clipping = () => nodeObject( new ClippingNode() );
  13690. /**
  13691. * TSL function for setting up alpha to coverage.
  13692. *
  13693. * @tsl
  13694. * @function
  13695. * @returns {ClippingNode}
  13696. */
  13697. const clippingAlpha = () => nodeObject( new ClippingNode( ClippingNode.ALPHA_TO_COVERAGE ) );
  13698. /**
  13699. * TSL function for setting up hardware-based clipping.
  13700. *
  13701. * @tsl
  13702. * @function
  13703. * @returns {ClippingNode}
  13704. */
  13705. const hardwareClipping = () => nodeObject( new ClippingNode( ClippingNode.HARDWARE ) );
  13706. // See: https://casual-effects.com/research/Wyman2017Hashed/index.html
  13707. const ALPHA_HASH_SCALE = 0.05; // Derived from trials only, and may be changed.
  13708. const hash2D = /*@__PURE__*/ Fn( ( [ value ] ) => {
  13709. 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 ) ) ) ) ) );
  13710. } );
  13711. const hash3D = /*@__PURE__*/ Fn( ( [ value ] ) => {
  13712. return hash2D( vec2( hash2D( value.xy ), value.z ) );
  13713. } );
  13714. const getAlphaHashThreshold = /*@__PURE__*/ Fn( ( [ position ] ) => {
  13715. // Find the discretized derivatives of our coordinates
  13716. const maxDeriv = max$1(
  13717. length( dFdx( position.xyz ) ),
  13718. length( dFdy( position.xyz ) )
  13719. );
  13720. const pixScale = float( 1 ).div( float( ALPHA_HASH_SCALE ).mul( maxDeriv ) ).toVar( 'pixScale' );
  13721. // Find two nearest log-discretized noise scales
  13722. const pixScales = vec2(
  13723. exp2( floor( log2( pixScale ) ) ),
  13724. exp2( ceil( log2( pixScale ) ) )
  13725. );
  13726. // Compute alpha thresholds at our two noise scales
  13727. const alpha = vec2(
  13728. hash3D( floor( pixScales.x.mul( position.xyz ) ) ),
  13729. hash3D( floor( pixScales.y.mul( position.xyz ) ) ),
  13730. );
  13731. // Factor to interpolate lerp with
  13732. const lerpFactor = fract( log2( pixScale ) );
  13733. // Interpolate alpha threshold from noise at two scales
  13734. const x = add( mul( lerpFactor.oneMinus(), alpha.x ), mul( lerpFactor, alpha.y ) );
  13735. // Pass into CDF to compute uniformly distrib threshold
  13736. const a = min$1( lerpFactor, lerpFactor.oneMinus() );
  13737. const cases = vec3(
  13738. x.mul( x ).div( mul( 2.0, a ).mul( sub( 1.0, a ) ) ),
  13739. x.sub( mul( 0.5, a ) ).div( sub( 1.0, a ) ),
  13740. sub( 1.0, sub( 1.0, x ).mul( sub( 1.0, x ) ).div( mul( 2.0, a ).mul( sub( 1.0, a ) ) ) ) );
  13741. // Find our final, uniformly distributed alpha threshold (ατ)
  13742. const threshold = x.lessThan( a.oneMinus() ).select( x.lessThan( a ).select( cases.x, cases.y ), cases.z );
  13743. // Avoids ατ == 0. Could also do ατ =1-ατ
  13744. return clamp( threshold, 1.0e-6, 1.0 );
  13745. } ).setLayout( {
  13746. name: 'getAlphaHashThreshold',
  13747. type: 'float',
  13748. inputs: [
  13749. { name: 'position', type: 'vec3' }
  13750. ]
  13751. } );
  13752. /**
  13753. * An attribute node for representing vertex colors.
  13754. *
  13755. * @augments AttributeNode
  13756. */
  13757. class VertexColorNode extends AttributeNode {
  13758. static get type() {
  13759. return 'VertexColorNode';
  13760. }
  13761. /**
  13762. * Constructs a new vertex color node.
  13763. *
  13764. * @param {number} index - The attribute index.
  13765. */
  13766. constructor( index ) {
  13767. super( null, 'vec4' );
  13768. /**
  13769. * This flag can be used for type testing.
  13770. *
  13771. * @type {boolean}
  13772. * @readonly
  13773. * @default true
  13774. */
  13775. this.isVertexColorNode = true;
  13776. /**
  13777. * The attribute index to enable more than one sets of vertex colors.
  13778. *
  13779. * @type {number}
  13780. * @default 0
  13781. */
  13782. this.index = index;
  13783. }
  13784. /**
  13785. * Overwrites the default implementation by honoring the attribute index.
  13786. *
  13787. * @param {NodeBuilder} builder - The current node builder.
  13788. * @return {string} The attribute name.
  13789. */
  13790. getAttributeName( /*builder*/ ) {
  13791. const index = this.index;
  13792. return 'color' + ( index > 0 ? index : '' );
  13793. }
  13794. generate( builder ) {
  13795. const attributeName = this.getAttributeName( builder );
  13796. const geometryAttribute = builder.hasGeometryAttribute( attributeName );
  13797. let result;
  13798. if ( geometryAttribute === true ) {
  13799. result = super.generate( builder );
  13800. } else {
  13801. // Vertex color fallback should be white
  13802. result = builder.generateConst( this.nodeType, new Vector4( 1, 1, 1, 1 ) );
  13803. }
  13804. return result;
  13805. }
  13806. serialize( data ) {
  13807. super.serialize( data );
  13808. data.index = this.index;
  13809. }
  13810. deserialize( data ) {
  13811. super.deserialize( data );
  13812. this.index = data.index;
  13813. }
  13814. }
  13815. /**
  13816. * TSL function for creating a reference node.
  13817. *
  13818. * @tsl
  13819. * @function
  13820. * @param {number} [index=0] - The attribute index.
  13821. * @returns {VertexColorNode}
  13822. */
  13823. const vertexColor = ( index = 0 ) => nodeObject( new VertexColorNode( index ) );
  13824. /**
  13825. * Represents a "Color Burn" blend mode.
  13826. *
  13827. * It's designed to darken the base layer's colors based on the color of the blend layer.
  13828. * It significantly increases the contrast of the base layer, making the colors more vibrant and saturated.
  13829. * The darker the color in the blend layer, the stronger the darkening and contrast effect on the base layer.
  13830. *
  13831. * @tsl
  13832. * @function
  13833. * @param {Node<vec3>} base - The base color.
  13834. * @param {Node<vec3>} blend - The blend color. A white (#ffffff) blend color does not alter the base color.
  13835. * @return {Node<vec3>} The result.
  13836. */
  13837. const blendBurn = /*@__PURE__*/ Fn( ( [ base, blend ] ) => {
  13838. return min$1( 1.0, base.oneMinus().div( blend ) ).oneMinus();
  13839. } ).setLayout( {
  13840. name: 'blendBurn',
  13841. type: 'vec3',
  13842. inputs: [
  13843. { name: 'base', type: 'vec3' },
  13844. { name: 'blend', type: 'vec3' }
  13845. ]
  13846. } );
  13847. /**
  13848. * Represents a "Color Dodge" blend mode.
  13849. *
  13850. * It's designed to lighten the base layer's colors based on the color of the blend layer.
  13851. * It significantly increases the brightness of the base layer, making the colors lighter and more vibrant.
  13852. * The brighter the color in the blend layer, the stronger the lightening and contrast effect on the base layer.
  13853. *
  13854. * @tsl
  13855. * @function
  13856. * @param {Node<vec3>} base - The base color.
  13857. * @param {Node<vec3>} blend - The blend color. A black (#000000) blend color does not alter the base color.
  13858. * @return {Node<vec3>} The result.
  13859. */
  13860. const blendDodge = /*@__PURE__*/ Fn( ( [ base, blend ] ) => {
  13861. return min$1( base.div( blend.oneMinus() ), 1.0 );
  13862. } ).setLayout( {
  13863. name: 'blendDodge',
  13864. type: 'vec3',
  13865. inputs: [
  13866. { name: 'base', type: 'vec3' },
  13867. { name: 'blend', type: 'vec3' }
  13868. ]
  13869. } );
  13870. /**
  13871. * Represents a "Screen" blend mode.
  13872. *
  13873. * Similar to `blendDodge()`, this mode also lightens the base layer's colors based on the color of the blend layer.
  13874. * The "Screen" blend mode is better for general brightening whereas the "Dodge" results in more subtle and nuanced
  13875. * effects.
  13876. *
  13877. * @tsl
  13878. * @function
  13879. * @param {Node<vec3>} base - The base color.
  13880. * @param {Node<vec3>} blend - The blend color. A black (#000000) blend color does not alter the base color.
  13881. * @return {Node<vec3>} The result.
  13882. */
  13883. const blendScreen = /*@__PURE__*/ Fn( ( [ base, blend ] ) => {
  13884. return base.oneMinus().mul( blend.oneMinus() ).oneMinus();
  13885. } ).setLayout( {
  13886. name: 'blendScreen',
  13887. type: 'vec3',
  13888. inputs: [
  13889. { name: 'base', type: 'vec3' },
  13890. { name: 'blend', type: 'vec3' }
  13891. ]
  13892. } );
  13893. /**
  13894. * Represents a "Overlay" blend mode.
  13895. *
  13896. * It's designed to increase the contrast of the base layer based on the color of the blend layer.
  13897. * It amplifies the existing colors and contrast in the base layer, making lighter areas lighter and darker areas darker.
  13898. * The color of the blend layer significantly influences the resulting contrast and color shift in the base layer.
  13899. *
  13900. * @tsl
  13901. * @function
  13902. * @param {Node<vec3>} base - The base color.
  13903. * @param {Node<vec3>} blend - The blend color
  13904. * @return {Node<vec3>} The result.
  13905. */
  13906. const blendOverlay = /*@__PURE__*/ Fn( ( [ base, blend ] ) => {
  13907. return mix( base.mul( 2.0 ).mul( blend ), base.oneMinus().mul( 2.0 ).mul( blend.oneMinus() ).oneMinus(), step( 0.5, base ) );
  13908. } ).setLayout( {
  13909. name: 'blendOverlay',
  13910. type: 'vec3',
  13911. inputs: [
  13912. { name: 'base', type: 'vec3' },
  13913. { name: 'blend', type: 'vec3' }
  13914. ]
  13915. } );
  13916. /**
  13917. * This function blends two color based on their alpha values by replicating the behavior of `THREE.NormalBlending`.
  13918. * It assumes both input colors have non-premultiplied alpha.
  13919. *
  13920. * @tsl
  13921. * @function
  13922. * @param {Node<vec4>} base - The base color.
  13923. * @param {Node<vec4>} blend - The blend color
  13924. * @return {Node<vec4>} The result.
  13925. */
  13926. const blendColor = /*@__PURE__*/ Fn( ( [ base, blend ] ) => {
  13927. const outAlpha = blend.a.add( base.a.mul( blend.a.oneMinus() ) );
  13928. return vec4( blend.rgb.mul( blend.a ).add( base.rgb.mul( base.a ).mul( blend.a.oneMinus() ) ).div( outAlpha ), outAlpha );
  13929. } ).setLayout( {
  13930. name: 'blendColor',
  13931. type: 'vec4',
  13932. inputs: [
  13933. { name: 'base', type: 'vec4' },
  13934. { name: 'blend', type: 'vec4' }
  13935. ]
  13936. } );
  13937. /**
  13938. * Premultiplies the RGB channels of a color by its alpha channel.
  13939. *
  13940. * This function is useful for converting a non-premultiplied alpha color
  13941. * into a premultiplied alpha format, where the RGB values are scaled
  13942. * by the alpha value. Premultiplied alpha is often used in graphics
  13943. * rendering for certain operations, such as compositing and image processing.
  13944. *
  13945. * @tsl
  13946. * @function
  13947. * @param {Node<vec4>} color - The input color with non-premultiplied alpha.
  13948. * @return {Node<vec4>} The color with premultiplied alpha.
  13949. */
  13950. const premultiplyAlpha = /*@__PURE__*/ Fn( ( [ color ] ) => {
  13951. return vec4( color.rgb.mul( color.a ), color.a );
  13952. }, { color: 'vec4', return: 'vec4' } );
  13953. /**
  13954. * Unpremultiplies the RGB channels of a color by its alpha channel.
  13955. *
  13956. * This function is useful for converting a premultiplied alpha color
  13957. * back into a non-premultiplied alpha format, where the RGB values are
  13958. * divided by the alpha value. Unpremultiplied alpha is often used in graphics
  13959. * rendering for certain operations, such as compositing and image processing.
  13960. *
  13961. * @tsl
  13962. * @function
  13963. * @param {Node<vec4>} color - The input color with premultiplied alpha.
  13964. * @return {Node<vec4>} The color with non-premultiplied alpha.
  13965. */
  13966. const unpremultiplyAlpha = /*@__PURE__*/ Fn( ( [ color ] ) => {
  13967. If( color.a.equal( 0.0 ), () => vec4( 0.0 ) );
  13968. return vec4( color.rgb.div( color.a ), color.a );
  13969. }, { color: 'vec4', return: 'vec4' } );
  13970. // Deprecated
  13971. /**
  13972. * @tsl
  13973. * @function
  13974. * @deprecated since r171. Use {@link blendBurn} instead.
  13975. *
  13976. * @param {...any} params
  13977. * @returns {Function}
  13978. */
  13979. const burn = ( ...params ) => { // @deprecated, r171
  13980. warn( 'TSL: "burn" has been renamed. Use "blendBurn" instead.' );
  13981. return blendBurn( params );
  13982. };
  13983. /**
  13984. * @tsl
  13985. * @function
  13986. * @deprecated since r171. Use {@link blendDodge} instead.
  13987. *
  13988. * @param {...any} params
  13989. * @returns {Function}
  13990. */
  13991. const dodge = ( ...params ) => { // @deprecated, r171
  13992. warn( 'TSL: "dodge" has been renamed. Use "blendDodge" instead.' );
  13993. return blendDodge( params );
  13994. };
  13995. /**
  13996. * @tsl
  13997. * @function
  13998. * @deprecated since r171. Use {@link blendScreen} instead.
  13999. *
  14000. * @param {...any} params
  14001. * @returns {Function}
  14002. */
  14003. const screen = ( ...params ) => { // @deprecated, r171
  14004. warn( 'TSL: "screen" has been renamed. Use "blendScreen" instead.' );
  14005. return blendScreen( params );
  14006. };
  14007. /**
  14008. * @tsl
  14009. * @function
  14010. * @deprecated since r171. Use {@link blendOverlay} instead.
  14011. *
  14012. * @param {...any} params
  14013. * @returns {Function}
  14014. */
  14015. const overlay = ( ...params ) => { // @deprecated, r171
  14016. warn( 'TSL: "overlay" has been renamed. Use "blendOverlay" instead.' );
  14017. return blendOverlay( params );
  14018. };
  14019. /**
  14020. * Base class for all node materials.
  14021. *
  14022. * @augments Material
  14023. */
  14024. class NodeMaterial extends Material {
  14025. static get type() {
  14026. return 'NodeMaterial';
  14027. }
  14028. /**
  14029. * Represents the type of the node material.
  14030. *
  14031. * @type {string}
  14032. */
  14033. get type() {
  14034. return this.constructor.type;
  14035. }
  14036. set type( _value ) { /* */ }
  14037. /**
  14038. * Constructs a new node material.
  14039. */
  14040. constructor() {
  14041. super();
  14042. /**
  14043. * This flag can be used for type testing.
  14044. *
  14045. * @type {boolean}
  14046. * @readonly
  14047. * @default true
  14048. */
  14049. this.isNodeMaterial = true;
  14050. /**
  14051. * Whether this material is affected by fog or not.
  14052. *
  14053. * @type {boolean}
  14054. * @default true
  14055. */
  14056. this.fog = true;
  14057. /**
  14058. * Whether this material is affected by lights or not.
  14059. *
  14060. * @type {boolean}
  14061. * @default false
  14062. */
  14063. this.lights = false;
  14064. /**
  14065. * Whether this material uses hardware clipping or not.
  14066. * This property is managed by the engine and should not be
  14067. * modified by apps.
  14068. *
  14069. * @type {boolean}
  14070. * @default false
  14071. */
  14072. this.hardwareClipping = false;
  14073. /**
  14074. * Node materials which set their `lights` property to `true`
  14075. * are affected by all lights of the scene. Sometimes selective
  14076. * lighting is wanted which means only _some_ lights in the scene
  14077. * affect a material. This can be achieved by creating an instance
  14078. * of {@link LightsNode} with a list of selective
  14079. * lights and assign the node to this property.
  14080. *
  14081. * ```js
  14082. * const customLightsNode = lights( [ light1, light2 ] );
  14083. * material.lightsNode = customLightsNode;
  14084. * ```
  14085. *
  14086. * @type {?LightsNode}
  14087. * @default null
  14088. */
  14089. this.lightsNode = null;
  14090. /**
  14091. * The environment of node materials can be defined by an environment
  14092. * map assigned to the `envMap` property or by `Scene.environment`
  14093. * if the node material is a PBR material. This node property allows to overwrite
  14094. * the default behavior and define the environment with a custom node.
  14095. *
  14096. * ```js
  14097. * material.envNode = pmremTexture( renderTarget.texture );
  14098. * ```
  14099. *
  14100. * @type {?Node<vec3>}
  14101. * @default null
  14102. */
  14103. this.envNode = null;
  14104. /**
  14105. * The lighting of node materials might be influenced by ambient occlusion.
  14106. * The default AO is inferred from an ambient occlusion map assigned to `aoMap`
  14107. * and the respective `aoMapIntensity`. This node property allows to overwrite
  14108. * the default and define the ambient occlusion with a custom node instead.
  14109. *
  14110. * If you don't want to overwrite the diffuse color but modify the existing
  14111. * values instead, use {@link materialAO}.
  14112. *
  14113. * @type {?Node<float>}
  14114. * @default null
  14115. */
  14116. this.aoNode = null;
  14117. /**
  14118. * The diffuse color of node materials is by default inferred from the
  14119. * `color` and `map` properties. This node property allows to overwrite the default
  14120. * and define the diffuse color with a node instead.
  14121. *
  14122. * ```js
  14123. * material.colorNode = color( 0xff0000 ); // define red color
  14124. * ```
  14125. *
  14126. * If you don't want to overwrite the diffuse color but modify the existing
  14127. * values instead, use {@link materialColor}.
  14128. *
  14129. * ```js
  14130. * material.colorNode = materialColor.mul( color( 0xff0000 ) ); // give diffuse colors a red tint
  14131. * ```
  14132. *
  14133. * @type {?Node<vec3>}
  14134. * @default null
  14135. */
  14136. this.colorNode = null;
  14137. /**
  14138. * The normals of node materials are by default inferred from the `normalMap`/`normalScale`
  14139. * or `bumpMap`/`bumpScale` properties. This node property allows to overwrite the default
  14140. * and define the normals with a node instead.
  14141. *
  14142. * If you don't want to overwrite the normals but modify the existing values instead,
  14143. * use {@link materialNormal}.
  14144. *
  14145. * @type {?Node<vec3>}
  14146. * @default null
  14147. */
  14148. this.normalNode = null;
  14149. /**
  14150. * The opacity of node materials is by default inferred from the `opacity`
  14151. * and `alphaMap` properties. This node property allows to overwrite the default
  14152. * and define the opacity with a node instead.
  14153. *
  14154. * If you don't want to overwrite the opacity but modify the existing
  14155. * value instead, use {@link materialOpacity}.
  14156. *
  14157. * @type {?Node<float>}
  14158. * @default null
  14159. */
  14160. this.opacityNode = null;
  14161. /**
  14162. * This node can be used to implement a variety of filter-like effects. The idea is
  14163. * to store the current rendering into a texture e.g. via `viewportSharedTexture()`, use it
  14164. * to create an arbitrary effect and then assign the node composition to this property.
  14165. * Everything behind the object using this material will now be affected by a filter.
  14166. *
  14167. * ```js
  14168. * const material = new NodeMaterial()
  14169. * material.transparent = true;
  14170. *
  14171. * // everything behind the object will be monochromatic
  14172. * material.backdropNode = saturation( viewportSharedTexture().rgb, 0 );
  14173. * ```
  14174. *
  14175. * Backdrop computations are part of the lighting so only lit materials can use this property.
  14176. *
  14177. * @type {?Node<vec3>}
  14178. * @default null
  14179. */
  14180. this.backdropNode = null;
  14181. /**
  14182. * This node allows to modulate the influence of `backdropNode` to the outgoing light.
  14183. *
  14184. * @type {?Node<float>}
  14185. * @default null
  14186. */
  14187. this.backdropAlphaNode = null;
  14188. /**
  14189. * The alpha test of node materials is by default inferred from the `alphaTest`
  14190. * property. This node property allows to overwrite the default and define the
  14191. * alpha test with a node instead.
  14192. *
  14193. * If you don't want to overwrite the alpha test but modify the existing
  14194. * value instead, use {@link materialAlphaTest}.
  14195. *
  14196. * @type {?Node<float>}
  14197. * @default null
  14198. */
  14199. this.alphaTestNode = null;
  14200. /**
  14201. * Discards the fragment if the mask value is `false`.
  14202. *
  14203. * @type {?Node<bool>}
  14204. * @default null
  14205. */
  14206. this.maskNode = null;
  14207. /**
  14208. * The local vertex positions are computed based on multiple factors like the
  14209. * attribute data, morphing or skinning. This node property allows to overwrite
  14210. * the default and define local vertex positions with nodes instead.
  14211. *
  14212. * If you don't want to overwrite the vertex positions but modify the existing
  14213. * values instead, use {@link positionLocal}.
  14214. *
  14215. *```js
  14216. * material.positionNode = positionLocal.add( displace );
  14217. * ```
  14218. *
  14219. * @type {?Node<vec3>}
  14220. * @default null
  14221. */
  14222. this.positionNode = null;
  14223. /**
  14224. * This node property is intended for logic which modifies geometry data once or per animation step.
  14225. * Apps usually place such logic randomly in initialization routines or in the animation loop.
  14226. * `geometryNode` is intended as a dedicated API so there is an intended spot where geometry modifications
  14227. * can be implemented.
  14228. *
  14229. * The idea is to assign a `Fn` definition that holds the geometry modification logic. A typical example
  14230. * would be a GPU based particle system that provides a node material for usage on app level. The particle
  14231. * simulation would be implemented as compute shaders and managed inside a `Fn` function. This function is
  14232. * eventually assigned to `geometryNode`.
  14233. *
  14234. * @type {?Function}
  14235. * @default null
  14236. */
  14237. this.geometryNode = null;
  14238. /**
  14239. * Allows to overwrite depth values in the fragment shader.
  14240. *
  14241. * @type {?Node<float>}
  14242. * @default null
  14243. */
  14244. this.depthNode = null;
  14245. /**
  14246. * Allows to overwrite the position used for shadow map rendering which
  14247. * is by default {@link positionWorld}, the vertex position
  14248. * in world space.
  14249. *
  14250. * @type {?Node<float>}
  14251. * @default null
  14252. */
  14253. this.receivedShadowPositionNode = null;
  14254. /**
  14255. * Allows to overwrite the geometry position used for shadow map projection which
  14256. * is by default {@link positionLocal}, the vertex position in local space.
  14257. *
  14258. * @type {?Node<float>}
  14259. * @default null
  14260. */
  14261. this.castShadowPositionNode = null;
  14262. /**
  14263. * This node can be used to influence how an object using this node material
  14264. * receive shadows.
  14265. *
  14266. * ```js
  14267. * const totalShadows = float( 1 ).toVar();
  14268. * material.receivedShadowNode = Fn( ( [ shadow ] ) => {
  14269. * totalShadows.mulAssign( shadow );
  14270. * //return float( 1 ); // bypass received shadows
  14271. * return shadow.mix( color( 0xff0000 ), 1 ); // modify shadow color
  14272. * } );
  14273. *
  14274. * @type {?(Function|FunctionNode<vec4>)}
  14275. * @default null
  14276. */
  14277. this.receivedShadowNode = null;
  14278. /**
  14279. * This node can be used to influence how an object using this node material
  14280. * casts shadows. To apply a color to shadows, you can simply do:
  14281. *
  14282. * ```js
  14283. * material.castShadowNode = vec4( 1, 0, 0, 1 );
  14284. * ```
  14285. *
  14286. * Which can be nice to fake colored shadows of semi-transparent objects. It
  14287. * is also common to use the property with `Fn` function so checks are performed
  14288. * per fragment.
  14289. *
  14290. * ```js
  14291. * materialCustomShadow.castShadowNode = Fn( () => {
  14292. * hash( vertexIndex ).greaterThan( 0.5 ).discard();
  14293. * return materialColor;
  14294. * } )();
  14295. * ```
  14296. *
  14297. * @type {?Node<vec4>}
  14298. * @default null
  14299. */
  14300. this.castShadowNode = null;
  14301. /**
  14302. * This node can be used to define the final output of the material.
  14303. *
  14304. * TODO: Explain the differences to `fragmentNode`.
  14305. *
  14306. * @type {?Node<vec4>}
  14307. * @default null
  14308. */
  14309. this.outputNode = null;
  14310. /**
  14311. * MRT configuration is done on renderer or pass level. This node allows to
  14312. * overwrite what values are written into MRT targets on material level. This
  14313. * can be useful for implementing selective FX features that should only affect
  14314. * specific objects.
  14315. *
  14316. * @type {?MRTNode}
  14317. * @default null
  14318. */
  14319. this.mrtNode = null;
  14320. /**
  14321. * This node property can be used if you need complete freedom in implementing
  14322. * the fragment shader. Assigning a node will replace the built-in material
  14323. * logic used in the fragment stage.
  14324. *
  14325. * @type {?Node<vec4>}
  14326. * @default null
  14327. */
  14328. this.fragmentNode = null;
  14329. /**
  14330. * This node property can be used if you need complete freedom in implementing
  14331. * the vertex shader. Assigning a node will replace the built-in material logic
  14332. * used in the vertex stage.
  14333. *
  14334. * @type {?Node<vec4>}
  14335. * @default null
  14336. */
  14337. this.vertexNode = null;
  14338. // Deprecated properties
  14339. Object.defineProperty( this, 'shadowPositionNode', { // @deprecated, r176
  14340. get: () => {
  14341. return this.receivedShadowPositionNode;
  14342. },
  14343. set: ( value ) => {
  14344. warn( 'NodeMaterial: ".shadowPositionNode" was renamed to ".receivedShadowPositionNode".' );
  14345. this.receivedShadowPositionNode = value;
  14346. }
  14347. } );
  14348. }
  14349. /**
  14350. * Returns an array of child nodes for this material.
  14351. *
  14352. * @private
  14353. * @returns {Array<{property: string, childNode: Node}>}
  14354. */
  14355. _getNodeChildren() {
  14356. const children = [];
  14357. for ( const property of Object.getOwnPropertyNames( this ) ) {
  14358. if ( property.startsWith( '_' ) === true ) continue;
  14359. const object = this[ property ];
  14360. if ( object && object.isNode === true ) {
  14361. children.push( { property, childNode: object } );
  14362. }
  14363. }
  14364. return children;
  14365. }
  14366. /**
  14367. * Allows to define a custom cache key that influence the material key computation
  14368. * for render objects.
  14369. *
  14370. * @return {string} The custom cache key.
  14371. */
  14372. customProgramCacheKey() {
  14373. const values = [];
  14374. for ( const { property, childNode } of this._getNodeChildren() ) {
  14375. values.push( hashString( property.slice( 0, -4 ) ), childNode.getCacheKey() );
  14376. }
  14377. return this.type + hashArray( values );
  14378. }
  14379. /**
  14380. * Builds this material with the given node builder.
  14381. *
  14382. * @param {NodeBuilder} builder - The current node builder.
  14383. */
  14384. build( builder ) {
  14385. this.setup( builder );
  14386. }
  14387. /**
  14388. * Setups a node material observer with the given builder.
  14389. *
  14390. * @param {NodeBuilder} builder - The current node builder.
  14391. * @return {NodeMaterialObserver} The node material observer.
  14392. */
  14393. setupObserver( builder ) {
  14394. return new NodeMaterialObserver( builder );
  14395. }
  14396. /**
  14397. * Setups the vertex and fragment stage of this node material.
  14398. *
  14399. * @param {NodeBuilder} builder - The current node builder.
  14400. */
  14401. setup( builder ) {
  14402. builder.context.setupNormal = () => subBuild( this.setupNormal( builder ), 'NORMAL', 'vec3' );
  14403. builder.context.setupPositionView = () => this.setupPositionView( builder );
  14404. builder.context.setupModelViewProjection = () => this.setupModelViewProjection( builder );
  14405. const renderer = builder.renderer;
  14406. const renderTarget = renderer.getRenderTarget();
  14407. // < VERTEX STAGE >
  14408. builder.addStack();
  14409. const mvp = subBuild( this.setupVertex( builder ), 'VERTEX' );
  14410. const vertexNode = this.vertexNode || mvp;
  14411. builder.stack.outputNode = vertexNode;
  14412. this.setupHardwareClipping( builder );
  14413. if ( this.geometryNode !== null ) {
  14414. builder.stack.outputNode = builder.stack.outputNode.bypass( this.geometryNode );
  14415. }
  14416. builder.addFlow( 'vertex', builder.removeStack() );
  14417. // < FRAGMENT STAGE >
  14418. builder.addStack();
  14419. let resultNode;
  14420. const clippingNode = this.setupClipping( builder );
  14421. if ( this.depthWrite === true || this.depthTest === true ) {
  14422. // only write depth if depth buffer is configured
  14423. if ( renderTarget !== null ) {
  14424. if ( renderTarget.depthBuffer === true ) this.setupDepth( builder );
  14425. } else {
  14426. if ( renderer.depth === true ) this.setupDepth( builder );
  14427. }
  14428. }
  14429. if ( this.fragmentNode === null ) {
  14430. this.setupDiffuseColor( builder );
  14431. this.setupVariants( builder );
  14432. const outgoingLightNode = this.setupLighting( builder );
  14433. if ( clippingNode !== null ) builder.stack.addToStack( clippingNode );
  14434. // force unsigned floats - useful for RenderTargets
  14435. const basicOutput = vec4( outgoingLightNode, diffuseColor.a ).max( 0 );
  14436. resultNode = this.setupOutput( builder, basicOutput );
  14437. // OUTPUT NODE
  14438. output.assign( resultNode );
  14439. //
  14440. const isCustomOutput = this.outputNode !== null;
  14441. if ( isCustomOutput ) resultNode = this.outputNode;
  14442. // MRT
  14443. if ( renderTarget !== null ) {
  14444. const mrt = renderer.getMRT();
  14445. const materialMRT = this.mrtNode;
  14446. if ( mrt !== null ) {
  14447. if ( isCustomOutput ) output.assign( resultNode );
  14448. resultNode = mrt;
  14449. if ( materialMRT !== null ) {
  14450. resultNode = mrt.merge( materialMRT );
  14451. }
  14452. } else if ( materialMRT !== null ) {
  14453. resultNode = materialMRT;
  14454. }
  14455. }
  14456. } else {
  14457. let fragmentNode = this.fragmentNode;
  14458. if ( fragmentNode.isOutputStructNode !== true ) {
  14459. fragmentNode = vec4( fragmentNode );
  14460. }
  14461. resultNode = this.setupOutput( builder, fragmentNode );
  14462. }
  14463. builder.stack.outputNode = resultNode;
  14464. builder.addFlow( 'fragment', builder.removeStack() );
  14465. // < OBSERVER >
  14466. builder.observer = this.setupObserver( builder );
  14467. }
  14468. /**
  14469. * Setups the clipping node.
  14470. *
  14471. * @param {NodeBuilder} builder - The current node builder.
  14472. * @return {ClippingNode} The clipping node.
  14473. */
  14474. setupClipping( builder ) {
  14475. if ( builder.clippingContext === null ) return null;
  14476. const { unionPlanes, intersectionPlanes } = builder.clippingContext;
  14477. let result = null;
  14478. if ( unionPlanes.length > 0 || intersectionPlanes.length > 0 ) {
  14479. const samples = builder.renderer.currentSamples;
  14480. if ( this.alphaToCoverage && samples > 1 ) {
  14481. // to be added to flow when the color/alpha value has been determined
  14482. result = clippingAlpha();
  14483. } else {
  14484. builder.stack.addToStack( clipping() );
  14485. }
  14486. }
  14487. return result;
  14488. }
  14489. /**
  14490. * Setups the hardware clipping if available on the current device.
  14491. *
  14492. * @param {NodeBuilder} builder - The current node builder.
  14493. */
  14494. setupHardwareClipping( builder ) {
  14495. this.hardwareClipping = false;
  14496. if ( builder.clippingContext === null ) return;
  14497. const candidateCount = builder.clippingContext.unionPlanes.length;
  14498. // 8 planes supported by WebGL ANGLE_clip_cull_distance and WebGPU clip-distances
  14499. if ( candidateCount > 0 && candidateCount <= 8 && builder.isAvailable( 'clipDistance' ) ) {
  14500. builder.stack.addToStack( hardwareClipping() );
  14501. this.hardwareClipping = true;
  14502. }
  14503. return;
  14504. }
  14505. /**
  14506. * Setups the depth of this material.
  14507. *
  14508. * @param {NodeBuilder} builder - The current node builder.
  14509. */
  14510. setupDepth( builder ) {
  14511. const { renderer, camera } = builder;
  14512. // Depth
  14513. let depthNode = this.depthNode;
  14514. if ( depthNode === null ) {
  14515. const mrt = renderer.getMRT();
  14516. if ( mrt && mrt.has( 'depth' ) ) {
  14517. depthNode = mrt.get( 'depth' );
  14518. } else if ( renderer.logarithmicDepthBuffer === true ) {
  14519. if ( camera.isPerspectiveCamera ) {
  14520. depthNode = viewZToLogarithmicDepth( positionView.z, cameraNear, cameraFar );
  14521. } else {
  14522. depthNode = viewZToOrthographicDepth( positionView.z, cameraNear, cameraFar );
  14523. }
  14524. }
  14525. }
  14526. if ( depthNode !== null ) {
  14527. depth.assign( depthNode ).toStack();
  14528. }
  14529. }
  14530. /**
  14531. * Setups the position node in view space. This method exists
  14532. * so derived node materials can modify the implementation e.g. sprite materials.
  14533. *
  14534. * @param {NodeBuilder} builder - The current node builder.
  14535. * @return {Node<vec3>} The position in view space.
  14536. */
  14537. setupPositionView( /*builder*/ ) {
  14538. return modelViewMatrix.mul( positionLocal ).xyz;
  14539. }
  14540. /**
  14541. * Setups the position in clip space.
  14542. *
  14543. * @param {NodeBuilder} builder - The current node builder.
  14544. * @return {Node<vec4>} The position in view space.
  14545. */
  14546. setupModelViewProjection( /*builder*/ ) {
  14547. return cameraProjectionMatrix.mul( positionView );
  14548. }
  14549. /**
  14550. * Setups the logic for the vertex stage.
  14551. *
  14552. * @param {NodeBuilder} builder - The current node builder.
  14553. * @return {Node<vec4>} The position in clip space.
  14554. */
  14555. setupVertex( builder ) {
  14556. builder.addStack();
  14557. this.setupPosition( builder );
  14558. builder.context.vertex = builder.removeStack();
  14559. return modelViewProjection;
  14560. }
  14561. /**
  14562. * Setups the computation of the position in local space.
  14563. *
  14564. * @param {NodeBuilder} builder - The current node builder.
  14565. * @return {Node<vec3>} The position in local space.
  14566. */
  14567. setupPosition( builder ) {
  14568. const { object, geometry } = builder;
  14569. if ( geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color ) {
  14570. morphReference( object ).toStack();
  14571. }
  14572. if ( object.isSkinnedMesh === true ) {
  14573. skinning( object ).toStack();
  14574. }
  14575. if ( this.displacementMap ) {
  14576. const displacementMap = materialReference( 'displacementMap', 'texture' );
  14577. const displacementScale = materialReference( 'displacementScale', 'float' );
  14578. const displacementBias = materialReference( 'displacementBias', 'float' );
  14579. positionLocal.addAssign( normalLocal.normalize().mul( ( displacementMap.x.mul( displacementScale ).add( displacementBias ) ) ) );
  14580. }
  14581. if ( object.isBatchedMesh ) {
  14582. batch( object ).toStack();
  14583. }
  14584. if ( ( object.isInstancedMesh && object.instanceMatrix && object.instanceMatrix.isInstancedBufferAttribute === true ) ) {
  14585. instancedMesh( object ).toStack();
  14586. }
  14587. if ( this.positionNode !== null ) {
  14588. positionLocal.assign( subBuild( this.positionNode, 'POSITION', 'vec3' ) );
  14589. }
  14590. return positionLocal;
  14591. }
  14592. /**
  14593. * Setups the computation of the material's diffuse color.
  14594. *
  14595. * @param {NodeBuilder} builder - The current node builder.
  14596. * @param {BufferGeometry} geometry - The geometry.
  14597. */
  14598. setupDiffuseColor( builder ) {
  14599. const { object, geometry } = builder;
  14600. // MASK
  14601. if ( this.maskNode !== null ) {
  14602. // Discard if the mask is `false`
  14603. bool( this.maskNode ).not().discard();
  14604. }
  14605. // COLOR
  14606. let colorNode = this.colorNode ? vec4( this.colorNode ) : materialColor;
  14607. // VERTEX COLORS
  14608. if ( this.vertexColors === true && geometry.hasAttribute( 'color' ) ) {
  14609. colorNode = colorNode.mul( vertexColor() );
  14610. }
  14611. // INSTANCED COLORS
  14612. if ( object.instanceColor ) {
  14613. const instanceColor = varyingProperty( 'vec3', 'vInstanceColor' );
  14614. colorNode = instanceColor.mul( colorNode );
  14615. }
  14616. if ( object.isBatchedMesh && object._colorsTexture ) {
  14617. const batchColor = varyingProperty( 'vec3', 'vBatchColor' );
  14618. colorNode = batchColor.mul( colorNode );
  14619. }
  14620. // DIFFUSE COLOR
  14621. diffuseColor.assign( colorNode );
  14622. // OPACITY
  14623. const opacityNode = this.opacityNode ? float( this.opacityNode ) : materialOpacity;
  14624. diffuseColor.a.assign( diffuseColor.a.mul( opacityNode ) );
  14625. // ALPHA TEST
  14626. let alphaTestNode = null;
  14627. if ( this.alphaTestNode !== null || this.alphaTest > 0 ) {
  14628. alphaTestNode = this.alphaTestNode !== null ? float( this.alphaTestNode ) : materialAlphaTest;
  14629. if ( this.alphaToCoverage === true ) {
  14630. diffuseColor.a = smoothstep( alphaTestNode, alphaTestNode.add( fwidth( diffuseColor.a ) ), diffuseColor.a );
  14631. diffuseColor.a.lessThanEqual( 0 ).discard();
  14632. } else {
  14633. diffuseColor.a.lessThanEqual( alphaTestNode ).discard();
  14634. }
  14635. }
  14636. // ALPHA HASH
  14637. if ( this.alphaHash === true ) {
  14638. diffuseColor.a.lessThan( getAlphaHashThreshold( positionLocal ) ).discard();
  14639. }
  14640. // OPAQUE
  14641. if ( builder.isOpaque() ) {
  14642. diffuseColor.a.assign( 1.0 );
  14643. }
  14644. }
  14645. /**
  14646. * Abstract interface method that can be implemented by derived materials
  14647. * to setup material-specific node variables.
  14648. *
  14649. * @abstract
  14650. * @param {NodeBuilder} builder - The current node builder.
  14651. */
  14652. setupVariants( /*builder*/ ) {
  14653. // Interface function.
  14654. }
  14655. /**
  14656. * Setups the outgoing light node variable
  14657. *
  14658. * @return {Node<vec3>} The outgoing light node.
  14659. */
  14660. setupOutgoingLight() {
  14661. return ( this.lights === true ) ? vec3( 0 ) : diffuseColor.rgb;
  14662. }
  14663. /**
  14664. * Setups the normal node from the material.
  14665. *
  14666. * @return {Node<vec3>} The normal node.
  14667. */
  14668. setupNormal() {
  14669. return this.normalNode ? vec3( this.normalNode ) : materialNormal;
  14670. }
  14671. /**
  14672. * Setups the environment node from the material.
  14673. *
  14674. * @param {NodeBuilder} builder - The current node builder.
  14675. * @return {Node<vec4>} The environment node.
  14676. */
  14677. setupEnvironment( /*builder*/ ) {
  14678. let node = null;
  14679. if ( this.envNode ) {
  14680. node = this.envNode;
  14681. } else if ( this.envMap ) {
  14682. node = this.envMap.isCubeTexture ? materialReference( 'envMap', 'cubeTexture' ) : materialReference( 'envMap', 'texture' );
  14683. }
  14684. return node;
  14685. }
  14686. /**
  14687. * Setups the light map node from the material.
  14688. *
  14689. * @param {NodeBuilder} builder - The current node builder.
  14690. * @return {Node<vec3>} The light map node.
  14691. */
  14692. setupLightMap( builder ) {
  14693. let node = null;
  14694. if ( builder.material.lightMap ) {
  14695. node = new IrradianceNode( materialLightMap );
  14696. }
  14697. return node;
  14698. }
  14699. /**
  14700. * Setups the lights node based on the scene, environment and material.
  14701. *
  14702. * @param {NodeBuilder} builder - The current node builder.
  14703. * @return {LightsNode} The lights node.
  14704. */
  14705. setupLights( builder ) {
  14706. const materialLightsNode = [];
  14707. //
  14708. const envNode = this.setupEnvironment( builder );
  14709. if ( envNode && envNode.isLightingNode ) {
  14710. materialLightsNode.push( envNode );
  14711. }
  14712. const lightMapNode = this.setupLightMap( builder );
  14713. if ( lightMapNode && lightMapNode.isLightingNode ) {
  14714. materialLightsNode.push( lightMapNode );
  14715. }
  14716. if ( this.aoNode !== null || builder.material.aoMap ) {
  14717. const aoNode = this.aoNode !== null ? this.aoNode : materialAO;
  14718. materialLightsNode.push( new AONode( aoNode ) );
  14719. }
  14720. let lightsN = this.lightsNode || builder.lightsNode;
  14721. if ( materialLightsNode.length > 0 ) {
  14722. lightsN = builder.renderer.lighting.createNode( [ ...lightsN.getLights(), ...materialLightsNode ] );
  14723. }
  14724. return lightsN;
  14725. }
  14726. /**
  14727. * This method should be implemented by most derived materials
  14728. * since it defines the material's lighting model.
  14729. *
  14730. * @abstract
  14731. * @param {NodeBuilder} builder - The current node builder.
  14732. * @return {LightingModel} The lighting model.
  14733. */
  14734. setupLightingModel( /*builder*/ ) {
  14735. // Interface function.
  14736. }
  14737. /**
  14738. * Setups the outgoing light node.
  14739. *
  14740. * @param {NodeBuilder} builder - The current node builder.
  14741. * @return {Node<vec3>} The outgoing light node.
  14742. */
  14743. setupLighting( builder ) {
  14744. const { material } = builder;
  14745. const { backdropNode, backdropAlphaNode, emissiveNode } = this;
  14746. // OUTGOING LIGHT
  14747. const lights = this.lights === true || this.lightsNode !== null;
  14748. const lightsNode = lights ? this.setupLights( builder ) : null;
  14749. let outgoingLightNode = this.setupOutgoingLight( builder );
  14750. if ( lightsNode && lightsNode.getScope().hasLights ) {
  14751. const lightingModel = this.setupLightingModel( builder ) || null;
  14752. outgoingLightNode = lightingContext( lightsNode, lightingModel, backdropNode, backdropAlphaNode );
  14753. } else if ( backdropNode !== null ) {
  14754. outgoingLightNode = vec3( backdropAlphaNode !== null ? mix( outgoingLightNode, backdropNode, backdropAlphaNode ) : backdropNode );
  14755. }
  14756. // EMISSIVE
  14757. if ( ( emissiveNode && emissiveNode.isNode === true ) || ( material.emissive && material.emissive.isColor === true ) ) {
  14758. emissive.assign( vec3( emissiveNode ? emissiveNode : materialEmissive ) );
  14759. outgoingLightNode = outgoingLightNode.add( emissive );
  14760. }
  14761. return outgoingLightNode;
  14762. }
  14763. /**
  14764. * Setup the fog.
  14765. *
  14766. * @param {NodeBuilder} builder - The current node builder.
  14767. * @param {Node<vec4>} outputNode - The existing output node.
  14768. * @return {Node<vec4>} The output node.
  14769. */
  14770. setupFog( builder, outputNode ) {
  14771. const fogNode = builder.fogNode;
  14772. if ( fogNode ) {
  14773. output.assign( outputNode );
  14774. outputNode = vec4( fogNode.toVar() );
  14775. }
  14776. return outputNode;
  14777. }
  14778. /**
  14779. * Setups premultiplied alpha.
  14780. *
  14781. * @param {NodeBuilder} builder - The current node builder.
  14782. * @param {Node<vec4>} outputNode - The existing output node.
  14783. * @return {Node<vec4>} The output node.
  14784. */
  14785. setupPremultipliedAlpha( builder, outputNode ) {
  14786. return premultiplyAlpha( outputNode );
  14787. }
  14788. /**
  14789. * Setups the output node.
  14790. *
  14791. * @param {NodeBuilder} builder - The current node builder.
  14792. * @param {Node<vec4>} outputNode - The existing output node.
  14793. * @return {Node<vec4>} The output node.
  14794. */
  14795. setupOutput( builder, outputNode ) {
  14796. // FOG
  14797. if ( this.fog === true ) {
  14798. outputNode = this.setupFog( builder, outputNode );
  14799. }
  14800. // PREMULTIPLIED ALPHA
  14801. if ( this.premultipliedAlpha === true ) {
  14802. outputNode = this.setupPremultipliedAlpha( builder, outputNode );
  14803. }
  14804. return outputNode;
  14805. }
  14806. /**
  14807. * Most classic material types have a node pendant e.g. for `MeshBasicMaterial`
  14808. * there is `MeshBasicNodeMaterial`. This utility method is intended for
  14809. * defining all material properties of the classic type in the node type.
  14810. *
  14811. * @param {Material} material - The material to copy properties with their values to this node material.
  14812. */
  14813. setDefaultValues( material ) {
  14814. // This approach is to reuse the native refreshUniforms*
  14815. // and turn available the use of features like transmission and environment in core
  14816. for ( const property in material ) {
  14817. const value = material[ property ];
  14818. if ( this[ property ] === undefined ) {
  14819. this[ property ] = value;
  14820. if ( value && value.clone ) this[ property ] = value.clone();
  14821. }
  14822. }
  14823. const descriptors = Object.getOwnPropertyDescriptors( material.constructor.prototype );
  14824. for ( const key in descriptors ) {
  14825. if ( Object.getOwnPropertyDescriptor( this.constructor.prototype, key ) === undefined &&
  14826. descriptors[ key ].get !== undefined ) {
  14827. Object.defineProperty( this.constructor.prototype, key, descriptors[ key ] );
  14828. }
  14829. }
  14830. }
  14831. /**
  14832. * Serializes this material to JSON.
  14833. *
  14834. * @param {?(Object|string)} meta - The meta information for serialization.
  14835. * @return {Object} The serialized node.
  14836. */
  14837. toJSON( meta ) {
  14838. const isRoot = ( meta === undefined || typeof meta === 'string' );
  14839. if ( isRoot ) {
  14840. meta = {
  14841. textures: {},
  14842. images: {},
  14843. nodes: {}
  14844. };
  14845. }
  14846. const data = Material.prototype.toJSON.call( this, meta );
  14847. data.inputNodes = {};
  14848. for ( const { property, childNode } of this._getNodeChildren() ) {
  14849. data.inputNodes[ property ] = childNode.toJSON( meta ).uuid;
  14850. }
  14851. // TODO: Copied from Object3D.toJSON
  14852. function extractFromCache( cache ) {
  14853. const values = [];
  14854. for ( const key in cache ) {
  14855. const data = cache[ key ];
  14856. delete data.metadata;
  14857. values.push( data );
  14858. }
  14859. return values;
  14860. }
  14861. if ( isRoot ) {
  14862. const textures = extractFromCache( meta.textures );
  14863. const images = extractFromCache( meta.images );
  14864. const nodes = extractFromCache( meta.nodes );
  14865. if ( textures.length > 0 ) data.textures = textures;
  14866. if ( images.length > 0 ) data.images = images;
  14867. if ( nodes.length > 0 ) data.nodes = nodes;
  14868. }
  14869. return data;
  14870. }
  14871. /**
  14872. * Copies the properties of the given node material to this instance.
  14873. *
  14874. * @param {NodeMaterial} source - The material to copy.
  14875. * @return {NodeMaterial} A reference to this node material.
  14876. */
  14877. copy( source ) {
  14878. this.lightsNode = source.lightsNode;
  14879. this.envNode = source.envNode;
  14880. this.aoNode = source.aoNode;
  14881. this.colorNode = source.colorNode;
  14882. this.normalNode = source.normalNode;
  14883. this.opacityNode = source.opacityNode;
  14884. this.backdropNode = source.backdropNode;
  14885. this.backdropAlphaNode = source.backdropAlphaNode;
  14886. this.alphaTestNode = source.alphaTestNode;
  14887. this.maskNode = source.maskNode;
  14888. this.positionNode = source.positionNode;
  14889. this.geometryNode = source.geometryNode;
  14890. this.depthNode = source.depthNode;
  14891. this.receivedShadowPositionNode = source.receivedShadowPositionNode;
  14892. this.castShadowPositionNode = source.castShadowPositionNode;
  14893. this.receivedShadowNode = source.receivedShadowNode;
  14894. this.castShadowNode = source.castShadowNode;
  14895. this.outputNode = source.outputNode;
  14896. this.mrtNode = source.mrtNode;
  14897. this.fragmentNode = source.fragmentNode;
  14898. this.vertexNode = source.vertexNode;
  14899. return super.copy( source );
  14900. }
  14901. }
  14902. const _defaultValues$d = /*@__PURE__*/ new LineBasicMaterial();
  14903. /**
  14904. * Node material version of {@link LineBasicMaterial}.
  14905. *
  14906. * @augments NodeMaterial
  14907. */
  14908. class LineBasicNodeMaterial extends NodeMaterial {
  14909. static get type() {
  14910. return 'LineBasicNodeMaterial';
  14911. }
  14912. /**
  14913. * Constructs a new line basic node material.
  14914. *
  14915. * @param {Object} [parameters] - The configuration parameter.
  14916. */
  14917. constructor( parameters ) {
  14918. super();
  14919. /**
  14920. * This flag can be used for type testing.
  14921. *
  14922. * @type {boolean}
  14923. * @readonly
  14924. * @default true
  14925. */
  14926. this.isLineBasicNodeMaterial = true;
  14927. this.setDefaultValues( _defaultValues$d );
  14928. this.setValues( parameters );
  14929. }
  14930. }
  14931. const _defaultValues$c = /*@__PURE__*/ new LineDashedMaterial();
  14932. /**
  14933. * Node material version of {@link LineDashedMaterial}.
  14934. *
  14935. * @augments NodeMaterial
  14936. */
  14937. class LineDashedNodeMaterial extends NodeMaterial {
  14938. static get type() {
  14939. return 'LineDashedNodeMaterial';
  14940. }
  14941. /**
  14942. * Constructs a new line dashed node material.
  14943. *
  14944. * @param {Object} [parameters] - The configuration parameter.
  14945. */
  14946. constructor( parameters ) {
  14947. super();
  14948. /**
  14949. * This flag can be used for type testing.
  14950. *
  14951. * @type {boolean}
  14952. * @readonly
  14953. * @default true
  14954. */
  14955. this.isLineDashedNodeMaterial = true;
  14956. this.setDefaultValues( _defaultValues$c );
  14957. /**
  14958. * The dash offset.
  14959. *
  14960. * @type {number}
  14961. * @default 0
  14962. */
  14963. this.dashOffset = 0;
  14964. /**
  14965. * The offset of dash materials is by default inferred from the `dashOffset`
  14966. * property. This node property allows to overwrite the default
  14967. * and define the offset with a node instead.
  14968. *
  14969. * If you don't want to overwrite the offset but modify the existing
  14970. * value instead, use {@link materialLineDashOffset}.
  14971. *
  14972. * @type {?Node<float>}
  14973. * @default null
  14974. */
  14975. this.offsetNode = null;
  14976. /**
  14977. * The scale of dash materials is by default inferred from the `scale`
  14978. * property. This node property allows to overwrite the default
  14979. * and define the scale with a node instead.
  14980. *
  14981. * If you don't want to overwrite the scale but modify the existing
  14982. * value instead, use {@link materialLineScale}.
  14983. *
  14984. * @type {?Node<float>}
  14985. * @default null
  14986. */
  14987. this.dashScaleNode = null;
  14988. /**
  14989. * The dash size of dash materials is by default inferred from the `dashSize`
  14990. * property. This node property allows to overwrite the default
  14991. * and define the dash size with a node instead.
  14992. *
  14993. * If you don't want to overwrite the dash size but modify the existing
  14994. * value instead, use {@link materialLineDashSize}.
  14995. *
  14996. * @type {?Node<float>}
  14997. * @default null
  14998. */
  14999. this.dashSizeNode = null;
  15000. /**
  15001. * The gap size of dash materials is by default inferred from the `gapSize`
  15002. * property. This node property allows to overwrite the default
  15003. * and define the gap size with a node instead.
  15004. *
  15005. * If you don't want to overwrite the gap size but modify the existing
  15006. * value instead, use {@link materialLineGapSize}.
  15007. *
  15008. * @type {?Node<float>}
  15009. * @default null
  15010. */
  15011. this.gapSizeNode = null;
  15012. this.setValues( parameters );
  15013. }
  15014. /**
  15015. * Setups the dash specific node variables.
  15016. *
  15017. * @param {NodeBuilder} builder - The current node builder.
  15018. */
  15019. setupVariants( /* builder */ ) {
  15020. const offsetNode = this.offsetNode ? float( this.offsetNode ) : materialLineDashOffset;
  15021. const dashScaleNode = this.dashScaleNode ? float( this.dashScaleNode ) : materialLineScale;
  15022. const dashSizeNode = this.dashSizeNode ? float( this.dashSizeNode ) : materialLineDashSize;
  15023. const gapSizeNode = this.gapSizeNode ? float( this.gapSizeNode ) : materialLineGapSize;
  15024. dashSize.assign( dashSizeNode );
  15025. gapSize.assign( gapSizeNode );
  15026. const vLineDistance = varying( attribute( 'lineDistance' ).mul( dashScaleNode ) );
  15027. const vLineDistanceOffset = offsetNode ? vLineDistance.add( offsetNode ) : vLineDistance;
  15028. vLineDistanceOffset.mod( dashSize.add( gapSize ) ).greaterThan( dashSize ).discard();
  15029. }
  15030. }
  15031. let _sharedFramebuffer = null;
  15032. /**
  15033. * `ViewportTextureNode` creates an internal texture for each node instance. This module
  15034. * shares a texture across all instances of `ViewportSharedTextureNode`. It should
  15035. * be the first choice when using data of the default/screen framebuffer for performance reasons.
  15036. *
  15037. * @augments ViewportTextureNode
  15038. */
  15039. class ViewportSharedTextureNode extends ViewportTextureNode {
  15040. static get type() {
  15041. return 'ViewportSharedTextureNode';
  15042. }
  15043. /**
  15044. * Constructs a new viewport shared texture node.
  15045. *
  15046. * @param {Node} [uvNode=screenUV] - The uv node.
  15047. * @param {?Node} [levelNode=null] - The level node.
  15048. */
  15049. constructor( uvNode = screenUV, levelNode = null ) {
  15050. if ( _sharedFramebuffer === null ) {
  15051. _sharedFramebuffer = new FramebufferTexture();
  15052. }
  15053. super( uvNode, levelNode, _sharedFramebuffer );
  15054. }
  15055. /**
  15056. * Overwritten so the method always returns the unique shared
  15057. * framebuffer texture.
  15058. *
  15059. * @return {FramebufferTexture} The shared framebuffer texture.
  15060. */
  15061. getTextureForReference() {
  15062. return _sharedFramebuffer;
  15063. }
  15064. updateReference() {
  15065. return this;
  15066. }
  15067. }
  15068. /**
  15069. * TSL function for creating a shared viewport texture node.
  15070. *
  15071. * @tsl
  15072. * @function
  15073. * @param {?Node} [uvNode=screenUV] - The uv node.
  15074. * @param {?Node} [levelNode=null] - The level node.
  15075. * @returns {ViewportSharedTextureNode}
  15076. */
  15077. const viewportSharedTexture = /*@__PURE__*/ nodeProxy( ViewportSharedTextureNode ).setParameterLength( 0, 2 );
  15078. const _defaultValues$b = /*@__PURE__*/ new LineDashedMaterial();
  15079. /**
  15080. * This node material can be used to render lines with a size larger than one
  15081. * by representing them as instanced meshes.
  15082. *
  15083. * @augments NodeMaterial
  15084. */
  15085. class Line2NodeMaterial extends NodeMaterial {
  15086. static get type() {
  15087. return 'Line2NodeMaterial';
  15088. }
  15089. /**
  15090. * Constructs a new node material for wide line rendering.
  15091. *
  15092. * @param {Object} [parameters={}] - The configuration parameter.
  15093. */
  15094. constructor( parameters = {} ) {
  15095. super();
  15096. /**
  15097. * This flag can be used for type testing.
  15098. *
  15099. * @type {boolean}
  15100. * @readonly
  15101. * @default true
  15102. */
  15103. this.isLine2NodeMaterial = true;
  15104. this.setDefaultValues( _defaultValues$b );
  15105. /**
  15106. * Whether vertex colors should be used or not.
  15107. *
  15108. * @type {boolean}
  15109. * @default false
  15110. */
  15111. this.useColor = parameters.vertexColors;
  15112. /**
  15113. * The dash offset.
  15114. *
  15115. * @type {number}
  15116. * @default 0
  15117. */
  15118. this.dashOffset = 0;
  15119. /**
  15120. * Defines the lines color.
  15121. *
  15122. * @type {?Node<vec3>}
  15123. * @default null
  15124. */
  15125. this.lineColorNode = null;
  15126. /**
  15127. * Defines the offset.
  15128. *
  15129. * @type {?Node<float>}
  15130. * @default null
  15131. */
  15132. this.offsetNode = null;
  15133. /**
  15134. * Defines the dash scale.
  15135. *
  15136. * @type {?Node<float>}
  15137. * @default null
  15138. */
  15139. this.dashScaleNode = null;
  15140. /**
  15141. * Defines the dash size.
  15142. *
  15143. * @type {?Node<float>}
  15144. * @default null
  15145. */
  15146. this.dashSizeNode = null;
  15147. /**
  15148. * Defines the gap size.
  15149. *
  15150. * @type {?Node<float>}
  15151. * @default null
  15152. */
  15153. this.gapSizeNode = null;
  15154. /**
  15155. * Blending is set to `NoBlending` since transparency
  15156. * is not supported, yet.
  15157. *
  15158. * @type {number}
  15159. * @default 0
  15160. */
  15161. this.blending = NoBlending;
  15162. this._useDash = parameters.dashed;
  15163. this._useAlphaToCoverage = true;
  15164. this._useWorldUnits = false;
  15165. this.setValues( parameters );
  15166. }
  15167. /**
  15168. * Setups the vertex and fragment stage of this node material.
  15169. *
  15170. * @param {NodeBuilder} builder - The current node builder.
  15171. */
  15172. setup( builder ) {
  15173. const { renderer } = builder;
  15174. const useAlphaToCoverage = this._useAlphaToCoverage;
  15175. const useColor = this.useColor;
  15176. const useDash = this._useDash;
  15177. const useWorldUnits = this._useWorldUnits;
  15178. const trimSegment = Fn( ( { start, end } ) => {
  15179. const a = cameraProjectionMatrix.element( 2 ).element( 2 ); // 3nd entry in 3th column
  15180. const b = cameraProjectionMatrix.element( 3 ).element( 2 ); // 3nd entry in 4th column
  15181. const nearEstimate = b.mul( -0.5 ).div( a );
  15182. const alpha = nearEstimate.sub( start.z ).div( end.z.sub( start.z ) );
  15183. return vec4( mix( start.xyz, end.xyz, alpha ), end.w );
  15184. } ).setLayout( {
  15185. name: 'trimSegment',
  15186. type: 'vec4',
  15187. inputs: [
  15188. { name: 'start', type: 'vec4' },
  15189. { name: 'end', type: 'vec4' }
  15190. ]
  15191. } );
  15192. this.vertexNode = Fn( () => {
  15193. const instanceStart = attribute( 'instanceStart' );
  15194. const instanceEnd = attribute( 'instanceEnd' );
  15195. // camera space
  15196. const start = vec4( modelViewMatrix.mul( vec4( instanceStart, 1.0 ) ) ).toVar( 'start' );
  15197. const end = vec4( modelViewMatrix.mul( vec4( instanceEnd, 1.0 ) ) ).toVar( 'end' );
  15198. if ( useDash ) {
  15199. const dashScaleNode = this.dashScaleNode ? float( this.dashScaleNode ) : materialLineScale;
  15200. const offsetNode = this.offsetNode ? float( this.offsetNode ) : materialLineDashOffset;
  15201. const instanceDistanceStart = attribute( 'instanceDistanceStart' );
  15202. const instanceDistanceEnd = attribute( 'instanceDistanceEnd' );
  15203. let lineDistance = positionGeometry.y.lessThan( 0.5 ).select( dashScaleNode.mul( instanceDistanceStart ), dashScaleNode.mul( instanceDistanceEnd ) );
  15204. lineDistance = lineDistance.add( offsetNode );
  15205. varyingProperty( 'float', 'lineDistance' ).assign( lineDistance );
  15206. }
  15207. if ( useWorldUnits ) {
  15208. varyingProperty( 'vec3', 'worldStart' ).assign( start.xyz );
  15209. varyingProperty( 'vec3', 'worldEnd' ).assign( end.xyz );
  15210. }
  15211. const aspect = viewport.z.div( viewport.w );
  15212. // special case for perspective projection, and segments that terminate either in, or behind, the camera plane
  15213. // clearly the gpu firmware has a way of addressing this issue when projecting into ndc space
  15214. // but we need to perform ndc-space calculations in the shader, so we must address this issue directly
  15215. // perhaps there is a more elegant solution -- WestLangley
  15216. const perspective = cameraProjectionMatrix.element( 2 ).element( 3 ).equal( -1 ); // 4th entry in the 3rd column
  15217. If( perspective, () => {
  15218. If( start.z.lessThan( 0.0 ).and( end.z.greaterThan( 0.0 ) ), () => {
  15219. end.assign( trimSegment( { start: start, end: end } ) );
  15220. } ).ElseIf( end.z.lessThan( 0.0 ).and( start.z.greaterThanEqual( 0.0 ) ), () => {
  15221. start.assign( trimSegment( { start: end, end: start } ) );
  15222. } );
  15223. } );
  15224. // clip space
  15225. const clipStart = cameraProjectionMatrix.mul( start );
  15226. const clipEnd = cameraProjectionMatrix.mul( end );
  15227. // ndc space
  15228. const ndcStart = clipStart.xyz.div( clipStart.w );
  15229. const ndcEnd = clipEnd.xyz.div( clipEnd.w );
  15230. // direction
  15231. const dir = ndcEnd.xy.sub( ndcStart.xy ).toVar();
  15232. // account for clip-space aspect ratio
  15233. dir.x.assign( dir.x.mul( aspect ) );
  15234. dir.assign( dir.normalize() );
  15235. const clip = vec4().toVar();
  15236. if ( useWorldUnits ) {
  15237. // get the offset direction as perpendicular to the view vector
  15238. const worldDir = end.xyz.sub( start.xyz ).normalize();
  15239. const tmpFwd = mix( start.xyz, end.xyz, 0.5 ).normalize();
  15240. const worldUp = worldDir.cross( tmpFwd ).normalize();
  15241. const worldFwd = worldDir.cross( worldUp );
  15242. const worldPos = varyingProperty( 'vec4', 'worldPos' );
  15243. worldPos.assign( positionGeometry.y.lessThan( 0.5 ).select( start, end ) );
  15244. // height offset
  15245. const hw = materialLineWidth.mul( 0.5 );
  15246. worldPos.addAssign( vec4( positionGeometry.x.lessThan( 0.0 ).select( worldUp.mul( hw ), worldUp.mul( hw ).negate() ), 0 ) );
  15247. // don't extend the line if we're rendering dashes because we
  15248. // won't be rendering the endcaps
  15249. if ( ! useDash ) {
  15250. // cap extension
  15251. worldPos.addAssign( vec4( positionGeometry.y.lessThan( 0.5 ).select( worldDir.mul( hw ).negate(), worldDir.mul( hw ) ), 0 ) );
  15252. // add width to the box
  15253. worldPos.addAssign( vec4( worldFwd.mul( hw ), 0 ) );
  15254. // endcaps
  15255. If( positionGeometry.y.greaterThan( 1.0 ).or( positionGeometry.y.lessThan( 0.0 ) ), () => {
  15256. worldPos.subAssign( vec4( worldFwd.mul( 2.0 ).mul( hw ), 0 ) );
  15257. } );
  15258. }
  15259. // project the worldpos
  15260. clip.assign( cameraProjectionMatrix.mul( worldPos ) );
  15261. // shift the depth of the projected points so the line
  15262. // segments overlap neatly
  15263. const clipPose = vec3().toVar();
  15264. clipPose.assign( positionGeometry.y.lessThan( 0.5 ).select( ndcStart, ndcEnd ) );
  15265. clip.z.assign( clipPose.z.mul( clip.w ) );
  15266. } else {
  15267. const offset = vec2( dir.y, dir.x.negate() ).toVar( 'offset' );
  15268. // undo aspect ratio adjustment
  15269. dir.x.assign( dir.x.div( aspect ) );
  15270. offset.x.assign( offset.x.div( aspect ) );
  15271. // sign flip
  15272. offset.assign( positionGeometry.x.lessThan( 0.0 ).select( offset.negate(), offset ) );
  15273. // endcaps
  15274. If( positionGeometry.y.lessThan( 0.0 ), () => {
  15275. offset.assign( offset.sub( dir ) );
  15276. } ).ElseIf( positionGeometry.y.greaterThan( 1.0 ), () => {
  15277. offset.assign( offset.add( dir ) );
  15278. } );
  15279. // adjust for linewidth
  15280. offset.assign( offset.mul( materialLineWidth ) );
  15281. // adjust for clip-space to screen-space conversion // maybe resolution should be based on viewport ...
  15282. offset.assign( offset.div( viewport.w ) );
  15283. // select end
  15284. clip.assign( positionGeometry.y.lessThan( 0.5 ).select( clipStart, clipEnd ) );
  15285. // back to clip space
  15286. offset.assign( offset.mul( clip.w ) );
  15287. clip.assign( clip.add( vec4( offset, 0, 0 ) ) );
  15288. }
  15289. return clip;
  15290. } )();
  15291. const closestLineToLine = Fn( ( { p1, p2, p3, p4 } ) => {
  15292. const p13 = p1.sub( p3 );
  15293. const p43 = p4.sub( p3 );
  15294. const p21 = p2.sub( p1 );
  15295. const d1343 = p13.dot( p43 );
  15296. const d4321 = p43.dot( p21 );
  15297. const d1321 = p13.dot( p21 );
  15298. const d4343 = p43.dot( p43 );
  15299. const d2121 = p21.dot( p21 );
  15300. const denom = d2121.mul( d4343 ).sub( d4321.mul( d4321 ) );
  15301. const numer = d1343.mul( d4321 ).sub( d1321.mul( d4343 ) );
  15302. const mua = numer.div( denom ).clamp();
  15303. const mub = d1343.add( d4321.mul( mua ) ).div( d4343 ).clamp();
  15304. return vec2( mua, mub );
  15305. } );
  15306. this.colorNode = Fn( () => {
  15307. const vUv = uv$1();
  15308. if ( useDash ) {
  15309. const dashSizeNode = this.dashSizeNode ? float( this.dashSizeNode ) : materialLineDashSize;
  15310. const gapSizeNode = this.gapSizeNode ? float( this.gapSizeNode ) : materialLineGapSize;
  15311. dashSize.assign( dashSizeNode );
  15312. gapSize.assign( gapSizeNode );
  15313. const vLineDistance = varyingProperty( 'float', 'lineDistance' );
  15314. vUv.y.lessThan( -1 ).or( vUv.y.greaterThan( 1.0 ) ).discard(); // discard endcaps
  15315. vLineDistance.mod( dashSize.add( gapSize ) ).greaterThan( dashSize ).discard(); // todo - FIX
  15316. }
  15317. const alpha = float( 1 ).toVar( 'alpha' );
  15318. if ( useWorldUnits ) {
  15319. const worldStart = varyingProperty( 'vec3', 'worldStart' );
  15320. const worldEnd = varyingProperty( 'vec3', 'worldEnd' );
  15321. // Find the closest points on the view ray and the line segment
  15322. const rayEnd = varyingProperty( 'vec4', 'worldPos' ).xyz.normalize().mul( 1e5 );
  15323. const lineDir = worldEnd.sub( worldStart );
  15324. const params = closestLineToLine( { p1: worldStart, p2: worldEnd, p3: vec3( 0.0, 0.0, 0.0 ), p4: rayEnd } );
  15325. const p1 = worldStart.add( lineDir.mul( params.x ) );
  15326. const p2 = rayEnd.mul( params.y );
  15327. const delta = p1.sub( p2 );
  15328. const len = delta.length();
  15329. const norm = len.div( materialLineWidth );
  15330. if ( ! useDash ) {
  15331. if ( useAlphaToCoverage && renderer.currentSamples > 0 ) {
  15332. const dnorm = norm.fwidth();
  15333. alpha.assign( smoothstep( dnorm.negate().add( 0.5 ), dnorm.add( 0.5 ), norm ).oneMinus() );
  15334. } else {
  15335. norm.greaterThan( 0.5 ).discard();
  15336. }
  15337. }
  15338. } else {
  15339. // round endcaps
  15340. if ( useAlphaToCoverage && renderer.currentSamples > 0 ) {
  15341. const a = vUv.x;
  15342. const b = vUv.y.greaterThan( 0.0 ).select( vUv.y.sub( 1.0 ), vUv.y.add( 1.0 ) );
  15343. const len2 = a.mul( a ).add( b.mul( b ) );
  15344. const dlen = float( len2.fwidth() ).toVar( 'dlen' );
  15345. If( vUv.y.abs().greaterThan( 1.0 ), () => {
  15346. alpha.assign( smoothstep( dlen.oneMinus(), dlen.add( 1 ), len2 ).oneMinus() );
  15347. } );
  15348. } else {
  15349. If( vUv.y.abs().greaterThan( 1.0 ), () => {
  15350. const a = vUv.x;
  15351. const b = vUv.y.greaterThan( 0.0 ).select( vUv.y.sub( 1.0 ), vUv.y.add( 1.0 ) );
  15352. const len2 = a.mul( a ).add( b.mul( b ) );
  15353. len2.greaterThan( 1.0 ).discard();
  15354. } );
  15355. }
  15356. }
  15357. let lineColorNode;
  15358. if ( this.lineColorNode ) {
  15359. lineColorNode = this.lineColorNode;
  15360. } else {
  15361. if ( useColor ) {
  15362. const instanceColorStart = attribute( 'instanceColorStart' );
  15363. const instanceColorEnd = attribute( 'instanceColorEnd' );
  15364. const instanceColor = positionGeometry.y.lessThan( 0.5 ).select( instanceColorStart, instanceColorEnd );
  15365. lineColorNode = instanceColor.mul( materialColor );
  15366. } else {
  15367. lineColorNode = materialColor;
  15368. }
  15369. }
  15370. return vec4( lineColorNode, alpha );
  15371. } )();
  15372. if ( this.transparent ) {
  15373. const opacityNode = this.opacityNode ? float( this.opacityNode ) : materialOpacity;
  15374. this.outputNode = vec4( this.colorNode.rgb.mul( opacityNode ).add( viewportSharedTexture().rgb.mul( opacityNode.oneMinus() ) ), this.colorNode.a );
  15375. }
  15376. super.setup( builder );
  15377. }
  15378. /**
  15379. * Whether the lines should sized in world units or not.
  15380. * When set to `false` the unit is pixel.
  15381. *
  15382. * @type {boolean}
  15383. * @default false
  15384. */
  15385. get worldUnits() {
  15386. return this._useWorldUnits;
  15387. }
  15388. set worldUnits( value ) {
  15389. if ( this._useWorldUnits !== value ) {
  15390. this._useWorldUnits = value;
  15391. this.needsUpdate = true;
  15392. }
  15393. }
  15394. /**
  15395. * Whether the lines should be dashed or not.
  15396. *
  15397. * @type {boolean}
  15398. * @default false
  15399. */
  15400. get dashed() {
  15401. return this._useDash;
  15402. }
  15403. set dashed( value ) {
  15404. if ( this._useDash !== value ) {
  15405. this._useDash = value;
  15406. this.needsUpdate = true;
  15407. }
  15408. }
  15409. /**
  15410. * Whether alpha to coverage should be used or not.
  15411. *
  15412. * @type {boolean}
  15413. * @default true
  15414. */
  15415. get alphaToCoverage() {
  15416. return this._useAlphaToCoverage;
  15417. }
  15418. set alphaToCoverage( value ) {
  15419. if ( this._useAlphaToCoverage !== value ) {
  15420. this._useAlphaToCoverage = value;
  15421. this.needsUpdate = true;
  15422. }
  15423. }
  15424. }
  15425. /**
  15426. * Packs a direction vector into a color value.
  15427. *
  15428. * @tsl
  15429. * @function
  15430. * @param {Node<vec3>} node - The direction to pack.
  15431. * @return {Node<vec3>} The color.
  15432. */
  15433. const directionToColor = ( node ) => nodeObject( node ).mul( 0.5 ).add( 0.5 );
  15434. /**
  15435. * Unpacks a color value into a direction vector.
  15436. *
  15437. * @tsl
  15438. * @function
  15439. * @param {Node<vec3>} node - The color to unpack.
  15440. * @return {Node<vec3>} The direction.
  15441. */
  15442. const colorToDirection = ( node ) => nodeObject( node ).mul( 2.0 ).sub( 1 );
  15443. const _defaultValues$a = /*@__PURE__*/ new MeshNormalMaterial();
  15444. /**
  15445. * Node material version of {@link MeshNormalMaterial}.
  15446. *
  15447. * @augments NodeMaterial
  15448. */
  15449. class MeshNormalNodeMaterial extends NodeMaterial {
  15450. static get type() {
  15451. return 'MeshNormalNodeMaterial';
  15452. }
  15453. /**
  15454. * Constructs a new mesh normal node material.
  15455. *
  15456. * @param {Object} [parameters] - The configuration parameter.
  15457. */
  15458. constructor( parameters ) {
  15459. super();
  15460. /**
  15461. * This flag can be used for type testing.
  15462. *
  15463. * @type {boolean}
  15464. * @readonly
  15465. * @default true
  15466. */
  15467. this.isMeshNormalNodeMaterial = true;
  15468. this.setDefaultValues( _defaultValues$a );
  15469. this.setValues( parameters );
  15470. }
  15471. /**
  15472. * Overwrites the default implementation by computing the diffuse color
  15473. * based on the normal data.
  15474. */
  15475. setupDiffuseColor() {
  15476. const opacityNode = this.opacityNode ? float( this.opacityNode ) : materialOpacity;
  15477. // By convention, a normal packed to RGB is in sRGB color space. Convert it to working color space.
  15478. diffuseColor.assign( colorSpaceToWorking( vec4( directionToColor( normalView ), opacityNode ), SRGBColorSpace ) );
  15479. }
  15480. }
  15481. /**
  15482. * TSL function for creating an equirect uv node.
  15483. *
  15484. * Can be used to compute texture coordinates for projecting an
  15485. * equirectangular texture onto a mesh for using it as the scene's
  15486. * background.
  15487. *
  15488. * ```js
  15489. * scene.backgroundNode = texture( equirectTexture, equirectUV() );
  15490. * ```
  15491. *
  15492. * @tsl
  15493. * @function
  15494. * @param {?Node<vec3>} [dirNode=positionWorldDirection] - A direction vector for sampling which is by default `positionWorldDirection`.
  15495. * @returns {Node<vec2>}
  15496. */
  15497. const equirectUV = /*@__PURE__*/ Fn( ( [ dir = positionWorldDirection ] ) => {
  15498. const u = dir.z.atan( dir.x ).mul( 1 / ( Math.PI * 2 ) ).add( 0.5 );
  15499. const v = dir.y.clamp( -1, 1.0 ).asin().mul( 1 / Math.PI ).add( 0.5 );
  15500. return vec2( u, v );
  15501. } );
  15502. // @TODO: Consider rename WebGLCubeRenderTarget to just CubeRenderTarget
  15503. /**
  15504. * This class represents a cube render target. It is a special version
  15505. * of `WebGLCubeRenderTarget` which is compatible with `WebGPURenderer`.
  15506. *
  15507. * @augments WebGLCubeRenderTarget
  15508. */
  15509. class CubeRenderTarget extends WebGLCubeRenderTarget {
  15510. /**
  15511. * Constructs a new cube render target.
  15512. *
  15513. * @param {number} [size=1] - The size of the render target.
  15514. * @param {RenderTarget~Options} [options] - The configuration object.
  15515. */
  15516. constructor( size = 1, options = {} ) {
  15517. super( size, options );
  15518. /**
  15519. * This flag can be used for type testing.
  15520. *
  15521. * @type {boolean}
  15522. * @readonly
  15523. * @default true
  15524. */
  15525. this.isCubeRenderTarget = true;
  15526. }
  15527. /**
  15528. * Converts the given equirectangular texture to a cube map.
  15529. *
  15530. * @param {Renderer} renderer - The renderer.
  15531. * @param {Texture} texture - The equirectangular texture.
  15532. * @return {CubeRenderTarget} A reference to this cube render target.
  15533. */
  15534. fromEquirectangularTexture( renderer, texture$1 ) {
  15535. const currentMinFilter = texture$1.minFilter;
  15536. const currentGenerateMipmaps = texture$1.generateMipmaps;
  15537. texture$1.generateMipmaps = true;
  15538. this.texture.type = texture$1.type;
  15539. this.texture.colorSpace = texture$1.colorSpace;
  15540. this.texture.generateMipmaps = texture$1.generateMipmaps;
  15541. this.texture.minFilter = texture$1.minFilter;
  15542. this.texture.magFilter = texture$1.magFilter;
  15543. const geometry = new BoxGeometry( 5, 5, 5 );
  15544. const uvNode = equirectUV( positionWorldDirection );
  15545. const material = new NodeMaterial();
  15546. material.colorNode = texture( texture$1, uvNode, 0 );
  15547. material.side = BackSide;
  15548. material.blending = NoBlending;
  15549. const mesh = new Mesh( geometry, material );
  15550. const scene = new Scene();
  15551. scene.add( mesh );
  15552. // Avoid blurred poles
  15553. if ( texture$1.minFilter === LinearMipmapLinearFilter ) texture$1.minFilter = LinearFilter;
  15554. const camera = new CubeCamera( 1, 10, this );
  15555. const currentMRT = renderer.getMRT();
  15556. renderer.setMRT( null );
  15557. camera.update( renderer, scene );
  15558. renderer.setMRT( currentMRT );
  15559. texture$1.minFilter = currentMinFilter;
  15560. texture$1.currentGenerateMipmaps = currentGenerateMipmaps;
  15561. mesh.geometry.dispose();
  15562. mesh.material.dispose();
  15563. return this;
  15564. }
  15565. }
  15566. const _cache$1 = new WeakMap();
  15567. /**
  15568. * This node can be used to automatically convert environment maps in the
  15569. * equirectangular format into the cube map format.
  15570. *
  15571. * @augments TempNode
  15572. */
  15573. class CubeMapNode extends TempNode {
  15574. static get type() {
  15575. return 'CubeMapNode';
  15576. }
  15577. /**
  15578. * Constructs a new cube map node.
  15579. *
  15580. * @param {Node} envNode - The node representing the environment map.
  15581. */
  15582. constructor( envNode ) {
  15583. super( 'vec3' );
  15584. /**
  15585. * The node representing the environment map.
  15586. *
  15587. * @type {Node}
  15588. */
  15589. this.envNode = envNode;
  15590. /**
  15591. * A reference to the internal cube texture.
  15592. *
  15593. * @private
  15594. * @type {?CubeTexture}
  15595. * @default null
  15596. */
  15597. this._cubeTexture = null;
  15598. /**
  15599. * A reference to the internal cube texture node.
  15600. *
  15601. * @private
  15602. * @type {CubeTextureNode}
  15603. */
  15604. this._cubeTextureNode = cubeTexture( null );
  15605. const defaultTexture = new CubeTexture();
  15606. defaultTexture.isRenderTargetTexture = true;
  15607. /**
  15608. * A default cube texture that acts as a placeholder.
  15609. * It is used when the conversion from equirectangular to cube
  15610. * map has not finished yet for a given texture.
  15611. *
  15612. * @private
  15613. * @type {CubeTexture}
  15614. */
  15615. this._defaultTexture = defaultTexture;
  15616. /**
  15617. * The `updateBeforeType` is set to `NodeUpdateType.RENDER` since the node updates
  15618. * the texture once per render in its {@link CubeMapNode#updateBefore} method.
  15619. *
  15620. * @type {string}
  15621. * @default 'render'
  15622. */
  15623. this.updateBeforeType = NodeUpdateType.RENDER;
  15624. }
  15625. updateBefore( frame ) {
  15626. const { renderer, material } = frame;
  15627. const envNode = this.envNode;
  15628. if ( envNode.isTextureNode || envNode.isMaterialReferenceNode ) {
  15629. const texture = ( envNode.isTextureNode ) ? envNode.value : material[ envNode.property ];
  15630. if ( texture && texture.isTexture ) {
  15631. const mapping = texture.mapping;
  15632. if ( mapping === EquirectangularReflectionMapping || mapping === EquirectangularRefractionMapping ) {
  15633. // check for converted cubemap map
  15634. if ( _cache$1.has( texture ) ) {
  15635. const cubeMap = _cache$1.get( texture );
  15636. mapTextureMapping( cubeMap, texture.mapping );
  15637. this._cubeTexture = cubeMap;
  15638. } else {
  15639. // create cube map from equirectangular map
  15640. const image = texture.image;
  15641. if ( isEquirectangularMapReady$1( image ) ) {
  15642. const renderTarget = new CubeRenderTarget( image.height );
  15643. renderTarget.fromEquirectangularTexture( renderer, texture );
  15644. mapTextureMapping( renderTarget.texture, texture.mapping );
  15645. this._cubeTexture = renderTarget.texture;
  15646. _cache$1.set( texture, renderTarget.texture );
  15647. texture.addEventListener( 'dispose', onTextureDispose );
  15648. } else {
  15649. // default cube texture as fallback when equirectangular texture is not yet loaded
  15650. this._cubeTexture = this._defaultTexture;
  15651. }
  15652. }
  15653. //
  15654. this._cubeTextureNode.value = this._cubeTexture;
  15655. } else {
  15656. // envNode already refers to a cube map
  15657. this._cubeTextureNode = this.envNode;
  15658. }
  15659. }
  15660. }
  15661. }
  15662. setup( builder ) {
  15663. this.updateBefore( builder );
  15664. return this._cubeTextureNode;
  15665. }
  15666. }
  15667. /**
  15668. * Returns true if the given equirectangular image has been fully loaded
  15669. * and is ready for further processing.
  15670. *
  15671. * @private
  15672. * @param {Image} image - The equirectangular image to check.
  15673. * @return {boolean} Whether the image is ready or not.
  15674. */
  15675. function isEquirectangularMapReady$1( image ) {
  15676. if ( image === null || image === undefined ) return false;
  15677. return image.height > 0;
  15678. }
  15679. /**
  15680. * This function is executed when `dispose()` is called on the equirectangular
  15681. * texture. In this case, the generated cube map with its render target
  15682. * is deleted as well.
  15683. *
  15684. * @private
  15685. * @param {Object} event - The event object.
  15686. */
  15687. function onTextureDispose( event ) {
  15688. const texture = event.target;
  15689. texture.removeEventListener( 'dispose', onTextureDispose );
  15690. const renderTarget = _cache$1.get( texture );
  15691. if ( renderTarget !== undefined ) {
  15692. _cache$1.delete( texture );
  15693. renderTarget.dispose();
  15694. }
  15695. }
  15696. /**
  15697. * This function makes sure the generated cube map uses the correct
  15698. * texture mapping that corresponds to the equirectangular original.
  15699. *
  15700. * @private
  15701. * @param {Texture} texture - The cube texture.
  15702. * @param {number} mapping - The original texture mapping.
  15703. */
  15704. function mapTextureMapping( texture, mapping ) {
  15705. if ( mapping === EquirectangularReflectionMapping ) {
  15706. texture.mapping = CubeReflectionMapping;
  15707. } else if ( mapping === EquirectangularRefractionMapping ) {
  15708. texture.mapping = CubeRefractionMapping;
  15709. }
  15710. }
  15711. /**
  15712. * TSL function for creating a cube map node.
  15713. *
  15714. * @tsl
  15715. * @function
  15716. * @param {Node} envNode - The node representing the environment map.
  15717. * @returns {CubeMapNode}
  15718. */
  15719. const cubeMapNode = /*@__PURE__*/ nodeProxy( CubeMapNode ).setParameterLength( 1 );
  15720. /**
  15721. * Represents a basic model for Image-based lighting (IBL). The environment
  15722. * is defined via environment maps in the equirectangular or cube map format.
  15723. * `BasicEnvironmentNode` is intended for non-PBR materials like {@link MeshBasicNodeMaterial}
  15724. * or {@link MeshPhongNodeMaterial}.
  15725. *
  15726. * @augments LightingNode
  15727. */
  15728. class BasicEnvironmentNode extends LightingNode {
  15729. static get type() {
  15730. return 'BasicEnvironmentNode';
  15731. }
  15732. /**
  15733. * Constructs a new basic environment node.
  15734. *
  15735. * @param {Node} [envNode=null] - A node representing the environment.
  15736. */
  15737. constructor( envNode = null ) {
  15738. super();
  15739. /**
  15740. * A node representing the environment.
  15741. *
  15742. * @type {Node}
  15743. * @default null
  15744. */
  15745. this.envNode = envNode;
  15746. }
  15747. setup( builder ) {
  15748. // environment property is used in the finish() method of BasicLightingModel
  15749. builder.context.environment = cubeMapNode( this.envNode );
  15750. }
  15751. }
  15752. /**
  15753. * A specific version of {@link IrradianceNode} that is only relevant
  15754. * for {@link MeshBasicNodeMaterial}. Since the material is unlit, it
  15755. * requires a special scaling factor for the light map.
  15756. *
  15757. * @augments LightingNode
  15758. */
  15759. class BasicLightMapNode extends LightingNode {
  15760. static get type() {
  15761. return 'BasicLightMapNode';
  15762. }
  15763. /**
  15764. * Constructs a new basic light map node.
  15765. *
  15766. * @param {?Node<vec3>} [lightMapNode=null] - The light map node.
  15767. */
  15768. constructor( lightMapNode = null ) {
  15769. super();
  15770. /**
  15771. * The light map node.
  15772. *
  15773. * @type {?Node<vec3>}
  15774. */
  15775. this.lightMapNode = lightMapNode;
  15776. }
  15777. setup( builder ) {
  15778. // irradianceLightMap property is used in the indirectDiffuse() method of BasicLightingModel
  15779. const RECIPROCAL_PI = float( 1 / Math.PI );
  15780. builder.context.irradianceLightMap = this.lightMapNode.mul( RECIPROCAL_PI );
  15781. }
  15782. }
  15783. /**
  15784. * Abstract class for implementing lighting models. The module defines
  15785. * multiple methods that concrete lighting models can implement. These
  15786. * methods are executed at different points during the light evaluation
  15787. * process.
  15788. */
  15789. class LightingModel {
  15790. /**
  15791. * This method is intended for setting up lighting model and context data
  15792. * which are later used in the evaluation process.
  15793. *
  15794. * @abstract
  15795. * @param {NodeBuilder} builder - The current node builder.
  15796. */
  15797. start( builder ) {
  15798. // lights ( direct )
  15799. builder.lightsNode.setupLights( builder, builder.lightsNode.getLightNodes( builder ) );
  15800. // indirect
  15801. this.indirect( builder );
  15802. }
  15803. /**
  15804. * This method is intended for executing final tasks like final updates
  15805. * to the outgoing light.
  15806. *
  15807. * @abstract
  15808. * @param {NodeBuilder} builder - The current node builder.
  15809. */
  15810. finish( /*builder*/ ) { }
  15811. /**
  15812. * This method is intended for implementing the direct light term and
  15813. * executed during the build process of directional, point and spot light nodes.
  15814. *
  15815. * @abstract
  15816. * @param {Object} lightData - The light data.
  15817. * @param {NodeBuilder} builder - The current node builder.
  15818. */
  15819. direct( /*lightData, builder*/ ) { }
  15820. /**
  15821. * This method is intended for implementing the direct light term for
  15822. * rect area light nodes.
  15823. *
  15824. * @abstract
  15825. * @param {Object} lightData - The light data.
  15826. * @param {NodeBuilder} builder - The current node builder.
  15827. */
  15828. directRectArea( /*lightData, builder*/ ) {}
  15829. /**
  15830. * This method is intended for implementing the indirect light term.
  15831. *
  15832. * @abstract
  15833. * @param {NodeBuilder} builder - The current node builder.
  15834. */
  15835. indirect( /*builder*/ ) { }
  15836. /**
  15837. * This method is intended for implementing the ambient occlusion term.
  15838. * Unlike other methods, this method must be called manually by the lighting
  15839. * model in its indirect term.
  15840. *
  15841. * @abstract
  15842. * @param {NodeBuilder} builder - The current node builder.
  15843. */
  15844. ambientOcclusion( /*input, stack, builder*/ ) { }
  15845. }
  15846. /**
  15847. * Represents the lighting model for unlit materials. The only light contribution
  15848. * is baked indirect lighting modulated with ambient occlusion and the material's
  15849. * diffuse color. Environment mapping is supported. Used in {@link MeshBasicNodeMaterial}.
  15850. *
  15851. * @augments LightingModel
  15852. */
  15853. class BasicLightingModel extends LightingModel {
  15854. /**
  15855. * Constructs a new basic lighting model.
  15856. */
  15857. constructor() {
  15858. super();
  15859. }
  15860. /**
  15861. * Implements the baked indirect lighting with its modulation.
  15862. *
  15863. * @param {NodeBuilder} builder - The current node builder.
  15864. */
  15865. indirect( { context } ) {
  15866. const ambientOcclusion = context.ambientOcclusion;
  15867. const reflectedLight = context.reflectedLight;
  15868. const irradianceLightMap = context.irradianceLightMap;
  15869. reflectedLight.indirectDiffuse.assign( vec4( 0.0 ) );
  15870. // accumulation (baked indirect lighting only)
  15871. if ( irradianceLightMap ) {
  15872. reflectedLight.indirectDiffuse.addAssign( irradianceLightMap );
  15873. } else {
  15874. reflectedLight.indirectDiffuse.addAssign( vec4( 1.0, 1.0, 1.0, 0.0 ) );
  15875. }
  15876. // modulation
  15877. reflectedLight.indirectDiffuse.mulAssign( ambientOcclusion );
  15878. reflectedLight.indirectDiffuse.mulAssign( diffuseColor.rgb );
  15879. }
  15880. /**
  15881. * Implements the environment mapping.
  15882. *
  15883. * @param {NodeBuilder} builder - The current node builder.
  15884. */
  15885. finish( builder ) {
  15886. const { material, context } = builder;
  15887. const outgoingLight = context.outgoingLight;
  15888. const envNode = builder.context.environment;
  15889. if ( envNode ) {
  15890. switch ( material.combine ) {
  15891. case MultiplyOperation:
  15892. outgoingLight.rgb.assign( mix( outgoingLight.rgb, outgoingLight.rgb.mul( envNode.rgb ), materialSpecularStrength.mul( materialReflectivity ) ) );
  15893. break;
  15894. case MixOperation:
  15895. outgoingLight.rgb.assign( mix( outgoingLight.rgb, envNode.rgb, materialSpecularStrength.mul( materialReflectivity ) ) );
  15896. break;
  15897. case AddOperation:
  15898. outgoingLight.rgb.addAssign( envNode.rgb.mul( materialSpecularStrength.mul( materialReflectivity ) ) );
  15899. break;
  15900. default:
  15901. warn( 'BasicLightingModel: Unsupported .combine value:', material.combine );
  15902. break;
  15903. }
  15904. }
  15905. }
  15906. }
  15907. const _defaultValues$9 = /*@__PURE__*/ new MeshBasicMaterial();
  15908. /**
  15909. * Node material version of {@link MeshBasicMaterial}.
  15910. *
  15911. * @augments NodeMaterial
  15912. */
  15913. class MeshBasicNodeMaterial extends NodeMaterial {
  15914. static get type() {
  15915. return 'MeshBasicNodeMaterial';
  15916. }
  15917. /**
  15918. * Constructs a new mesh basic node material.
  15919. *
  15920. * @param {Object} [parameters] - The configuration parameter.
  15921. */
  15922. constructor( parameters ) {
  15923. super();
  15924. /**
  15925. * This flag can be used for type testing.
  15926. *
  15927. * @type {boolean}
  15928. * @readonly
  15929. * @default true
  15930. */
  15931. this.isMeshBasicNodeMaterial = true;
  15932. /**
  15933. * Although the basic material is by definition unlit, we set
  15934. * this property to `true` since we use a lighting model to compute
  15935. * the outgoing light of the fragment shader.
  15936. *
  15937. * @type {boolean}
  15938. * @default true
  15939. */
  15940. this.lights = true;
  15941. this.setDefaultValues( _defaultValues$9 );
  15942. this.setValues( parameters );
  15943. }
  15944. /**
  15945. * Basic materials are not affected by normal and bump maps so we
  15946. * return by default {@link normalViewGeometry}.
  15947. *
  15948. * @return {Node<vec3>} The normal node.
  15949. */
  15950. setupNormal() {
  15951. return directionToFaceDirection( normalViewGeometry ); // see #28839
  15952. }
  15953. /**
  15954. * Overwritten since this type of material uses {@link BasicEnvironmentNode}
  15955. * to implement the default environment mapping.
  15956. *
  15957. * @param {NodeBuilder} builder - The current node builder.
  15958. * @return {?BasicEnvironmentNode<vec3>} The environment node.
  15959. */
  15960. setupEnvironment( builder ) {
  15961. const envNode = super.setupEnvironment( builder );
  15962. return envNode ? new BasicEnvironmentNode( envNode ) : null;
  15963. }
  15964. /**
  15965. * This method must be overwritten since light maps are evaluated
  15966. * with a special scaling factor for basic materials.
  15967. *
  15968. * @param {NodeBuilder} builder - The current node builder.
  15969. * @return {?BasicLightMapNode<vec3>} The light map node.
  15970. */
  15971. setupLightMap( builder ) {
  15972. let node = null;
  15973. if ( builder.material.lightMap ) {
  15974. node = new BasicLightMapNode( materialLightMap );
  15975. }
  15976. return node;
  15977. }
  15978. /**
  15979. * The material overwrites this method because `lights` is set to `true` but
  15980. * we still want to return the diffuse color as the outgoing light.
  15981. *
  15982. * @return {Node<vec3>} The outgoing light node.
  15983. */
  15984. setupOutgoingLight() {
  15985. return diffuseColor.rgb;
  15986. }
  15987. /**
  15988. * Setups the lighting model.
  15989. *
  15990. * @return {BasicLightingModel} The lighting model.
  15991. */
  15992. setupLightingModel() {
  15993. return new BasicLightingModel();
  15994. }
  15995. }
  15996. const F_Schlick = /*@__PURE__*/ Fn( ( { f0, f90, dotVH } ) => {
  15997. // Original approximation by Christophe Schlick '94
  15998. // float fresnel = pow( 1.0 - dotVH, 5.0 );
  15999. // Optimized variant (presented by Epic at SIGGRAPH '13)
  16000. // https://cdn2.unrealengine.com/Resources/files/2013SiggraphPresentationsNotes-26915738.pdf
  16001. const fresnel = dotVH.mul( -5.55473 ).sub( 6.98316 ).mul( dotVH ).exp2();
  16002. return f0.mul( fresnel.oneMinus() ).add( f90.mul( fresnel ) );
  16003. } ); // validated
  16004. const BRDF_Lambert = /*@__PURE__*/ Fn( ( inputs ) => {
  16005. return inputs.diffuseColor.mul( 1 / Math.PI ); // punctual light
  16006. } ); // validated
  16007. const G_BlinnPhong_Implicit = () => float( 0.25 );
  16008. const D_BlinnPhong = /*@__PURE__*/ Fn( ( { dotNH } ) => {
  16009. return shininess.mul( float( 0.5 ) ).add( 1.0 ).mul( float( 1 / Math.PI ) ).mul( dotNH.pow( shininess ) );
  16010. } );
  16011. const BRDF_BlinnPhong = /*@__PURE__*/ Fn( ( { lightDirection } ) => {
  16012. const halfDir = lightDirection.add( positionViewDirection ).normalize();
  16013. const dotNH = normalView.dot( halfDir ).clamp();
  16014. const dotVH = positionViewDirection.dot( halfDir ).clamp();
  16015. const F = F_Schlick( { f0: specularColor, f90: 1.0, dotVH } );
  16016. const G = G_BlinnPhong_Implicit();
  16017. const D = D_BlinnPhong( { dotNH } );
  16018. return F.mul( G ).mul( D );
  16019. } );
  16020. /**
  16021. * Represents the lighting model for a phong material. Used in {@link MeshPhongNodeMaterial}.
  16022. *
  16023. * @augments BasicLightingModel
  16024. */
  16025. class PhongLightingModel extends BasicLightingModel {
  16026. /**
  16027. * Constructs a new phong lighting model.
  16028. *
  16029. * @param {boolean} [specular=true] - Whether specular is supported or not.
  16030. */
  16031. constructor( specular = true ) {
  16032. super();
  16033. /**
  16034. * Whether specular is supported or not. Set this to `false` if you are
  16035. * looking for a Lambert-like material meaning a material for non-shiny
  16036. * surfaces, without specular highlights.
  16037. *
  16038. * @type {boolean}
  16039. * @default true
  16040. */
  16041. this.specular = specular;
  16042. }
  16043. /**
  16044. * Implements the direct lighting. The specular portion is optional an can be controlled
  16045. * with the {@link PhongLightingModel#specular} flag.
  16046. *
  16047. * @param {Object} lightData - The light data.
  16048. */
  16049. direct( { lightDirection, lightColor, reflectedLight } ) {
  16050. const dotNL = normalView.dot( lightDirection ).clamp();
  16051. const irradiance = dotNL.mul( lightColor );
  16052. reflectedLight.directDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor: diffuseColor.rgb } ) ) );
  16053. if ( this.specular === true ) {
  16054. reflectedLight.directSpecular.addAssign( irradiance.mul( BRDF_BlinnPhong( { lightDirection } ) ).mul( materialSpecularStrength ) );
  16055. }
  16056. }
  16057. /**
  16058. * Implements the indirect lighting.
  16059. *
  16060. * @param {NodeBuilder} builder - The current node builder.
  16061. */
  16062. indirect( builder ) {
  16063. const { ambientOcclusion, irradiance, reflectedLight } = builder.context;
  16064. reflectedLight.indirectDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor } ) ) );
  16065. reflectedLight.indirectDiffuse.mulAssign( ambientOcclusion );
  16066. }
  16067. }
  16068. const _defaultValues$8 = /*@__PURE__*/ new MeshLambertMaterial();
  16069. /**
  16070. * Node material version of {@link MeshLambertMaterial}.
  16071. *
  16072. * @augments NodeMaterial
  16073. */
  16074. class MeshLambertNodeMaterial extends NodeMaterial {
  16075. static get type() {
  16076. return 'MeshLambertNodeMaterial';
  16077. }
  16078. /**
  16079. * Constructs a new mesh lambert node material.
  16080. *
  16081. * @param {Object} [parameters] - The configuration parameter.
  16082. */
  16083. constructor( parameters ) {
  16084. super();
  16085. /**
  16086. * This flag can be used for type testing.
  16087. *
  16088. * @type {boolean}
  16089. * @readonly
  16090. * @default true
  16091. */
  16092. this.isMeshLambertNodeMaterial = true;
  16093. /**
  16094. * Set to `true` because lambert materials react on lights.
  16095. *
  16096. * @type {boolean}
  16097. * @default true
  16098. */
  16099. this.lights = true;
  16100. this.setDefaultValues( _defaultValues$8 );
  16101. this.setValues( parameters );
  16102. }
  16103. /**
  16104. * Overwritten since this type of material uses {@link BasicEnvironmentNode}
  16105. * to implement the default environment mapping.
  16106. *
  16107. * @param {NodeBuilder} builder - The current node builder.
  16108. * @return {?BasicEnvironmentNode<vec3>} The environment node.
  16109. */
  16110. setupEnvironment( builder ) {
  16111. const envNode = super.setupEnvironment( builder );
  16112. return envNode ? new BasicEnvironmentNode( envNode ) : null;
  16113. }
  16114. /**
  16115. * Setups the lighting model.
  16116. *
  16117. * @return {PhongLightingModel} The lighting model.
  16118. */
  16119. setupLightingModel( /*builder*/ ) {
  16120. return new PhongLightingModel( false ); // ( specular ) -> force lambert
  16121. }
  16122. }
  16123. const _defaultValues$7 = /*@__PURE__*/ new MeshPhongMaterial();
  16124. /**
  16125. * Node material version of {@link MeshPhongMaterial}.
  16126. *
  16127. * @augments NodeMaterial
  16128. */
  16129. class MeshPhongNodeMaterial extends NodeMaterial {
  16130. static get type() {
  16131. return 'MeshPhongNodeMaterial';
  16132. }
  16133. /**
  16134. * Constructs a new mesh lambert node material.
  16135. *
  16136. * @param {Object} [parameters] - The configuration parameter.
  16137. */
  16138. constructor( parameters ) {
  16139. super();
  16140. /**
  16141. * This flag can be used for type testing.
  16142. *
  16143. * @type {boolean}
  16144. * @readonly
  16145. * @default true
  16146. */
  16147. this.isMeshPhongNodeMaterial = true;
  16148. /**
  16149. * Set to `true` because phong materials react on lights.
  16150. *
  16151. * @type {boolean}
  16152. * @default true
  16153. */
  16154. this.lights = true;
  16155. /**
  16156. * The shininess of phong materials is by default inferred from the `shininess`
  16157. * property. This node property allows to overwrite the default
  16158. * and define the shininess with a node instead.
  16159. *
  16160. * If you don't want to overwrite the shininess but modify the existing
  16161. * value instead, use {@link materialShininess}.
  16162. *
  16163. * @type {?Node<float>}
  16164. * @default null
  16165. */
  16166. this.shininessNode = null;
  16167. /**
  16168. * The specular color of phong materials is by default inferred from the
  16169. * `specular` property. This node property allows to overwrite the default
  16170. * and define the specular color with a node instead.
  16171. *
  16172. * If you don't want to overwrite the specular color but modify the existing
  16173. * value instead, use {@link materialSpecular}.
  16174. *
  16175. * @type {?Node<vec3>}
  16176. * @default null
  16177. */
  16178. this.specularNode = null;
  16179. this.setDefaultValues( _defaultValues$7 );
  16180. this.setValues( parameters );
  16181. }
  16182. /**
  16183. * Overwritten since this type of material uses {@link BasicEnvironmentNode}
  16184. * to implement the default environment mapping.
  16185. *
  16186. * @param {NodeBuilder} builder - The current node builder.
  16187. * @return {?BasicEnvironmentNode<vec3>} The environment node.
  16188. */
  16189. setupEnvironment( builder ) {
  16190. const envNode = super.setupEnvironment( builder );
  16191. return envNode ? new BasicEnvironmentNode( envNode ) : null;
  16192. }
  16193. /**
  16194. * Setups the lighting model.
  16195. *
  16196. * @return {PhongLightingModel} The lighting model.
  16197. */
  16198. setupLightingModel( /*builder*/ ) {
  16199. return new PhongLightingModel();
  16200. }
  16201. /**
  16202. * Setups the phong specific node variables.
  16203. *
  16204. * @param {NodeBuilder} builder - The current node builder.
  16205. */
  16206. setupVariants( /*builder*/ ) {
  16207. // SHININESS
  16208. const shininessNode = ( this.shininessNode ? float( this.shininessNode ) : materialShininess ).max( 1e-4 ); // to prevent pow( 0.0, 0.0 )
  16209. shininess.assign( shininessNode );
  16210. // SPECULAR COLOR
  16211. const specularNode = this.specularNode || materialSpecular;
  16212. specularColor.assign( specularNode );
  16213. }
  16214. copy( source ) {
  16215. this.shininessNode = source.shininessNode;
  16216. this.specularNode = source.specularNode;
  16217. return super.copy( source );
  16218. }
  16219. }
  16220. const getGeometryRoughness = /*@__PURE__*/ Fn( ( builder ) => {
  16221. if ( builder.geometry.hasAttribute( 'normal' ) === false ) {
  16222. return float( 0 );
  16223. }
  16224. const dxy = normalViewGeometry.dFdx().abs().max( normalViewGeometry.dFdy().abs() );
  16225. const geometryRoughness = dxy.x.max( dxy.y ).max( dxy.z );
  16226. return geometryRoughness;
  16227. } );
  16228. const getRoughness = /*@__PURE__*/ Fn( ( inputs ) => {
  16229. const { roughness } = inputs;
  16230. const geometryRoughness = getGeometryRoughness();
  16231. let roughnessFactor = roughness.max( 0.0525 ); // 0.0525 corresponds to the base mip of a 256 cubemap.
  16232. roughnessFactor = roughnessFactor.add( geometryRoughness );
  16233. roughnessFactor = roughnessFactor.min( 1.0 );
  16234. return roughnessFactor;
  16235. } );
  16236. // Moving Frostbite to Physically Based Rendering 3.0 - page 12, listing 2
  16237. // https://seblagarde.files.wordpress.com/2015/07/course_notes_moving_frostbite_to_pbr_v32.pdf
  16238. const V_GGX_SmithCorrelated = /*@__PURE__*/ Fn( ( { alpha, dotNL, dotNV } ) => {
  16239. const a2 = alpha.pow2();
  16240. const gv = dotNL.mul( a2.add( a2.oneMinus().mul( dotNV.pow2() ) ).sqrt() );
  16241. const gl = dotNV.mul( a2.add( a2.oneMinus().mul( dotNL.pow2() ) ).sqrt() );
  16242. return div( 0.5, gv.add( gl ).max( EPSILON ) );
  16243. } ).setLayout( {
  16244. name: 'V_GGX_SmithCorrelated',
  16245. type: 'float',
  16246. inputs: [
  16247. { name: 'alpha', type: 'float' },
  16248. { name: 'dotNL', type: 'float' },
  16249. { name: 'dotNV', type: 'float' }
  16250. ]
  16251. } ); // validated
  16252. // https://google.github.io/filament/Filament.md.html#materialsystem/anisotropicmodel/anisotropicspecularbrdf
  16253. const V_GGX_SmithCorrelated_Anisotropic = /*@__PURE__*/ Fn( ( { alphaT, alphaB, dotTV, dotBV, dotTL, dotBL, dotNV, dotNL } ) => {
  16254. const gv = dotNL.mul( vec3( alphaT.mul( dotTV ), alphaB.mul( dotBV ), dotNV ).length() );
  16255. const gl = dotNV.mul( vec3( alphaT.mul( dotTL ), alphaB.mul( dotBL ), dotNL ).length() );
  16256. const v = div( 0.5, gv.add( gl ) );
  16257. return v.saturate();
  16258. } ).setLayout( {
  16259. name: 'V_GGX_SmithCorrelated_Anisotropic',
  16260. type: 'float',
  16261. inputs: [
  16262. { name: 'alphaT', type: 'float', qualifier: 'in' },
  16263. { name: 'alphaB', type: 'float', qualifier: 'in' },
  16264. { name: 'dotTV', type: 'float', qualifier: 'in' },
  16265. { name: 'dotBV', type: 'float', qualifier: 'in' },
  16266. { name: 'dotTL', type: 'float', qualifier: 'in' },
  16267. { name: 'dotBL', type: 'float', qualifier: 'in' },
  16268. { name: 'dotNV', type: 'float', qualifier: 'in' },
  16269. { name: 'dotNL', type: 'float', qualifier: 'in' }
  16270. ]
  16271. } );
  16272. // Microfacet Models for Refraction through Rough Surfaces - equation (33)
  16273. // http://graphicrants.blogspot.com/2013/08/specular-brdf-reference.html
  16274. // alpha is "roughness squared" in Disney’s reparameterization
  16275. const D_GGX = /*@__PURE__*/ Fn( ( { alpha, dotNH } ) => {
  16276. const a2 = alpha.pow2();
  16277. const denom = dotNH.pow2().mul( a2.oneMinus() ).oneMinus(); // avoid alpha = 0 with dotNH = 1
  16278. return a2.div( denom.pow2() ).mul( 1 / Math.PI );
  16279. } ).setLayout( {
  16280. name: 'D_GGX',
  16281. type: 'float',
  16282. inputs: [
  16283. { name: 'alpha', type: 'float' },
  16284. { name: 'dotNH', type: 'float' }
  16285. ]
  16286. } ); // validated
  16287. const RECIPROCAL_PI = /*@__PURE__*/ float( 1 / Math.PI );
  16288. // https://google.github.io/filament/Filament.md.html#materialsystem/anisotropicmodel/anisotropicspecularbrdf
  16289. const D_GGX_Anisotropic = /*@__PURE__*/ Fn( ( { alphaT, alphaB, dotNH, dotTH, dotBH } ) => {
  16290. const a2 = alphaT.mul( alphaB );
  16291. const v = vec3( alphaB.mul( dotTH ), alphaT.mul( dotBH ), a2.mul( dotNH ) );
  16292. const v2 = v.dot( v );
  16293. const w2 = a2.div( v2 );
  16294. return RECIPROCAL_PI.mul( a2.mul( w2.pow2() ) );
  16295. } ).setLayout( {
  16296. name: 'D_GGX_Anisotropic',
  16297. type: 'float',
  16298. inputs: [
  16299. { name: 'alphaT', type: 'float', qualifier: 'in' },
  16300. { name: 'alphaB', type: 'float', qualifier: 'in' },
  16301. { name: 'dotNH', type: 'float', qualifier: 'in' },
  16302. { name: 'dotTH', type: 'float', qualifier: 'in' },
  16303. { name: 'dotBH', type: 'float', qualifier: 'in' }
  16304. ]
  16305. } );
  16306. // GGX Distribution, Schlick Fresnel, GGX_SmithCorrelated Visibility
  16307. const BRDF_GGX = /*@__PURE__*/ Fn( ( { lightDirection, f0, f90, roughness, f, normalView: normalView$1 = normalView, USE_IRIDESCENCE, USE_ANISOTROPY } ) => {
  16308. const alpha = roughness.pow2(); // UE4's roughness
  16309. const halfDir = lightDirection.add( positionViewDirection ).normalize();
  16310. const dotNL = normalView$1.dot( lightDirection ).clamp();
  16311. const dotNV = normalView$1.dot( positionViewDirection ).clamp(); // @ TODO: Move to core dotNV
  16312. const dotNH = normalView$1.dot( halfDir ).clamp();
  16313. const dotVH = positionViewDirection.dot( halfDir ).clamp();
  16314. let F = F_Schlick( { f0, f90, dotVH } );
  16315. let V, D;
  16316. if ( defined( USE_IRIDESCENCE ) ) {
  16317. F = iridescence.mix( F, f );
  16318. }
  16319. if ( defined( USE_ANISOTROPY ) ) {
  16320. const dotTL = anisotropyT.dot( lightDirection );
  16321. const dotTV = anisotropyT.dot( positionViewDirection );
  16322. const dotTH = anisotropyT.dot( halfDir );
  16323. const dotBL = anisotropyB.dot( lightDirection );
  16324. const dotBV = anisotropyB.dot( positionViewDirection );
  16325. const dotBH = anisotropyB.dot( halfDir );
  16326. V = V_GGX_SmithCorrelated_Anisotropic( { alphaT, alphaB: alpha, dotTV, dotBV, dotTL, dotBL, dotNV, dotNL } );
  16327. D = D_GGX_Anisotropic( { alphaT, alphaB: alpha, dotNH, dotTH, dotBH } );
  16328. } else {
  16329. V = V_GGX_SmithCorrelated( { alpha, dotNL, dotNV } );
  16330. D = D_GGX( { alpha, dotNH } );
  16331. }
  16332. return F.mul( V ).mul( D );
  16333. } ); // validated
  16334. /**
  16335. * Precomputed DFG LUT for Image-Based Lighting
  16336. * Resolution: 32x32
  16337. * Samples: 4096 per texel
  16338. * Format: RG16F (2 half floats per texel: scale, bias)
  16339. */
  16340. const DATA = new Uint16Array( [
  16341. 0x2cd9, 0x3b64, 0x2d0e, 0x3b43, 0x2e20, 0x3aa7, 0x3061, 0x39fb, 0x325e, 0x397c, 0x3454, 0x3908, 0x357d, 0x3893, 0x3698, 0x381e, 0x379d, 0x375b, 0x3845, 0x3689, 0x38af, 0x35ca, 0x390d, 0x351e, 0x395f, 0x3484, 0x39a8, 0x33f9, 0x39e6, 0x330a, 0x3a1c, 0x3239, 0x3a4b, 0x3183, 0x3a73, 0x30e5, 0x3a95, 0x305b, 0x3ab1, 0x2fc6, 0x3ac9, 0x2ef7, 0x3ade, 0x2e43, 0x3aee, 0x2da7, 0x3afc, 0x2d1f, 0x3b07, 0x2ca9, 0x3b10, 0x2c42, 0x3b17, 0x2bd1, 0x3b1c, 0x2b34, 0x3b1f, 0x2aaa, 0x3b22, 0x2a31, 0x3b23, 0x29c7, 0x3b23, 0x2968,
  16342. 0x32d4, 0x3a4b, 0x32dc, 0x3a45, 0x3308, 0x3a26, 0x3378, 0x39d0, 0x3425, 0x394a, 0x34c9, 0x38be, 0x359c, 0x383e, 0x3688, 0x3796, 0x3778, 0x36c4, 0x382f, 0x3603, 0x3898, 0x3553, 0x38f7, 0x34b3, 0x394b, 0x3424, 0x3994, 0x334c, 0x39d3, 0x326c, 0x3a08, 0x31a9, 0x3a35, 0x30fe, 0x3a5a, 0x306a, 0x3a78, 0x2fd1, 0x3a90, 0x2ef1, 0x3aa2, 0x2e2e, 0x3ab0, 0x2d86, 0x3aba, 0x2cf3, 0x3ac1, 0x2c74, 0x3ac4, 0x2c05, 0x3ac4, 0x2b49, 0x3ac2, 0x2aa1, 0x3abd, 0x2a0c, 0x3ab7, 0x298b, 0x3aaf, 0x2918, 0x3aa6, 0x28b3, 0x3a9b, 0x285a,
  16343. 0x3559, 0x3954, 0x355a, 0x3951, 0x3566, 0x3944, 0x3582, 0x391e, 0x35b6, 0x38d3, 0x360a, 0x386a, 0x3684, 0x37ed, 0x3720, 0x370d, 0x37d3, 0x3641, 0x3847, 0x3588, 0x38a3, 0x34e2, 0x38fa, 0x344d, 0x3948, 0x3391, 0x398d, 0x32a6, 0x39c8, 0x31d6, 0x39fa, 0x3121, 0x3a22, 0x3082, 0x3a43, 0x2ff0, 0x3a5c, 0x2f01, 0x3a6f, 0x2e32, 0x3a7c, 0x2d7e, 0x3a84, 0x2ce2, 0x3a87, 0x2c5b, 0x3a87, 0x2bcc, 0x3a83, 0x2b00, 0x3a7b, 0x2a4e, 0x3a71, 0x29b3, 0x3a66, 0x292c, 0x3a58, 0x28b4, 0x3a4b, 0x284b, 0x3a3d, 0x27dc, 0x3a2e, 0x2739,
  16344. 0x3709, 0x387c, 0x370a, 0x387b, 0x3710, 0x3874, 0x3720, 0x385f, 0x373d, 0x3834, 0x376a, 0x37e1, 0x37ac, 0x3732, 0x3805, 0x3675, 0x383f, 0x35bc, 0x3883, 0x3511, 0x38cb, 0x3476, 0x3912, 0x33d8, 0x3955, 0x32e2, 0x3991, 0x3208, 0x39c6, 0x3149, 0x39f1, 0x30a1, 0x3a15, 0x300f, 0x3a30, 0x2f21, 0x3a44, 0x2e45, 0x3a51, 0x2d87, 0x3a59, 0x2ce2, 0x3a5b, 0x2c53, 0x3a58, 0x2bb0, 0x3a52, 0x2ada, 0x3a49, 0x2a1f, 0x3a40, 0x297d, 0x3a34, 0x28f0, 0x3a25, 0x2874, 0x3a13, 0x2807, 0x3a00, 0x274e, 0x39eb, 0x26a6, 0x39d5, 0x2611,
  16345. 0x3840, 0x3780, 0x3840, 0x377e, 0x3842, 0x3776, 0x3846, 0x375e, 0x384f, 0x372a, 0x385b, 0x36d3, 0x386c, 0x3659, 0x3885, 0x35c7, 0x38a8, 0x352d, 0x38d4, 0x3497, 0x3906, 0x340c, 0x393b, 0x331a, 0x3970, 0x323a, 0x39a0, 0x3172, 0x39cb, 0x30c3, 0x39ef, 0x302a, 0x3a0c, 0x2f4a, 0x3a21, 0x2e63, 0x3a2f, 0x2d9b, 0x3a37, 0x2ced, 0x3a39, 0x2c57, 0x3a37, 0x2baa, 0x3a34, 0x2ac9, 0x3a2c, 0x2a05, 0x3a20, 0x295d, 0x3a11, 0x28ca, 0x39ff, 0x2849, 0x39eb, 0x27b2, 0x39d5, 0x26ed, 0x39be, 0x2640, 0x39a5, 0x25aa, 0x398b, 0x2523,
  16346. 0x38e2, 0x363b, 0x38e2, 0x363b, 0x38e3, 0x3635, 0x38e6, 0x3626, 0x38ea, 0x3606, 0x38f0, 0x35cd, 0x38f8, 0x3579, 0x3903, 0x350e, 0x3915, 0x3495, 0x392d, 0x3418, 0x394c, 0x3340, 0x3970, 0x3261, 0x3995, 0x3197, 0x39b8, 0x30e4, 0x39d8, 0x3046, 0x39f3, 0x2f76, 0x3a08, 0x2e86, 0x3a16, 0x2db5, 0x3a1e, 0x2cff, 0x3a22, 0x2c61, 0x3a24, 0x2bb3, 0x3a20, 0x2ac7, 0x3a17, 0x29fc, 0x3a0a, 0x294c, 0x39fa, 0x28b2, 0x39e7, 0x282e, 0x39d1, 0x2773, 0x39b9, 0x26a9, 0x399f, 0x25fa, 0x3985, 0x255f, 0x3968, 0x24d6, 0x394a, 0x245d,
  16347. 0x396e, 0x3524, 0x396e, 0x3524, 0x396e, 0x3520, 0x396f, 0x3517, 0x3971, 0x3502, 0x3973, 0x34dd, 0x3975, 0x34a5, 0x3978, 0x3458, 0x397e, 0x33f9, 0x3987, 0x3332, 0x3997, 0x326b, 0x39aa, 0x31ac, 0x39c0, 0x30fb, 0x39d7, 0x305c, 0x39eb, 0x2f9e, 0x39fc, 0x2ea7, 0x3a07, 0x2dcf, 0x3a0f, 0x2d13, 0x3a16, 0x2c70, 0x3a17, 0x2bc4, 0x3a14, 0x2ad0, 0x3a0a, 0x29fc, 0x39fd, 0x2945, 0x39ed, 0x28a6, 0x39d9, 0x281d, 0x39c2, 0x274a, 0x39a9, 0x267c, 0x398e, 0x25c7, 0x3971, 0x2528, 0x3952, 0x249e, 0x3931, 0x2425, 0x3910, 0x2374,
  16348. 0x39e5, 0x3436, 0x39e5, 0x3435, 0x39e5, 0x3434, 0x39e5, 0x342e, 0x39e5, 0x3420, 0x39e5, 0x3408, 0x39e3, 0x33c4, 0x39e1, 0x3359, 0x39df, 0x32d3, 0x39de, 0x323a, 0x39e1, 0x319a, 0x39e7, 0x30fb, 0x39f0, 0x3065, 0x39f9, 0x2fb6, 0x3a02, 0x2ec0, 0x3a08, 0x2de6, 0x3a0d, 0x2d26, 0x3a12, 0x2c7e, 0x3a13, 0x2bda, 0x3a0e, 0x2adc, 0x3a05, 0x2a02, 0x39f8, 0x2945, 0x39e7, 0x28a1, 0x39d3, 0x2813, 0x39bc, 0x2730, 0x39a2, 0x265c, 0x3985, 0x25a3, 0x3966, 0x2501, 0x3945, 0x2475, 0x3923, 0x23f3, 0x3901, 0x231c, 0x38dd, 0x225e,
  16349. 0x3a4b, 0x32d6, 0x3a4a, 0x32d6, 0x3a4a, 0x32d4, 0x3a4a, 0x32cc, 0x3a48, 0x32bb, 0x3a47, 0x329d, 0x3a43, 0x326b, 0x3a3d, 0x3222, 0x3a36, 0x31c2, 0x3a2e, 0x314f, 0x3a28, 0x30d2, 0x3a23, 0x3052, 0x3a20, 0x2fab, 0x3a1e, 0x2ec2, 0x3a1b, 0x2def, 0x3a19, 0x2d31, 0x3a1a, 0x2c89, 0x3a18, 0x2beb, 0x3a11, 0x2aea, 0x3a07, 0x2a0a, 0x39fa, 0x2948, 0x39e9, 0x28a1, 0x39d4, 0x280f, 0x39bd, 0x2721, 0x39a2, 0x2647, 0x3985, 0x258b, 0x3964, 0x24e5, 0x3942, 0x2455, 0x391f, 0x23b3, 0x38fb, 0x22d8, 0x38d4, 0x2219, 0x38ad, 0x2172,
  16350. 0x3aa0, 0x3180, 0x3aa0, 0x3180, 0x3aa0, 0x317f, 0x3a9f, 0x317b, 0x3a9d, 0x3170, 0x3a99, 0x315d, 0x3a95, 0x313d, 0x3a8d, 0x310c, 0x3a82, 0x30ca, 0x3a76, 0x3077, 0x3a69, 0x3019, 0x3a5c, 0x2f68, 0x3a4f, 0x2e9e, 0x3a42, 0x2dde, 0x3a37, 0x2d2b, 0x3a30, 0x2c89, 0x3a29, 0x2bef, 0x3a1f, 0x2af0, 0x3a12, 0x2a0f, 0x3a03, 0x294a, 0x39f1, 0x28a0, 0x39dc, 0x280c, 0x39c5, 0x2717, 0x39a9, 0x2638, 0x398b, 0x2578, 0x396a, 0x24d0, 0x3947, 0x243f, 0x3923, 0x2380, 0x38fc, 0x22a4, 0x38d4, 0x21e4, 0x38ac, 0x213c, 0x3883, 0x20a8,
  16351. 0x3ae8, 0x3062, 0x3ae8, 0x3062, 0x3ae7, 0x3061, 0x3ae6, 0x305f, 0x3ae4, 0x305a, 0x3ae0, 0x304f, 0x3ada, 0x303b, 0x3ad1, 0x301b, 0x3ac5, 0x2fdd, 0x3ab6, 0x2f6a, 0x3aa4, 0x2ede, 0x3a91, 0x2e45, 0x3a7c, 0x2da5, 0x3a67, 0x2d0a, 0x3a57, 0x2c77, 0x3a48, 0x2bdc, 0x3a38, 0x2ae5, 0x3a27, 0x2a0a, 0x3a16, 0x2947, 0x3a02, 0x289d, 0x39eb, 0x2808, 0x39d3, 0x270d, 0x39b6, 0x262b, 0x3997, 0x256a, 0x3976, 0x24bf, 0x3952, 0x242b, 0x392d, 0x2358, 0x3904, 0x227a, 0x38db, 0x21b8, 0x38b2, 0x2110, 0x3887, 0x207d, 0x385b, 0x1ff6,
  16352. 0x3b23, 0x2ee8, 0x3b23, 0x2ee8, 0x3b22, 0x2ee8, 0x3b21, 0x2ee7, 0x3b1f, 0x2ee3, 0x3b1a, 0x2ed6, 0x3b14, 0x2ec1, 0x3b0b, 0x2e99, 0x3afe, 0x2e60, 0x3aee, 0x2e12, 0x3ad8, 0x2dad, 0x3ac1, 0x2d3d, 0x3aa5, 0x2cc3, 0x3a8b, 0x2c48, 0x3a76, 0x2ba2, 0x3a60, 0x2ac0, 0x3a49, 0x29f2, 0x3a32, 0x2938, 0x3a1b, 0x2893, 0x3a02, 0x27ff, 0x39e8, 0x26ff, 0x39ca, 0x261e, 0x39aa, 0x255b, 0x3988, 0x24b0, 0x3964, 0x241c, 0x393d, 0x2336, 0x3913, 0x2257, 0x38e9, 0x2195, 0x38be, 0x20eb, 0x3891, 0x2059, 0x3864, 0x1fae, 0x3837, 0x1ecd,
  16353. 0x3b54, 0x2d61, 0x3b54, 0x2d61, 0x3b53, 0x2d61, 0x3b52, 0x2d62, 0x3b4f, 0x2d61, 0x3b4b, 0x2d5c, 0x3b45, 0x2d51, 0x3b3b, 0x2d3d, 0x3b2e, 0x2d1a, 0x3b1d, 0x2ce7, 0x3b06, 0x2ca3, 0x3aeb, 0x2c52, 0x3acb, 0x2bee, 0x3ab0, 0x2b31, 0x3a94, 0x2a74, 0x3a77, 0x29bf, 0x3a5a, 0x2915, 0x3a3f, 0x287a, 0x3a22, 0x27de, 0x3a05, 0x26e4, 0x39e5, 0x2609, 0x39c3, 0x2547, 0x39a0, 0x249f, 0x397b, 0x240c, 0x3953, 0x2314, 0x3928, 0x2238, 0x38fd, 0x2175, 0x38d0, 0x20cb, 0x38a2, 0x2038, 0x3873, 0x1f71, 0x3844, 0x1e90, 0x3815, 0x1dce,
  16354. 0x3b7c, 0x2c22, 0x3b7c, 0x2c22, 0x3b7b, 0x2c23, 0x3b7a, 0x2c25, 0x3b77, 0x2c27, 0x3b73, 0x2c26, 0x3b6d, 0x2c23, 0x3b64, 0x2c1a, 0x3b57, 0x2c07, 0x3b46, 0x2bd1, 0x3b2e, 0x2b79, 0x3b0f, 0x2b07, 0x3aef, 0x2a86, 0x3ad1, 0x29f8, 0x3ab0, 0x2967, 0x3a8e, 0x28d7, 0x3a6d, 0x284e, 0x3a4c, 0x279f, 0x3a2b, 0x26b7, 0x3a08, 0x25e5, 0x39e4, 0x252c, 0x39be, 0x2488, 0x3998, 0x23f0, 0x396f, 0x22f2, 0x3943, 0x2215, 0x3917, 0x2155, 0x38e8, 0x20ae, 0x38b9, 0x201c, 0x3888, 0x1f38, 0x3857, 0x1e5a, 0x3826, 0x1d9a, 0x37eb, 0x1cf0,
  16355. 0x3b9c, 0x2a43, 0x3b9c, 0x2a43, 0x3b9b, 0x2a46, 0x3b9a, 0x2a4a, 0x3b98, 0x2a50, 0x3b93, 0x2a54, 0x3b8e, 0x2a59, 0x3b85, 0x2a56, 0x3b79, 0x2a45, 0x3b67, 0x2a24, 0x3b4f, 0x29ee, 0x3b2f, 0x29a4, 0x3b10, 0x294b, 0x3aef, 0x28e5, 0x3ac9, 0x2877, 0x3aa4, 0x2809, 0x3a7e, 0x2739, 0x3a59, 0x266d, 0x3a34, 0x25af, 0x3a0c, 0x2503, 0x39e4, 0x2468, 0x39bb, 0x23bb, 0x3990, 0x22c6, 0x3963, 0x21f0, 0x3936, 0x2133, 0x3906, 0x208f, 0x38d5, 0x1ffd, 0x38a3, 0x1f04, 0x3870, 0x1e28, 0x383d, 0x1d69, 0x380b, 0x1cc3, 0x37b0, 0x1c32,
  16356. 0x3bb5, 0x28aa, 0x3bb5, 0x28ab, 0x3bb5, 0x28ad, 0x3bb4, 0x28b2, 0x3bb2, 0x28b9, 0x3bae, 0x28c2, 0x3ba8, 0x28ca, 0x3ba0, 0x28d1, 0x3b94, 0x28cd, 0x3b83, 0x28c1, 0x3b6a, 0x28a3, 0x3b4b, 0x2876, 0x3b2d, 0x283d, 0x3b09, 0x27ea, 0x3ae1, 0x274b, 0x3ab9, 0x26a6, 0x3a8f, 0x25fe, 0x3a67, 0x255d, 0x3a3d, 0x24c5, 0x3a11, 0x2439, 0x39e6, 0x2371, 0x39b9, 0x228d, 0x398a, 0x21c1, 0x395a, 0x210b, 0x3929, 0x206c, 0x38f7, 0x1fc1, 0x38c3, 0x1ecb, 0x388f, 0x1df6, 0x385a, 0x1d3a, 0x3825, 0x1c99, 0x37e1, 0x1c08, 0x3779, 0x1b1b,
  16357. 0x3bc9, 0x26d3, 0x3bc9, 0x26d4, 0x3bc9, 0x26d9, 0x3bc8, 0x26e3, 0x3bc6, 0x26ef, 0x3bc2, 0x2705, 0x3bbd, 0x271a, 0x3bb6, 0x2731, 0x3baa, 0x273c, 0x3b9a, 0x273d, 0x3b81, 0x2726, 0x3b65, 0x26f7, 0x3b46, 0x26af, 0x3b20, 0x2650, 0x3af7, 0x25e1, 0x3acd, 0x256a, 0x3aa1, 0x24eb, 0x3a75, 0x246f, 0x3a46, 0x23ee, 0x3a17, 0x230d, 0x39e9, 0x223e, 0x39b7, 0x2183, 0x3985, 0x20d8, 0x3953, 0x2043, 0x391e, 0x1f7a, 0x38e9, 0x1e8d, 0x38b3, 0x1dbf, 0x387c, 0x1d0b, 0x3845, 0x1c6c, 0x380e, 0x1bc4, 0x37b0, 0x1ad2, 0x3745, 0x19fd,
  16358. 0x3bd9, 0x24e4, 0x3bd9, 0x24e5, 0x3bd9, 0x24e8, 0x3bd8, 0x24f2, 0x3bd5, 0x24fe, 0x3bd2, 0x2512, 0x3bce, 0x252b, 0x3bc6, 0x2544, 0x3bbc, 0x255a, 0x3bac, 0x256b, 0x3b93, 0x2569, 0x3b7a, 0x2557, 0x3b5b, 0x252f, 0x3b34, 0x24f7, 0x3b0c, 0x24ad, 0x3adf, 0x2458, 0x3ab1, 0x23f8, 0x3a82, 0x233f, 0x3a4f, 0x2286, 0x3a1e, 0x21d5, 0x39eb, 0x2130, 0x39b6, 0x2098, 0x3982, 0x200e, 0x394b, 0x1f25, 0x3914, 0x1e45, 0x38dc, 0x1d83, 0x38a3, 0x1cd6, 0x386b, 0x1c3d, 0x3831, 0x1b71, 0x37f2, 0x1a87, 0x3782, 0x19bc, 0x3714, 0x1909,
  16359. 0x3be5, 0x22d8, 0x3be5, 0x22d9, 0x3be4, 0x22df, 0x3be4, 0x22ef, 0x3be1, 0x2305, 0x3bde, 0x232a, 0x3bda, 0x2358, 0x3bd4, 0x2392, 0x3bcb, 0x23ca, 0x3bbb, 0x23f4, 0x3ba3, 0x2405, 0x3b8c, 0x2405, 0x3b6c, 0x23ec, 0x3b47, 0x23ae, 0x3b1d, 0x2353, 0x3af0, 0x22e2, 0x3ac0, 0x2261, 0x3a8e, 0x21d9, 0x3a5a, 0x214e, 0x3a26, 0x20c7, 0x39ee, 0x2045, 0x39b7, 0x1f97, 0x397f, 0x1eba, 0x3945, 0x1df0, 0x390b, 0x1d3a, 0x38d0, 0x1c9a, 0x3895, 0x1c0a, 0x385a, 0x1b18, 0x381f, 0x1a39, 0x37c9, 0x1975, 0x3756, 0x18cc, 0x36e6, 0x1836,
  16360. 0x3bed, 0x20a8, 0x3bed, 0x20a9, 0x3bed, 0x20ae, 0x3bed, 0x20bb, 0x3beb, 0x20cf, 0x3be8, 0x20ef, 0x3be4, 0x2119, 0x3bde, 0x214f, 0x3bd6, 0x2189, 0x3bc6, 0x21b8, 0x3bb1, 0x21de, 0x3b9a, 0x21f2, 0x3b7b, 0x21f2, 0x3b57, 0x21d8, 0x3b2d, 0x21a4, 0x3b00, 0x215f, 0x3acf, 0x2108, 0x3a99, 0x20a8, 0x3a64, 0x2043, 0x3a2c, 0x1fba, 0x39f2, 0x1ef3, 0x39b8, 0x1e36, 0x397c, 0x1d86, 0x3940, 0x1ce5, 0x3903, 0x1c52, 0x38c6, 0x1b9e, 0x3888, 0x1ab3, 0x384a, 0x19e4, 0x380e, 0x192b, 0x37a3, 0x188b, 0x372d, 0x17f7, 0x36ba, 0x1701,
  16361. 0x3bf4, 0x1e23, 0x3bf4, 0x1e25, 0x3bf4, 0x1e2d, 0x3bf3, 0x1e41, 0x3bf1, 0x1e64, 0x3bef, 0x1e9c, 0x3beb, 0x1ee1, 0x3be6, 0x1f40, 0x3bde, 0x1fa7, 0x3bce, 0x2001, 0x3bbd, 0x202f, 0x3ba6, 0x204e, 0x3b88, 0x205f, 0x3b64, 0x205b, 0x3b3b, 0x2044, 0x3b0e, 0x201f, 0x3adb, 0x1fcf, 0x3aa6, 0x1f4e, 0x3a6e, 0x1ec1, 0x3a33, 0x1e2b, 0x39f7, 0x1d95, 0x39ba, 0x1d06, 0x397b, 0x1c7d, 0x393c, 0x1bfc, 0x38fc, 0x1b13, 0x38bc, 0x1a40, 0x387c, 0x1983, 0x383c, 0x18da, 0x37fa, 0x1842, 0x377f, 0x177f, 0x3706, 0x1695, 0x3691, 0x15c8,
  16362. 0x3bf8, 0x1bca, 0x3bf8, 0x1bcc, 0x3bf8, 0x1bd8, 0x3bf8, 0x1bf7, 0x3bf6, 0x1c1b, 0x3bf4, 0x1c45, 0x3bf1, 0x1c83, 0x3bec, 0x1cce, 0x3be4, 0x1d21, 0x3bd5, 0x1d78, 0x3bc5, 0x1dd1, 0x3bb0, 0x1e17, 0x3b93, 0x1e4a, 0x3b70, 0x1e5f, 0x3b48, 0x1e57, 0x3b1b, 0x1e35, 0x3ae7, 0x1df6, 0x3ab2, 0x1da4, 0x3a77, 0x1d44, 0x3a3a, 0x1cdb, 0x39fc, 0x1c6e, 0x39bb, 0x1c03, 0x397a, 0x1b35, 0x3938, 0x1a72, 0x38f5, 0x19bb, 0x38b3, 0x1914, 0x3870, 0x187d, 0x382e, 0x17eb, 0x37db, 0x16f9, 0x375c, 0x1621, 0x36e1, 0x1565, 0x3669, 0x14be,
  16363. 0x3bfb, 0x18b9, 0x3bfb, 0x18ba, 0x3bfb, 0x18c3, 0x3bfb, 0x18da, 0x3bf9, 0x190a, 0x3bf7, 0x1948, 0x3bf5, 0x19ac, 0x3bf0, 0x1a20, 0x3be9, 0x1ab3, 0x3bdb, 0x1b49, 0x3bcd, 0x1be6, 0x3bb7, 0x1c34, 0x3b9c, 0x1c6d, 0x3b7a, 0x1c8e, 0x3b54, 0x1c9e, 0x3b26, 0x1c96, 0x3af2, 0x1c75, 0x3abc, 0x1c47, 0x3a80, 0x1c09, 0x3a42, 0x1b85, 0x3a01, 0x1aec, 0x39be, 0x1a50, 0x397a, 0x19b5, 0x3935, 0x1921, 0x38f0, 0x1895, 0x38aa, 0x1814, 0x3866, 0x173a, 0x3821, 0x1665, 0x37be, 0x15a4, 0x373c, 0x14f9, 0x36be, 0x1460, 0x3644, 0x13b3,
  16364. 0x3bfd, 0x156b, 0x3bfd, 0x156c, 0x3bfd, 0x1578, 0x3bfd, 0x1598, 0x3bfc, 0x15dd, 0x3bfa, 0x163c, 0x3bf7, 0x16cb, 0x3bf3, 0x177b, 0x3beb, 0x1833, 0x3be0, 0x18ad, 0x3bd2, 0x192e, 0x3bbd, 0x19a6, 0x3ba4, 0x1a0c, 0x3b83, 0x1a5a, 0x3b5d, 0x1a8c, 0x3b30, 0x1a9b, 0x3afd, 0x1a86, 0x3ac6, 0x1a5c, 0x3a89, 0x1a11, 0x3a49, 0x19b7, 0x3a06, 0x194f, 0x39c1, 0x18e3, 0x397a, 0x1873, 0x3933, 0x1805, 0x38eb, 0x173a, 0x38a3, 0x1676, 0x385c, 0x15bf, 0x3816, 0x1519, 0x37a2, 0x1482, 0x371d, 0x13f7, 0x369c, 0x1306, 0x3620, 0x1231,
  16365. 0x3bff, 0x11cb, 0x3bff, 0x11cd, 0x3bfe, 0x11dd, 0x3bfe, 0x1219, 0x3bfd, 0x126b, 0x3bfb, 0x12e9, 0x3bf9, 0x13c5, 0x3bf5, 0x1460, 0x3bee, 0x150f, 0x3be3, 0x15c9, 0x3bd6, 0x168a, 0x3bc3, 0x174f, 0x3baa, 0x1806, 0x3b8b, 0x184f, 0x3b66, 0x1888, 0x3b39, 0x18a6, 0x3b07, 0x18ad, 0x3acf, 0x189c, 0x3a92, 0x1876, 0x3a50, 0x1840, 0x3a0c, 0x17fd, 0x39c4, 0x176a, 0x397b, 0x16ce, 0x3931, 0x1634, 0x38e6, 0x1599, 0x389c, 0x1508, 0x3852, 0x147f, 0x380a, 0x1401, 0x3788, 0x131c, 0x36ff, 0x124a, 0x367c, 0x1190, 0x35fe, 0x10ea,
  16366. 0x3bff, 0x0daa, 0x3bff, 0x0dad, 0x3bff, 0x0dc0, 0x3bff, 0x0e0e, 0x3bfe, 0x0e87, 0x3bfc, 0x0f14, 0x3bfb, 0x1029, 0x3bf7, 0x10d1, 0x3bf0, 0x11d3, 0x3be6, 0x12c9, 0x3bd9, 0x13fc, 0x3bc7, 0x1499, 0x3bb0, 0x152a, 0x3b92, 0x15ab, 0x3b6e, 0x1615, 0x3b42, 0x165a, 0x3b10, 0x1681, 0x3ad8, 0x1683, 0x3a9a, 0x1665, 0x3a57, 0x1629, 0x3a11, 0x15dd, 0x39c8, 0x1580, 0x397c, 0x1518, 0x3930, 0x14ae, 0x38e3, 0x1441, 0x3896, 0x13b1, 0x384a, 0x12e9, 0x37ff, 0x122f, 0x376f, 0x1182, 0x36e3, 0x10e5, 0x365e, 0x1057, 0x35de, 0x0fac,
  16367. 0x3c00, 0x08ea, 0x3c00, 0x08ed, 0x3c00, 0x0902, 0x3c00, 0x0961, 0x3bff, 0x09f3, 0x3bfd, 0x0abc, 0x3bfb, 0x0c1f, 0x3bf8, 0x0d15, 0x3bf1, 0x0e5b, 0x3be8, 0x0fb4, 0x3bdc, 0x10b0, 0x3bcb, 0x1190, 0x3bb5, 0x126c, 0x3b97, 0x132c, 0x3b74, 0x13de, 0x3b4a, 0x1432, 0x3b18, 0x145e, 0x3ae0, 0x1472, 0x3aa2, 0x146f, 0x3a5f, 0x1456, 0x3a17, 0x142e, 0x39cc, 0x13ee, 0x397e, 0x136b, 0x392f, 0x12e1, 0x38df, 0x124f, 0x3890, 0x11bd, 0x3842, 0x1131, 0x37eb, 0x10ac, 0x3757, 0x102e, 0x36c9, 0x0f76, 0x3640, 0x0ea3, 0x35bf, 0x0de4,
  16368. 0x3c00, 0x039b, 0x3c00, 0x039d, 0x3c00, 0x03b2, 0x3c00, 0x041c, 0x3bff, 0x04be, 0x3bfd, 0x05d6, 0x3bfc, 0x0764, 0x3bf8, 0x08e2, 0x3bf2, 0x0a67, 0x3bea, 0x0c1b, 0x3bde, 0x0d41, 0x3bcd, 0x0e5f, 0x3bb8, 0x0f8c, 0x3b9c, 0x1057, 0x3b7a, 0x10e5, 0x3b51, 0x1155, 0x3b20, 0x11a5, 0x3ae8, 0x11da, 0x3aaa, 0x11ef, 0x3a66, 0x11e5, 0x3a1d, 0x11c1, 0x39d0, 0x1185, 0x3980, 0x113b, 0x392e, 0x10e5, 0x38dc, 0x1087, 0x388b, 0x1028, 0x383b, 0x0f94, 0x37d9, 0x0edb, 0x3741, 0x0e2c, 0x36af, 0x0d89, 0x3625, 0x0cf2, 0x35a1, 0x0c69,
  16369. 0x3c00, 0x0107, 0x3c00, 0x0108, 0x3c00, 0x0110, 0x3c00, 0x0145, 0x3bff, 0x0197, 0x3bfe, 0x0224, 0x3bfc, 0x030c, 0x3bf8, 0x0478, 0x3bf3, 0x062c, 0x3beb, 0x0833, 0x3be0, 0x0979, 0x3bd0, 0x0aeb, 0x3bbc, 0x0c3d, 0x3ba0, 0x0d01, 0x3b80, 0x0dbd, 0x3b57, 0x0e69, 0x3b27, 0x0eeb, 0x3af0, 0x0f53, 0x3ab1, 0x0f8a, 0x3a6c, 0x0f9f, 0x3a22, 0x0f8b, 0x39d4, 0x0f5b, 0x3982, 0x0f0f, 0x392f, 0x0eac, 0x38da, 0x0e3d, 0x3886, 0x0dc9, 0x3834, 0x0d51, 0x37c7, 0x0cd9, 0x372c, 0x0c65, 0x3697, 0x0bef, 0x360a, 0x0b20, 0x3585, 0x0a62,
  16370. 0x3c00, 0x0031, 0x3c00, 0x0031, 0x3c00, 0x0034, 0x3c00, 0x004b, 0x3bff, 0x006f, 0x3bfe, 0x00c9, 0x3bfc, 0x011b, 0x3bf9, 0x0207, 0x3bf4, 0x02d6, 0x3bec, 0x0415, 0x3be1, 0x0587, 0x3bd2, 0x0703, 0x3bbf, 0x087d, 0x3ba5, 0x096a, 0x3b85, 0x0a59, 0x3b5d, 0x0b32, 0x3b2e, 0x0bee, 0x3af7, 0x0c44, 0x3ab8, 0x0c7c, 0x3a73, 0x0c9c, 0x3a28, 0x0ca4, 0x39d8, 0x0c98, 0x3985, 0x0c77, 0x392f, 0x0c4a, 0x38d9, 0x0c10, 0x3882, 0x0ba0, 0x382e, 0x0b14, 0x37b6, 0x0a84, 0x3717, 0x09f5, 0x3680, 0x0969, 0x35f0, 0x08e6, 0x356a, 0x086a,
  16371. 0x3c00, 0x0004, 0x3c00, 0x0004, 0x3c00, 0x0004, 0x3c00, 0x000d, 0x3bff, 0x0021, 0x3bfe, 0x003b, 0x3bfd, 0x0070, 0x3bf9, 0x00c7, 0x3bf4, 0x012e, 0x3bed, 0x01c8, 0x3be3, 0x0274, 0x3bd4, 0x033b, 0x3bc1, 0x043a, 0x3ba8, 0x0534, 0x3b89, 0x0641, 0x3b62, 0x073b, 0x3b34, 0x0815, 0x3afd, 0x087c, 0x3abf, 0x08d0, 0x3a7a, 0x090a, 0x3a2e, 0x092c, 0x39dd, 0x0936, 0x3988, 0x0928, 0x3930, 0x0907, 0x38d7, 0x08d7, 0x387f, 0x089b, 0x3828, 0x0855, 0x37a7, 0x080b, 0x3704, 0x077b, 0x366a, 0x06e1, 0x35d8, 0x0649, 0x3550, 0x05b8,
  16372. 0x3c00, 0x0000, 0x3c00, 0x0000, 0x3c00, 0x0000, 0x3c00, 0x0003, 0x3bff, 0x0012, 0x3bfe, 0x001a, 0x3bfd, 0x0035, 0x3bfa, 0x0050, 0x3bf4, 0x0061, 0x3bed, 0x00a5, 0x3be4, 0x00ee, 0x3bd6, 0x0146, 0x3bc3, 0x01ab, 0x3bab, 0x0211, 0x3b8d, 0x028e, 0x3b67, 0x0303, 0x3b39, 0x0375, 0x3b04, 0x03e2, 0x3ac6, 0x0441, 0x3a80, 0x0492, 0x3a34, 0x04cd, 0x39e1, 0x04f2, 0x398b, 0x0504, 0x3931, 0x0502, 0x38d6, 0x04ec, 0x387c, 0x04c7, 0x3822, 0x0496, 0x3798, 0x045c, 0x36f2, 0x041a, 0x3655, 0x03d5, 0x35c1, 0x038e, 0x3537, 0x0347
  16373. ] );
  16374. let lut = null;
  16375. const DFGApprox = /*@__PURE__*/ Fn( ( { roughness, dotNV } ) => {
  16376. if ( lut === null ) {
  16377. lut = new DataTexture( DATA, 32, 32, RGFormat, HalfFloatType );
  16378. lut.minFilter = LinearFilter;
  16379. lut.magFilter = LinearFilter;
  16380. lut.wrapS = ClampToEdgeWrapping;
  16381. lut.wrapT = ClampToEdgeWrapping;
  16382. lut.generateMipmaps = false;
  16383. lut.needsUpdate = true;
  16384. }
  16385. const uv = vec2( roughness, dotNV );
  16386. return texture( lut, uv ).rg;
  16387. } );
  16388. // GGX BRDF with multi-scattering energy compensation for direct lighting
  16389. // This provides more accurate energy conservation, especially for rough materials
  16390. // Based on "Practical Multiple Scattering Compensation for Microfacet Models"
  16391. // https://blog.selfshadow.com/publications/turquin/ms_comp_final.pdf
  16392. const BRDF_GGX_Multiscatter = /*@__PURE__*/ Fn( ( { lightDirection, f0, f90, roughness: _roughness, f, USE_IRIDESCENCE, USE_ANISOTROPY } ) => {
  16393. // Single-scattering BRDF (standard GGX)
  16394. const singleScatter = BRDF_GGX( { lightDirection, f0, f90, roughness: _roughness, f, USE_IRIDESCENCE, USE_ANISOTROPY } );
  16395. // Multi-scattering compensation
  16396. const dotNL = normalView.dot( lightDirection ).clamp();
  16397. const dotNV = normalView.dot( positionViewDirection ).clamp();
  16398. // Precomputed DFG values for view and light directions
  16399. const dfgV = DFGApprox( { roughness: _roughness, dotNV } );
  16400. const dfgL = DFGApprox( { roughness: _roughness, dotNV: dotNL } );
  16401. // Single-scattering energy for view and light
  16402. const FssEss_V = f0.mul( dfgV.x ).add( f90.mul( dfgV.y ) );
  16403. const FssEss_L = f0.mul( dfgL.x ).add( f90.mul( dfgL.y ) );
  16404. const Ess_V = dfgV.x.add( dfgV.y );
  16405. const Ess_L = dfgL.x.add( dfgL.y );
  16406. // Energy lost to multiple scattering
  16407. const Ems_V = float( 1.0 ).sub( Ess_V );
  16408. const Ems_L = float( 1.0 ).sub( Ess_L );
  16409. // Average Fresnel reflectance
  16410. const Favg = f0.add( f0.oneMinus().mul( 0.047619 ) ); // 1/21
  16411. // Multiple scattering contribution
  16412. // Uses geometric mean of view and light contributions for better energy distribution
  16413. const Fms = FssEss_V.mul( FssEss_L ).mul( Favg ).div( float( 1.0 ).sub( Ems_V.mul( Ems_L ).mul( Favg ).mul( Favg ) ).add( EPSILON ) );
  16414. // Energy compensation factor
  16415. const compensationFactor = Ems_V.mul( Ems_L );
  16416. const multiScatter = Fms.mul( compensationFactor );
  16417. return singleScatter.add( multiScatter );
  16418. } );
  16419. const EnvironmentBRDF = /*@__PURE__*/ Fn( ( inputs ) => {
  16420. const { dotNV, specularColor, specularF90, roughness } = inputs;
  16421. const fab = DFGApprox( { dotNV, roughness } );
  16422. return specularColor.mul( fab.x ).add( specularF90.mul( fab.y ) );
  16423. } );
  16424. const Schlick_to_F0 = /*@__PURE__*/ Fn( ( { f, f90, dotVH } ) => {
  16425. const x = dotVH.oneMinus().saturate();
  16426. const x2 = x.mul( x );
  16427. const x5 = x.mul( x2, x2 ).clamp( 0, .9999 );
  16428. return f.sub( vec3( f90 ).mul( x5 ) ).div( x5.oneMinus() );
  16429. } ).setLayout( {
  16430. name: 'Schlick_to_F0',
  16431. type: 'vec3',
  16432. inputs: [
  16433. { name: 'f', type: 'vec3' },
  16434. { name: 'f90', type: 'float' },
  16435. { name: 'dotVH', type: 'float' }
  16436. ]
  16437. } );
  16438. // https://github.com/google/filament/blob/master/shaders/src/brdf.fs
  16439. const D_Charlie = /*@__PURE__*/ Fn( ( { roughness, dotNH } ) => {
  16440. const alpha = roughness.pow2();
  16441. // Estevez and Kulla 2017, "Production Friendly Microfacet Sheen BRDF"
  16442. const invAlpha = float( 1.0 ).div( alpha );
  16443. const cos2h = dotNH.pow2();
  16444. const sin2h = cos2h.oneMinus().max( 0.0078125 ); // 2^(-14/2), so sin2h^2 > 0 in fp16
  16445. return float( 2.0 ).add( invAlpha ).mul( sin2h.pow( invAlpha.mul( 0.5 ) ) ).div( 2.0 * Math.PI );
  16446. } ).setLayout( {
  16447. name: 'D_Charlie',
  16448. type: 'float',
  16449. inputs: [
  16450. { name: 'roughness', type: 'float' },
  16451. { name: 'dotNH', type: 'float' }
  16452. ]
  16453. } );
  16454. // https://github.com/google/filament/blob/master/shaders/src/brdf.fs
  16455. const V_Neubelt = /*@__PURE__*/ Fn( ( { dotNV, dotNL } ) => {
  16456. // Neubelt and Pettineo 2013, "Crafting a Next-gen Material Pipeline for The Order: 1886"
  16457. return float( 1.0 ).div( float( 4.0 ).mul( dotNL.add( dotNV ).sub( dotNL.mul( dotNV ) ) ) );
  16458. } ).setLayout( {
  16459. name: 'V_Neubelt',
  16460. type: 'float',
  16461. inputs: [
  16462. { name: 'dotNV', type: 'float' },
  16463. { name: 'dotNL', type: 'float' }
  16464. ]
  16465. } );
  16466. const BRDF_Sheen = /*@__PURE__*/ Fn( ( { lightDirection } ) => {
  16467. const halfDir = lightDirection.add( positionViewDirection ).normalize();
  16468. const dotNL = normalView.dot( lightDirection ).clamp();
  16469. const dotNV = normalView.dot( positionViewDirection ).clamp();
  16470. const dotNH = normalView.dot( halfDir ).clamp();
  16471. const D = D_Charlie( { roughness: sheenRoughness, dotNH } );
  16472. const V = V_Neubelt( { dotNV, dotNL } );
  16473. return sheen.mul( D ).mul( V );
  16474. } );
  16475. // Rect Area Light
  16476. // Real-Time Polygonal-Light Shading with Linearly Transformed Cosines
  16477. // by Eric Heitz, Jonathan Dupuy, Stephen Hill and David Neubelt
  16478. // code: https://github.com/selfshadow/ltc_code/
  16479. const LTC_Uv = /*@__PURE__*/ Fn( ( { N, V, roughness } ) => {
  16480. const LUT_SIZE = 64.0;
  16481. const LUT_SCALE = ( LUT_SIZE - 1.0 ) / LUT_SIZE;
  16482. const LUT_BIAS = 0.5 / LUT_SIZE;
  16483. const dotNV = N.dot( V ).saturate();
  16484. // texture parameterized by sqrt( GGX alpha ) and sqrt( 1 - cos( theta ) )
  16485. const uv = vec2( roughness, dotNV.oneMinus().sqrt() );
  16486. uv.assign( uv.mul( LUT_SCALE ).add( LUT_BIAS ) );
  16487. return uv;
  16488. } ).setLayout( {
  16489. name: 'LTC_Uv',
  16490. type: 'vec2',
  16491. inputs: [
  16492. { name: 'N', type: 'vec3' },
  16493. { name: 'V', type: 'vec3' },
  16494. { name: 'roughness', type: 'float' }
  16495. ]
  16496. } );
  16497. const LTC_ClippedSphereFormFactor = /*@__PURE__*/ Fn( ( { f } ) => {
  16498. // Real-Time Area Lighting: a Journey from Research to Production (p.102)
  16499. // An approximation of the form factor of a horizon-clipped rectangle.
  16500. const l = f.length();
  16501. return max$1( l.mul( l ).add( f.z ).div( l.add( 1.0 ) ), 0 );
  16502. } ).setLayout( {
  16503. name: 'LTC_ClippedSphereFormFactor',
  16504. type: 'float',
  16505. inputs: [
  16506. { name: 'f', type: 'vec3' }
  16507. ]
  16508. } );
  16509. const LTC_EdgeVectorFormFactor = /*@__PURE__*/ Fn( ( { v1, v2 } ) => {
  16510. const x = v1.dot( v2 );
  16511. const y = x.abs().toVar();
  16512. // rational polynomial approximation to theta / sin( theta ) / 2PI
  16513. const a = y.mul( 0.0145206 ).add( 0.4965155 ).mul( y ).add( 0.8543985 ).toVar();
  16514. const b = y.add( 4.1616724 ).mul( y ).add( 3.4175940 ).toVar();
  16515. const v = a.div( b );
  16516. const theta_sintheta = x.greaterThan( 0.0 ).select( v, max$1( x.mul( x ).oneMinus(), 1e-7 ).inverseSqrt().mul( 0.5 ).sub( v ) );
  16517. return v1.cross( v2 ).mul( theta_sintheta );
  16518. } ).setLayout( {
  16519. name: 'LTC_EdgeVectorFormFactor',
  16520. type: 'vec3',
  16521. inputs: [
  16522. { name: 'v1', type: 'vec3' },
  16523. { name: 'v2', type: 'vec3' }
  16524. ]
  16525. } );
  16526. const LTC_Evaluate = /*@__PURE__*/ Fn( ( { N, V, P, mInv, p0, p1, p2, p3 } ) => {
  16527. // bail if point is on back side of plane of light
  16528. // assumes ccw winding order of light vertices
  16529. const v1 = p1.sub( p0 ).toVar();
  16530. const v2 = p3.sub( p0 ).toVar();
  16531. const lightNormal = v1.cross( v2 );
  16532. const result = vec3().toVar();
  16533. If( lightNormal.dot( P.sub( p0 ) ).greaterThanEqual( 0.0 ), () => {
  16534. // construct orthonormal basis around N
  16535. const T1 = V.sub( N.mul( V.dot( N ) ) ).normalize();
  16536. const T2 = N.cross( T1 ).negate(); // negated from paper; possibly due to a different handedness of world coordinate system
  16537. // compute transform
  16538. const mat = mInv.mul( mat3( T1, T2, N ).transpose() ).toVar();
  16539. // transform rect
  16540. // & project rect onto sphere
  16541. const coords0 = mat.mul( p0.sub( P ) ).normalize().toVar();
  16542. const coords1 = mat.mul( p1.sub( P ) ).normalize().toVar();
  16543. const coords2 = mat.mul( p2.sub( P ) ).normalize().toVar();
  16544. const coords3 = mat.mul( p3.sub( P ) ).normalize().toVar();
  16545. // calculate vector form factor
  16546. const vectorFormFactor = vec3( 0 ).toVar();
  16547. vectorFormFactor.addAssign( LTC_EdgeVectorFormFactor( { v1: coords0, v2: coords1 } ) );
  16548. vectorFormFactor.addAssign( LTC_EdgeVectorFormFactor( { v1: coords1, v2: coords2 } ) );
  16549. vectorFormFactor.addAssign( LTC_EdgeVectorFormFactor( { v1: coords2, v2: coords3 } ) );
  16550. vectorFormFactor.addAssign( LTC_EdgeVectorFormFactor( { v1: coords3, v2: coords0 } ) );
  16551. // adjust for horizon clipping
  16552. result.assign( vec3( LTC_ClippedSphereFormFactor( { f: vectorFormFactor } ) ) );
  16553. } );
  16554. return result;
  16555. } ).setLayout( {
  16556. name: 'LTC_Evaluate',
  16557. type: 'vec3',
  16558. inputs: [
  16559. { name: 'N', type: 'vec3' },
  16560. { name: 'V', type: 'vec3' },
  16561. { name: 'P', type: 'vec3' },
  16562. { name: 'mInv', type: 'mat3' },
  16563. { name: 'p0', type: 'vec3' },
  16564. { name: 'p1', type: 'vec3' },
  16565. { name: 'p2', type: 'vec3' },
  16566. { name: 'p3', type: 'vec3' }
  16567. ]
  16568. } );
  16569. const LTC_Evaluate_Volume = /*@__PURE__*/ Fn( ( { P, p0, p1, p2, p3 } ) => {
  16570. // bail if point is on back side of plane of light
  16571. // assumes ccw winding order of light vertices
  16572. const v1 = p1.sub( p0 ).toVar();
  16573. const v2 = p3.sub( p0 ).toVar();
  16574. const lightNormal = v1.cross( v2 );
  16575. const result = vec3().toVar();
  16576. If( lightNormal.dot( P.sub( p0 ) ).greaterThanEqual( 0.0 ), () => {
  16577. // transform rect
  16578. // & project rect onto sphere
  16579. const coords0 = p0.sub( P ).normalize().toVar();
  16580. const coords1 = p1.sub( P ).normalize().toVar();
  16581. const coords2 = p2.sub( P ).normalize().toVar();
  16582. const coords3 = p3.sub( P ).normalize().toVar();
  16583. // calculate vector form factor
  16584. const vectorFormFactor = vec3( 0 ).toVar();
  16585. vectorFormFactor.addAssign( LTC_EdgeVectorFormFactor( { v1: coords0, v2: coords1 } ) );
  16586. vectorFormFactor.addAssign( LTC_EdgeVectorFormFactor( { v1: coords1, v2: coords2 } ) );
  16587. vectorFormFactor.addAssign( LTC_EdgeVectorFormFactor( { v1: coords2, v2: coords3 } ) );
  16588. vectorFormFactor.addAssign( LTC_EdgeVectorFormFactor( { v1: coords3, v2: coords0 } ) );
  16589. // adjust for horizon clipping
  16590. result.assign( vec3( LTC_ClippedSphereFormFactor( { f: vectorFormFactor.abs() } ) ) );
  16591. } );
  16592. return result;
  16593. } ).setLayout( {
  16594. name: 'LTC_Evaluate',
  16595. type: 'vec3',
  16596. inputs: [
  16597. { name: 'P', type: 'vec3' },
  16598. { name: 'p0', type: 'vec3' },
  16599. { name: 'p1', type: 'vec3' },
  16600. { name: 'p2', type: 'vec3' },
  16601. { name: 'p3', type: 'vec3' }
  16602. ]
  16603. } );
  16604. // Mipped Bicubic Texture Filtering by N8
  16605. // https://www.shadertoy.com/view/Dl2SDW
  16606. const bC = 1.0 / 6.0;
  16607. const w0 = ( a ) => mul( bC, mul( a, mul( a, a.negate().add( 3.0 ) ).sub( 3.0 ) ).add( 1.0 ) );
  16608. const w1 = ( a ) => mul( bC, mul( a, mul( a, mul( 3.0, a ).sub( 6.0 ) ) ).add( 4.0 ) );
  16609. const w2 = ( a ) => mul( bC, mul( a, mul( a, mul( -3, a ).add( 3.0 ) ).add( 3.0 ) ).add( 1.0 ) );
  16610. const w3 = ( a ) => mul( bC, pow( a, 3 ) );
  16611. const g0 = ( a ) => w0( a ).add( w1( a ) );
  16612. const g1 = ( a ) => w2( a ).add( w3( a ) );
  16613. // h0 and h1 are the two offset functions
  16614. const h0 = ( a ) => add( -1, w1( a ).div( w0( a ).add( w1( a ) ) ) );
  16615. const h1 = ( a ) => add( 1.0, w3( a ).div( w2( a ).add( w3( a ) ) ) );
  16616. const bicubic = ( textureNode, texelSize, lod ) => {
  16617. const uv = textureNode.uvNode;
  16618. const uvScaled = mul( uv, texelSize.zw ).add( 0.5 );
  16619. const iuv = floor( uvScaled );
  16620. const fuv = fract( uvScaled );
  16621. const g0x = g0( fuv.x );
  16622. const g1x = g1( fuv.x );
  16623. const h0x = h0( fuv.x );
  16624. const h1x = h1( fuv.x );
  16625. const h0y = h0( fuv.y );
  16626. const h1y = h1( fuv.y );
  16627. const p0 = vec2( iuv.x.add( h0x ), iuv.y.add( h0y ) ).sub( 0.5 ).mul( texelSize.xy );
  16628. const p1 = vec2( iuv.x.add( h1x ), iuv.y.add( h0y ) ).sub( 0.5 ).mul( texelSize.xy );
  16629. const p2 = vec2( iuv.x.add( h0x ), iuv.y.add( h1y ) ).sub( 0.5 ).mul( texelSize.xy );
  16630. const p3 = vec2( iuv.x.add( h1x ), iuv.y.add( h1y ) ).sub( 0.5 ).mul( texelSize.xy );
  16631. const a = g0( fuv.y ).mul( add( g0x.mul( textureNode.sample( p0 ).level( lod ) ), g1x.mul( textureNode.sample( p1 ).level( lod ) ) ) );
  16632. const b = g1( fuv.y ).mul( add( g0x.mul( textureNode.sample( p2 ).level( lod ) ), g1x.mul( textureNode.sample( p3 ).level( lod ) ) ) );
  16633. return a.add( b );
  16634. };
  16635. /**
  16636. * Applies mipped bicubic texture filtering to the given texture node.
  16637. *
  16638. * @tsl
  16639. * @function
  16640. * @param {TextureNode} textureNode - The texture node that should be filtered.
  16641. * @param {Node<float>} lodNode - Defines the LOD to sample from.
  16642. * @return {Node} The filtered texture sample.
  16643. */
  16644. const textureBicubicLevel = /*@__PURE__*/ Fn( ( [ textureNode, lodNode ] ) => {
  16645. const fLodSize = vec2( textureNode.size( int( lodNode ) ) );
  16646. const cLodSize = vec2( textureNode.size( int( lodNode.add( 1.0 ) ) ) );
  16647. const fLodSizeInv = div( 1.0, fLodSize );
  16648. const cLodSizeInv = div( 1.0, cLodSize );
  16649. const fSample = bicubic( textureNode, vec4( fLodSizeInv, fLodSize ), floor( lodNode ) );
  16650. const cSample = bicubic( textureNode, vec4( cLodSizeInv, cLodSize ), ceil( lodNode ) );
  16651. return fract( lodNode ).mix( fSample, cSample );
  16652. } );
  16653. /**
  16654. * Applies mipped bicubic texture filtering to the given texture node.
  16655. *
  16656. * @tsl
  16657. * @function
  16658. * @param {TextureNode} textureNode - The texture node that should be filtered.
  16659. * @param {Node<float>} [strength] - Defines the strength of the bicubic filtering.
  16660. * @return {Node} The filtered texture sample.
  16661. */
  16662. const textureBicubic = /*@__PURE__*/ Fn( ( [ textureNode, strength ] ) => {
  16663. const lod = strength.mul( maxMipLevel( textureNode ) );
  16664. return textureBicubicLevel( textureNode, lod );
  16665. } );
  16666. //
  16667. // Transmission
  16668. //
  16669. const getVolumeTransmissionRay = /*@__PURE__*/ Fn( ( [ n, v, thickness, ior, modelMatrix ] ) => {
  16670. // Direction of refracted light.
  16671. const refractionVector = vec3( refract( v.negate(), normalize( n ), div( 1.0, ior ) ) );
  16672. // Compute rotation-independent scaling of the model matrix.
  16673. const modelScale = vec3(
  16674. length( modelMatrix[ 0 ].xyz ),
  16675. length( modelMatrix[ 1 ].xyz ),
  16676. length( modelMatrix[ 2 ].xyz )
  16677. );
  16678. // The thickness is specified in local space.
  16679. return normalize( refractionVector ).mul( thickness.mul( modelScale ) );
  16680. } ).setLayout( {
  16681. name: 'getVolumeTransmissionRay',
  16682. type: 'vec3',
  16683. inputs: [
  16684. { name: 'n', type: 'vec3' },
  16685. { name: 'v', type: 'vec3' },
  16686. { name: 'thickness', type: 'float' },
  16687. { name: 'ior', type: 'float' },
  16688. { name: 'modelMatrix', type: 'mat4' }
  16689. ]
  16690. } );
  16691. const applyIorToRoughness = /*@__PURE__*/ Fn( ( [ roughness, ior ] ) => {
  16692. // Scale roughness with IOR so that an IOR of 1.0 results in no microfacet refraction and
  16693. // an IOR of 1.5 results in the default amount of microfacet refraction.
  16694. return roughness.mul( clamp( ior.mul( 2.0 ).sub( 2.0 ), 0.0, 1.0 ) );
  16695. } ).setLayout( {
  16696. name: 'applyIorToRoughness',
  16697. type: 'float',
  16698. inputs: [
  16699. { name: 'roughness', type: 'float' },
  16700. { name: 'ior', type: 'float' }
  16701. ]
  16702. } );
  16703. const viewportBackSideTexture = /*@__PURE__*/ viewportMipTexture();
  16704. const viewportFrontSideTexture = /*@__PURE__*/ viewportMipTexture();
  16705. const getTransmissionSample = /*@__PURE__*/ Fn( ( [ fragCoord, roughness, ior ], { material } ) => {
  16706. const vTexture = material.side === BackSide ? viewportBackSideTexture : viewportFrontSideTexture;
  16707. const transmissionSample = vTexture.sample( fragCoord );
  16708. //const transmissionSample = viewportMipTexture( fragCoord );
  16709. const lod = log2( screenSize.x ).mul( applyIorToRoughness( roughness, ior ) );
  16710. return textureBicubicLevel( transmissionSample, lod );
  16711. } );
  16712. const volumeAttenuation = /*@__PURE__*/ Fn( ( [ transmissionDistance, attenuationColor, attenuationDistance ] ) => {
  16713. If( attenuationDistance.notEqual( 0 ), () => {
  16714. // Compute light attenuation using Beer's law.
  16715. const attenuationCoefficient = log( attenuationColor ).negate().div( attenuationDistance );
  16716. const transmittance = exp( attenuationCoefficient.negate().mul( transmissionDistance ) );
  16717. return transmittance;
  16718. } );
  16719. // Attenuation distance is +∞, i.e. the transmitted color is not attenuated at all.
  16720. return vec3( 1.0 );
  16721. } ).setLayout( {
  16722. name: 'volumeAttenuation',
  16723. type: 'vec3',
  16724. inputs: [
  16725. { name: 'transmissionDistance', type: 'float' },
  16726. { name: 'attenuationColor', type: 'vec3' },
  16727. { name: 'attenuationDistance', type: 'float' }
  16728. ]
  16729. } );
  16730. const getIBLVolumeRefraction = /*@__PURE__*/ Fn( ( [ n, v, roughness, diffuseColor, specularColor, specularF90, position, modelMatrix, viewMatrix, projMatrix, ior, thickness, attenuationColor, attenuationDistance, dispersion ] ) => {
  16731. let transmittedLight, transmittance;
  16732. if ( dispersion ) {
  16733. transmittedLight = vec4().toVar();
  16734. transmittance = vec3().toVar();
  16735. const halfSpread = ior.sub( 1.0 ).mul( dispersion.mul( 0.025 ) );
  16736. const iors = vec3( ior.sub( halfSpread ), ior, ior.add( halfSpread ) );
  16737. Loop( { start: 0, end: 3 }, ( { i } ) => {
  16738. const ior = iors.element( i );
  16739. const transmissionRay = getVolumeTransmissionRay( n, v, thickness, ior, modelMatrix );
  16740. const refractedRayExit = position.add( transmissionRay );
  16741. // Project refracted vector on the framebuffer, while mapping to normalized device coordinates.
  16742. const ndcPos = projMatrix.mul( viewMatrix.mul( vec4( refractedRayExit, 1.0 ) ) );
  16743. const refractionCoords = vec2( ndcPos.xy.div( ndcPos.w ) ).toVar();
  16744. refractionCoords.addAssign( 1.0 );
  16745. refractionCoords.divAssign( 2.0 );
  16746. refractionCoords.assign( vec2( refractionCoords.x, refractionCoords.y.oneMinus() ) ); // webgpu
  16747. // Sample framebuffer to get pixel the refracted ray hits.
  16748. const transmissionSample = getTransmissionSample( refractionCoords, roughness, ior );
  16749. transmittedLight.element( i ).assign( transmissionSample.element( i ) );
  16750. transmittedLight.a.addAssign( transmissionSample.a );
  16751. transmittance.element( i ).assign( diffuseColor.element( i ).mul( volumeAttenuation( length( transmissionRay ), attenuationColor, attenuationDistance ).element( i ) ) );
  16752. } );
  16753. transmittedLight.a.divAssign( 3.0 );
  16754. } else {
  16755. const transmissionRay = getVolumeTransmissionRay( n, v, thickness, ior, modelMatrix );
  16756. const refractedRayExit = position.add( transmissionRay );
  16757. // Project refracted vector on the framebuffer, while mapping to normalized device coordinates.
  16758. const ndcPos = projMatrix.mul( viewMatrix.mul( vec4( refractedRayExit, 1.0 ) ) );
  16759. const refractionCoords = vec2( ndcPos.xy.div( ndcPos.w ) ).toVar();
  16760. refractionCoords.addAssign( 1.0 );
  16761. refractionCoords.divAssign( 2.0 );
  16762. refractionCoords.assign( vec2( refractionCoords.x, refractionCoords.y.oneMinus() ) ); // webgpu
  16763. // Sample framebuffer to get pixel the refracted ray hits.
  16764. transmittedLight = getTransmissionSample( refractionCoords, roughness, ior );
  16765. transmittance = diffuseColor.mul( volumeAttenuation( length( transmissionRay ), attenuationColor, attenuationDistance ) );
  16766. }
  16767. const attenuatedColor = transmittance.rgb.mul( transmittedLight.rgb );
  16768. const dotNV = n.dot( v ).clamp();
  16769. // Get the specular component.
  16770. const F = vec3( EnvironmentBRDF( { // n, v, specularColor, specularF90, roughness
  16771. dotNV,
  16772. specularColor,
  16773. specularF90,
  16774. roughness
  16775. } ) );
  16776. // As less light is transmitted, the opacity should be increased. This simple approximation does a decent job
  16777. // of modulating a CSS background, and has no effect when the buffer is opaque, due to a solid object or clear color.
  16778. const transmittanceFactor = transmittance.r.add( transmittance.g, transmittance.b ).div( 3.0 );
  16779. return vec4( F.oneMinus().mul( attenuatedColor ), transmittedLight.a.oneMinus().mul( transmittanceFactor ).oneMinus() );
  16780. } );
  16781. //
  16782. // Iridescence
  16783. //
  16784. // XYZ to linear-sRGB color space
  16785. const XYZ_TO_REC709 = /*@__PURE__*/ mat3(
  16786. 3.2404542, -0.969266, 0.0556434,
  16787. -1.5371385, 1.8760108, -0.2040259,
  16788. -0.4985314, 0.0415560, 1.0572252
  16789. );
  16790. // Assume air interface for top
  16791. // Note: We don't handle the case fresnel0 == 1
  16792. const Fresnel0ToIor = ( fresnel0 ) => {
  16793. const sqrtF0 = fresnel0.sqrt();
  16794. return vec3( 1.0 ).add( sqrtF0 ).div( vec3( 1.0 ).sub( sqrtF0 ) );
  16795. };
  16796. // ior is a value between 1.0 and 3.0. 1.0 is air interface
  16797. const IorToFresnel0 = ( transmittedIor, incidentIor ) => {
  16798. return transmittedIor.sub( incidentIor ).div( transmittedIor.add( incidentIor ) ).pow2();
  16799. };
  16800. // Fresnel equations for dielectric/dielectric interfaces.
  16801. // Ref: https://belcour.github.io/blog/research/2017/05/01/brdf-thin-film.html
  16802. // Evaluation XYZ sensitivity curves in Fourier space
  16803. const evalSensitivity = ( OPD, shift ) => {
  16804. const phase = OPD.mul( 2.0 * Math.PI * 1.0e-9 );
  16805. const val = vec3( 5.4856e-13, 4.4201e-13, 5.2481e-13 );
  16806. const pos = vec3( 1.6810e+06, 1.7953e+06, 2.2084e+06 );
  16807. const VAR = vec3( 4.3278e+09, 9.3046e+09, 6.6121e+09 );
  16808. 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( -45282e5 ).exp() );
  16809. 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() );
  16810. xyz = vec3( xyz.x.add( x ), xyz.y, xyz.z ).div( 1.0685e-7 );
  16811. const rgb = XYZ_TO_REC709.mul( xyz );
  16812. return rgb;
  16813. };
  16814. const evalIridescence = /*@__PURE__*/ Fn( ( { outsideIOR, eta2, cosTheta1, thinFilmThickness, baseF0 } ) => {
  16815. // Force iridescenceIOR -> outsideIOR when thinFilmThickness -> 0.0
  16816. const iridescenceIOR = mix( outsideIOR, eta2, smoothstep( 0.0, 0.03, thinFilmThickness ) );
  16817. // Evaluate the cosTheta on the base layer (Snell law)
  16818. const sinTheta2Sq = outsideIOR.div( iridescenceIOR ).pow2().mul( cosTheta1.pow2().oneMinus() );
  16819. // Handle TIR:
  16820. const cosTheta2Sq = sinTheta2Sq.oneMinus();
  16821. If( cosTheta2Sq.lessThan( 0 ), () => {
  16822. return vec3( 1.0 );
  16823. } );
  16824. const cosTheta2 = cosTheta2Sq.sqrt();
  16825. // First interface
  16826. const R0 = IorToFresnel0( iridescenceIOR, outsideIOR );
  16827. const R12 = F_Schlick( { f0: R0, f90: 1.0, dotVH: cosTheta1 } );
  16828. //const R21 = R12;
  16829. const T121 = R12.oneMinus();
  16830. const phi12 = iridescenceIOR.lessThan( outsideIOR ).select( Math.PI, 0.0 );
  16831. const phi21 = float( Math.PI ).sub( phi12 );
  16832. // Second interface
  16833. const baseIOR = Fresnel0ToIor( baseF0.clamp( 0.0, 0.9999 ) ); // guard against 1.0
  16834. const R1 = IorToFresnel0( baseIOR, iridescenceIOR.toVec3() );
  16835. const R23 = F_Schlick( { f0: R1, f90: 1.0, dotVH: cosTheta2 } );
  16836. const phi23 = vec3(
  16837. baseIOR.x.lessThan( iridescenceIOR ).select( Math.PI, 0.0 ),
  16838. baseIOR.y.lessThan( iridescenceIOR ).select( Math.PI, 0.0 ),
  16839. baseIOR.z.lessThan( iridescenceIOR ).select( Math.PI, 0.0 )
  16840. );
  16841. // Phase shift
  16842. const OPD = iridescenceIOR.mul( thinFilmThickness, cosTheta2, 2.0 );
  16843. const phi = vec3( phi21 ).add( phi23 );
  16844. // Compound terms
  16845. const R123 = R12.mul( R23 ).clamp( 1e-5, 0.9999 );
  16846. const r123 = R123.sqrt();
  16847. const Rs = T121.pow2().mul( R23 ).div( vec3( 1.0 ).sub( R123 ) );
  16848. // Reflectance term for m = 0 (DC term amplitude)
  16849. const C0 = R12.add( Rs );
  16850. const I = C0.toVar();
  16851. // Reflectance term for m > 0 (pairs of diracs)
  16852. const Cm = Rs.sub( T121 ).toVar();
  16853. Loop( { start: 1, end: 2, condition: '<=', name: 'm' }, ( { m } ) => {
  16854. Cm.mulAssign( r123 );
  16855. const Sm = evalSensitivity( float( m ).mul( OPD ), float( m ).mul( phi ) ).mul( 2.0 );
  16856. I.addAssign( Cm.mul( Sm ) );
  16857. } );
  16858. // Since out of gamut colors might be produced, negative color values are clamped to 0.
  16859. return I.max( vec3( 0.0 ) );
  16860. } ).setLayout( {
  16861. name: 'evalIridescence',
  16862. type: 'vec3',
  16863. inputs: [
  16864. { name: 'outsideIOR', type: 'float' },
  16865. { name: 'eta2', type: 'float' },
  16866. { name: 'cosTheta1', type: 'float' },
  16867. { name: 'thinFilmThickness', type: 'float' },
  16868. { name: 'baseF0', type: 'vec3' }
  16869. ]
  16870. } );
  16871. //
  16872. // Sheen
  16873. //
  16874. // This is a curve-fit approximation to the "Charlie sheen" BRDF integrated over the hemisphere from
  16875. // Estevez and Kulla 2017, "Production Friendly Microfacet Sheen BRDF". The analysis can be found
  16876. // in the Sheen section of https://drive.google.com/file/d/1T0D1VSyR4AllqIJTQAraEIzjlb5h4FKH/view?usp=sharing
  16877. const IBLSheenBRDF = /*@__PURE__*/ Fn( ( { normal, viewDir, roughness } ) => {
  16878. const dotNV = normal.dot( viewDir ).saturate();
  16879. const r2 = roughness.pow2();
  16880. const a = select(
  16881. roughness.lessThan( 0.25 ),
  16882. float( -339.2 ).mul( r2 ).add( float( 161.4 ).mul( roughness ) ).sub( 25.9 ),
  16883. float( -8.48 ).mul( r2 ).add( float( 14.3 ).mul( roughness ) ).sub( 9.95 )
  16884. );
  16885. const b = select(
  16886. roughness.lessThan( 0.25 ),
  16887. float( 44.0 ).mul( r2 ).sub( float( 23.7 ).mul( roughness ) ).add( 3.26 ),
  16888. float( 1.97 ).mul( r2 ).sub( float( 3.27 ).mul( roughness ) ).add( 0.72 )
  16889. );
  16890. const DG = select( roughness.lessThan( 0.25 ), 0.0, float( 0.1 ).mul( roughness ).sub( 0.025 ) ).add( a.mul( dotNV ).add( b ).exp() );
  16891. return DG.mul( 1.0 / Math.PI ).saturate();
  16892. } );
  16893. const clearcoatF0 = vec3( 0.04 );
  16894. const clearcoatF90 = float( 1 );
  16895. /**
  16896. * Represents the lighting model for a PBR material.
  16897. *
  16898. * @augments LightingModel
  16899. */
  16900. class PhysicalLightingModel extends LightingModel {
  16901. /**
  16902. * Constructs a new physical lighting model.
  16903. *
  16904. * @param {boolean} [clearcoat=false] - Whether clearcoat is supported or not.
  16905. * @param {boolean} [sheen=false] - Whether sheen is supported or not.
  16906. * @param {boolean} [iridescence=false] - Whether iridescence is supported or not.
  16907. * @param {boolean} [anisotropy=false] - Whether anisotropy is supported or not.
  16908. * @param {boolean} [transmission=false] - Whether transmission is supported or not.
  16909. * @param {boolean} [dispersion=false] - Whether dispersion is supported or not.
  16910. */
  16911. constructor( clearcoat = false, sheen = false, iridescence = false, anisotropy = false, transmission = false, dispersion = false ) {
  16912. super();
  16913. /**
  16914. * Whether clearcoat is supported or not.
  16915. *
  16916. * @type {boolean}
  16917. * @default false
  16918. */
  16919. this.clearcoat = clearcoat;
  16920. /**
  16921. * Whether sheen is supported or not.
  16922. *
  16923. * @type {boolean}
  16924. * @default false
  16925. */
  16926. this.sheen = sheen;
  16927. /**
  16928. * Whether iridescence is supported or not.
  16929. *
  16930. * @type {boolean}
  16931. * @default false
  16932. */
  16933. this.iridescence = iridescence;
  16934. /**
  16935. * Whether anisotropy is supported or not.
  16936. *
  16937. * @type {boolean}
  16938. * @default false
  16939. */
  16940. this.anisotropy = anisotropy;
  16941. /**
  16942. * Whether transmission is supported or not.
  16943. *
  16944. * @type {boolean}
  16945. * @default false
  16946. */
  16947. this.transmission = transmission;
  16948. /**
  16949. * Whether dispersion is supported or not.
  16950. *
  16951. * @type {boolean}
  16952. * @default false
  16953. */
  16954. this.dispersion = dispersion;
  16955. /**
  16956. * The clear coat radiance.
  16957. *
  16958. * @type {?Node}
  16959. * @default null
  16960. */
  16961. this.clearcoatRadiance = null;
  16962. /**
  16963. * The clear coat specular direct.
  16964. *
  16965. * @type {?Node}
  16966. * @default null
  16967. */
  16968. this.clearcoatSpecularDirect = null;
  16969. /**
  16970. * The clear coat specular indirect.
  16971. *
  16972. * @type {?Node}
  16973. * @default null
  16974. */
  16975. this.clearcoatSpecularIndirect = null;
  16976. /**
  16977. * The sheen specular direct.
  16978. *
  16979. * @type {?Node}
  16980. * @default null
  16981. */
  16982. this.sheenSpecularDirect = null;
  16983. /**
  16984. * The sheen specular indirect.
  16985. *
  16986. * @type {?Node}
  16987. * @default null
  16988. */
  16989. this.sheenSpecularIndirect = null;
  16990. /**
  16991. * The iridescence Fresnel.
  16992. *
  16993. * @type {?Node}
  16994. * @default null
  16995. */
  16996. this.iridescenceFresnel = null;
  16997. /**
  16998. * The iridescence F0.
  16999. *
  17000. * @type {?Node}
  17001. * @default null
  17002. */
  17003. this.iridescenceF0 = null;
  17004. }
  17005. /**
  17006. * Depending on what features are requested, the method prepares certain node variables
  17007. * which are later used for lighting computations.
  17008. *
  17009. * @param {NodeBuilder} builder - The current node builder.
  17010. */
  17011. start( builder ) {
  17012. if ( this.clearcoat === true ) {
  17013. this.clearcoatRadiance = vec3().toVar( 'clearcoatRadiance' );
  17014. this.clearcoatSpecularDirect = vec3().toVar( 'clearcoatSpecularDirect' );
  17015. this.clearcoatSpecularIndirect = vec3().toVar( 'clearcoatSpecularIndirect' );
  17016. }
  17017. if ( this.sheen === true ) {
  17018. this.sheenSpecularDirect = vec3().toVar( 'sheenSpecularDirect' );
  17019. this.sheenSpecularIndirect = vec3().toVar( 'sheenSpecularIndirect' );
  17020. }
  17021. if ( this.iridescence === true ) {
  17022. const dotNVi = normalView.dot( positionViewDirection ).clamp();
  17023. this.iridescenceFresnel = evalIridescence( {
  17024. outsideIOR: float( 1.0 ),
  17025. eta2: iridescenceIOR,
  17026. cosTheta1: dotNVi,
  17027. thinFilmThickness: iridescenceThickness,
  17028. baseF0: specularColorBlended
  17029. } );
  17030. this.iridescenceF0 = Schlick_to_F0( { f: this.iridescenceFresnel, f90: 1.0, dotVH: dotNVi } );
  17031. }
  17032. if ( this.transmission === true ) {
  17033. const position = positionWorld;
  17034. const v = cameraPosition.sub( positionWorld ).normalize(); // TODO: Create Node for this, same issue in MaterialX
  17035. const n = normalWorld;
  17036. const context = builder.context;
  17037. context.backdrop = getIBLVolumeRefraction(
  17038. n,
  17039. v,
  17040. roughness,
  17041. diffuseContribution,
  17042. specularColorBlended,
  17043. specularF90, // specularF90
  17044. position, // positionWorld
  17045. modelWorldMatrix, // modelMatrix
  17046. cameraViewMatrix, // viewMatrix
  17047. cameraProjectionMatrix, // projMatrix
  17048. ior,
  17049. thickness,
  17050. attenuationColor,
  17051. attenuationDistance,
  17052. this.dispersion ? dispersion : null
  17053. );
  17054. context.backdropAlpha = transmission;
  17055. diffuseColor.a.mulAssign( mix( 1, context.backdrop.a, transmission ) );
  17056. }
  17057. super.start( builder );
  17058. }
  17059. // Fdez-Agüera's "Multiple-Scattering Microfacet Model for Real-Time Image Based Lighting"
  17060. // Approximates multi-scattering in order to preserve energy.
  17061. // http://www.jcgt.org/published/0008/01/03/
  17062. computeMultiscattering( singleScatter, multiScatter, specularF90, f0 ) {
  17063. const dotNV = normalView.dot( positionViewDirection ).clamp(); // @ TODO: Move to core dotNV
  17064. const fab = DFGApprox( { roughness, dotNV } );
  17065. const Fr = this.iridescenceF0 ? iridescence.mix( f0, this.iridescenceF0 ) : f0;
  17066. const FssEss = Fr.mul( fab.x ).add( specularF90.mul( fab.y ) );
  17067. const Ess = fab.x.add( fab.y );
  17068. const Ems = Ess.oneMinus();
  17069. const Favg = Fr.add( Fr.oneMinus().mul( 0.047619 ) ); // 1/21
  17070. const Fms = FssEss.mul( Favg ).div( Ems.mul( Favg ).oneMinus() );
  17071. singleScatter.addAssign( FssEss );
  17072. multiScatter.addAssign( Fms.mul( Ems ) );
  17073. }
  17074. /**
  17075. * Implements the direct light.
  17076. *
  17077. * @param {Object} lightData - The light data.
  17078. * @param {NodeBuilder} builder - The current node builder.
  17079. */
  17080. direct( { lightDirection, lightColor, reflectedLight }, /* builder */ ) {
  17081. const dotNL = normalView.dot( lightDirection ).clamp();
  17082. const irradiance = dotNL.mul( lightColor );
  17083. if ( this.sheen === true ) {
  17084. this.sheenSpecularDirect.addAssign( irradiance.mul( BRDF_Sheen( { lightDirection } ) ) );
  17085. }
  17086. if ( this.clearcoat === true ) {
  17087. const dotNLcc = clearcoatNormalView.dot( lightDirection ).clamp();
  17088. const ccIrradiance = dotNLcc.mul( lightColor );
  17089. this.clearcoatSpecularDirect.addAssign( ccIrradiance.mul( BRDF_GGX( { lightDirection, f0: clearcoatF0, f90: clearcoatF90, roughness: clearcoatRoughness, normalView: clearcoatNormalView } ) ) );
  17090. }
  17091. reflectedLight.directDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor: diffuseContribution } ) ) );
  17092. reflectedLight.directSpecular.addAssign( irradiance.mul( BRDF_GGX_Multiscatter( { lightDirection, f0: specularColorBlended, f90: 1, roughness, f: this.iridescenceFresnel, USE_IRIDESCENCE: this.iridescence, USE_ANISOTROPY: this.anisotropy } ) ) );
  17093. }
  17094. /**
  17095. * This method is intended for implementing the direct light term for
  17096. * rect area light nodes.
  17097. *
  17098. * @param {Object} input - The input data.
  17099. * @param {NodeBuilder} builder - The current node builder.
  17100. */
  17101. directRectArea( { lightColor, lightPosition, halfWidth, halfHeight, reflectedLight, ltc_1, ltc_2 }, /* builder */ ) {
  17102. const p0 = lightPosition.add( halfWidth ).sub( halfHeight ); // counterclockwise; light shines in local neg z direction
  17103. const p1 = lightPosition.sub( halfWidth ).sub( halfHeight );
  17104. const p2 = lightPosition.sub( halfWidth ).add( halfHeight );
  17105. const p3 = lightPosition.add( halfWidth ).add( halfHeight );
  17106. const N = normalView;
  17107. const V = positionViewDirection;
  17108. const P = positionView.toVar();
  17109. const uv = LTC_Uv( { N, V, roughness } );
  17110. const t1 = ltc_1.sample( uv ).toVar();
  17111. const t2 = ltc_2.sample( uv ).toVar();
  17112. const mInv = mat3(
  17113. vec3( t1.x, 0, t1.y ),
  17114. vec3( 0, 1, 0 ),
  17115. vec3( t1.z, 0, t1.w )
  17116. ).toVar();
  17117. // LTC Fresnel Approximation by Stephen Hill
  17118. // http://blog.selfshadow.com/publications/s2016-advances/s2016_ltc_fresnel.pdf
  17119. const fresnel = specularColorBlended.mul( t2.x ).add( specularColorBlended.oneMinus().mul( t2.y ) ).toVar();
  17120. reflectedLight.directSpecular.addAssign( lightColor.mul( fresnel ).mul( LTC_Evaluate( { N, V, P, mInv, p0, p1, p2, p3 } ) ) );
  17121. reflectedLight.directDiffuse.addAssign( lightColor.mul( diffuseContribution ).mul( LTC_Evaluate( { N, V, P, mInv: mat3( 1, 0, 0, 0, 1, 0, 0, 0, 1 ), p0, p1, p2, p3 } ) ) );
  17122. }
  17123. /**
  17124. * Implements the indirect lighting.
  17125. *
  17126. * @param {NodeBuilder} builder - The current node builder.
  17127. */
  17128. indirect( builder ) {
  17129. this.indirectDiffuse( builder );
  17130. this.indirectSpecular( builder );
  17131. this.ambientOcclusion( builder );
  17132. }
  17133. /**
  17134. * Implements the indirect diffuse term.
  17135. *
  17136. * @param {NodeBuilder} builder - The current node builder.
  17137. */
  17138. indirectDiffuse( builder ) {
  17139. const { irradiance, reflectedLight } = builder.context;
  17140. reflectedLight.indirectDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor: diffuseContribution } ) ) );
  17141. }
  17142. /**
  17143. * Implements the indirect specular term.
  17144. *
  17145. * @param {NodeBuilder} builder - The current node builder.
  17146. */
  17147. indirectSpecular( builder ) {
  17148. const { radiance, iblIrradiance, reflectedLight } = builder.context;
  17149. if ( this.sheen === true ) {
  17150. this.sheenSpecularIndirect.addAssign( iblIrradiance.mul(
  17151. sheen,
  17152. IBLSheenBRDF( {
  17153. normal: normalView,
  17154. viewDir: positionViewDirection,
  17155. roughness: sheenRoughness
  17156. } )
  17157. ) );
  17158. }
  17159. if ( this.clearcoat === true ) {
  17160. const dotNVcc = clearcoatNormalView.dot( positionViewDirection ).clamp();
  17161. const clearcoatEnv = EnvironmentBRDF( {
  17162. dotNV: dotNVcc,
  17163. specularColor: clearcoatF0,
  17164. specularF90: clearcoatF90,
  17165. roughness: clearcoatRoughness
  17166. } );
  17167. this.clearcoatSpecularIndirect.addAssign( this.clearcoatRadiance.mul( clearcoatEnv ) );
  17168. }
  17169. // Both indirect specular and indirect diffuse light accumulate here
  17170. // Compute multiscattering separately for dielectric and metallic, then mix
  17171. const singleScatteringDielectric = vec3().toVar( 'singleScatteringDielectric' );
  17172. const multiScatteringDielectric = vec3().toVar( 'multiScatteringDielectric' );
  17173. const singleScatteringMetallic = vec3().toVar( 'singleScatteringMetallic' );
  17174. const multiScatteringMetallic = vec3().toVar( 'multiScatteringMetallic' );
  17175. this.computeMultiscattering( singleScatteringDielectric, multiScatteringDielectric, specularF90, specularColor );
  17176. this.computeMultiscattering( singleScatteringMetallic, multiScatteringMetallic, specularF90, diffuseColor.rgb );
  17177. // Mix based on metalness
  17178. const singleScattering = mix( singleScatteringDielectric, singleScatteringMetallic, metalness );
  17179. const multiScattering = mix( multiScatteringDielectric, multiScatteringMetallic, metalness );
  17180. // Diffuse energy conservation uses dielectric path
  17181. const totalScatteringDielectric = singleScatteringDielectric.add( multiScatteringDielectric );
  17182. const diffuse = diffuseContribution.mul( totalScatteringDielectric.r.max( totalScatteringDielectric.g ).max( totalScatteringDielectric.b ).oneMinus() );
  17183. const cosineWeightedIrradiance = iblIrradiance.mul( 1 / Math.PI );
  17184. reflectedLight.indirectSpecular.addAssign( radiance.mul( singleScattering ) );
  17185. reflectedLight.indirectSpecular.addAssign( multiScattering.mul( cosineWeightedIrradiance ) );
  17186. reflectedLight.indirectDiffuse.addAssign( diffuse.mul( cosineWeightedIrradiance ) );
  17187. }
  17188. /**
  17189. * Implements the ambient occlusion term.
  17190. *
  17191. * @param {NodeBuilder} builder - The current node builder.
  17192. */
  17193. ambientOcclusion( builder ) {
  17194. const { ambientOcclusion, reflectedLight } = builder.context;
  17195. const dotNV = normalView.dot( positionViewDirection ).clamp(); // @ TODO: Move to core dotNV
  17196. const aoNV = dotNV.add( ambientOcclusion );
  17197. const aoExp = roughness.mul( -16 ).oneMinus().negate().exp2();
  17198. const aoNode = ambientOcclusion.sub( aoNV.pow( aoExp ).oneMinus() ).clamp();
  17199. if ( this.clearcoat === true ) {
  17200. this.clearcoatSpecularIndirect.mulAssign( ambientOcclusion );
  17201. }
  17202. if ( this.sheen === true ) {
  17203. this.sheenSpecularIndirect.mulAssign( ambientOcclusion );
  17204. }
  17205. reflectedLight.indirectDiffuse.mulAssign( ambientOcclusion );
  17206. reflectedLight.indirectSpecular.mulAssign( aoNode );
  17207. }
  17208. /**
  17209. * Used for final lighting accumulations depending on the requested features.
  17210. *
  17211. * @param {NodeBuilder} builder - The current node builder.
  17212. */
  17213. finish( { context } ) {
  17214. const { outgoingLight } = context;
  17215. if ( this.clearcoat === true ) {
  17216. const dotNVcc = clearcoatNormalView.dot( positionViewDirection ).clamp();
  17217. const Fcc = F_Schlick( {
  17218. dotVH: dotNVcc,
  17219. f0: clearcoatF0,
  17220. f90: clearcoatF90
  17221. } );
  17222. const clearcoatLight = outgoingLight.mul( clearcoat.mul( Fcc ).oneMinus() ).add( this.clearcoatSpecularDirect.add( this.clearcoatSpecularIndirect ).mul( clearcoat ) );
  17223. outgoingLight.assign( clearcoatLight );
  17224. }
  17225. if ( this.sheen === true ) {
  17226. const sheenEnergyComp = sheen.r.max( sheen.g ).max( sheen.b ).mul( 0.157 ).oneMinus();
  17227. const sheenLight = outgoingLight.mul( sheenEnergyComp ).add( this.sheenSpecularDirect, this.sheenSpecularIndirect );
  17228. outgoingLight.assign( sheenLight );
  17229. }
  17230. }
  17231. }
  17232. // These defines must match with PMREMGenerator
  17233. const cubeUV_r0 = /*@__PURE__*/ float( 1.0 );
  17234. const cubeUV_m0 = /*@__PURE__*/ float( -2 );
  17235. const cubeUV_r1 = /*@__PURE__*/ float( 0.8 );
  17236. const cubeUV_m1 = /*@__PURE__*/ float( -1 );
  17237. const cubeUV_r4 = /*@__PURE__*/ float( 0.4 );
  17238. const cubeUV_m4 = /*@__PURE__*/ float( 2.0 );
  17239. const cubeUV_r5 = /*@__PURE__*/ float( 0.305 );
  17240. const cubeUV_m5 = /*@__PURE__*/ float( 3.0 );
  17241. const cubeUV_r6 = /*@__PURE__*/ float( 0.21 );
  17242. const cubeUV_m6 = /*@__PURE__*/ float( 4.0 );
  17243. const cubeUV_minMipLevel = /*@__PURE__*/ float( 4.0 );
  17244. const cubeUV_minTileSize = /*@__PURE__*/ float( 16.0 );
  17245. // These shader functions convert between the UV coordinates of a single face of
  17246. // a cubemap, the 0-5 integer index of a cube face, and the direction vector for
  17247. // sampling a textureCube (not generally normalized ).
  17248. const getFace = /*@__PURE__*/ Fn( ( [ direction ] ) => {
  17249. const absDirection = vec3( abs( direction ) ).toVar();
  17250. const face = float( -1 ).toVar();
  17251. If( absDirection.x.greaterThan( absDirection.z ), () => {
  17252. If( absDirection.x.greaterThan( absDirection.y ), () => {
  17253. face.assign( select( direction.x.greaterThan( 0.0 ), 0.0, 3.0 ) );
  17254. } ).Else( () => {
  17255. face.assign( select( direction.y.greaterThan( 0.0 ), 1.0, 4.0 ) );
  17256. } );
  17257. } ).Else( () => {
  17258. If( absDirection.z.greaterThan( absDirection.y ), () => {
  17259. face.assign( select( direction.z.greaterThan( 0.0 ), 2.0, 5.0 ) );
  17260. } ).Else( () => {
  17261. face.assign( select( direction.y.greaterThan( 0.0 ), 1.0, 4.0 ) );
  17262. } );
  17263. } );
  17264. return face;
  17265. } ).setLayout( {
  17266. name: 'getFace',
  17267. type: 'float',
  17268. inputs: [
  17269. { name: 'direction', type: 'vec3' }
  17270. ]
  17271. } );
  17272. // RH coordinate system; PMREM face-indexing convention
  17273. const getUV = /*@__PURE__*/ Fn( ( [ direction, face ] ) => {
  17274. const uv = vec2().toVar();
  17275. If( face.equal( 0.0 ), () => {
  17276. uv.assign( vec2( direction.z, direction.y ).div( abs( direction.x ) ) ); // pos x
  17277. } ).ElseIf( face.equal( 1.0 ), () => {
  17278. uv.assign( vec2( direction.x.negate(), direction.z.negate() ).div( abs( direction.y ) ) ); // pos y
  17279. } ).ElseIf( face.equal( 2.0 ), () => {
  17280. uv.assign( vec2( direction.x.negate(), direction.y ).div( abs( direction.z ) ) ); // pos z
  17281. } ).ElseIf( face.equal( 3.0 ), () => {
  17282. uv.assign( vec2( direction.z.negate(), direction.y ).div( abs( direction.x ) ) ); // neg x
  17283. } ).ElseIf( face.equal( 4.0 ), () => {
  17284. uv.assign( vec2( direction.x.negate(), direction.z ).div( abs( direction.y ) ) ); // neg y
  17285. } ).Else( () => {
  17286. uv.assign( vec2( direction.x, direction.y ).div( abs( direction.z ) ) ); // neg z
  17287. } );
  17288. return mul( 0.5, uv.add( 1.0 ) );
  17289. } ).setLayout( {
  17290. name: 'getUV',
  17291. type: 'vec2',
  17292. inputs: [
  17293. { name: 'direction', type: 'vec3' },
  17294. { name: 'face', type: 'float' }
  17295. ]
  17296. } );
  17297. const roughnessToMip = /*@__PURE__*/ Fn( ( [ roughness ] ) => {
  17298. const mip = float( 0.0 ).toVar();
  17299. If( roughness.greaterThanEqual( cubeUV_r1 ), () => {
  17300. mip.assign( cubeUV_r0.sub( roughness ).mul( cubeUV_m1.sub( cubeUV_m0 ) ).div( cubeUV_r0.sub( cubeUV_r1 ) ).add( cubeUV_m0 ) );
  17301. } ).ElseIf( roughness.greaterThanEqual( cubeUV_r4 ), () => {
  17302. mip.assign( cubeUV_r1.sub( roughness ).mul( cubeUV_m4.sub( cubeUV_m1 ) ).div( cubeUV_r1.sub( cubeUV_r4 ) ).add( cubeUV_m1 ) );
  17303. } ).ElseIf( roughness.greaterThanEqual( cubeUV_r5 ), () => {
  17304. mip.assign( cubeUV_r4.sub( roughness ).mul( cubeUV_m5.sub( cubeUV_m4 ) ).div( cubeUV_r4.sub( cubeUV_r5 ) ).add( cubeUV_m4 ) );
  17305. } ).ElseIf( roughness.greaterThanEqual( cubeUV_r6 ), () => {
  17306. mip.assign( cubeUV_r5.sub( roughness ).mul( cubeUV_m6.sub( cubeUV_m5 ) ).div( cubeUV_r5.sub( cubeUV_r6 ) ).add( cubeUV_m5 ) );
  17307. } ).Else( () => {
  17308. mip.assign( float( -2 ).mul( log2( mul( 1.16, roughness ) ) ) ); // 1.16 = 1.79^0.25
  17309. } );
  17310. return mip;
  17311. } ).setLayout( {
  17312. name: 'roughnessToMip',
  17313. type: 'float',
  17314. inputs: [
  17315. { name: 'roughness', type: 'float' }
  17316. ]
  17317. } );
  17318. // RH coordinate system; PMREM face-indexing convention
  17319. const getDirection = /*@__PURE__*/ Fn( ( [ uv_immutable, face ] ) => {
  17320. const uv = uv_immutable.toVar();
  17321. uv.assign( mul( 2.0, uv ).sub( 1.0 ) );
  17322. const direction = vec3( uv, 1.0 ).toVar();
  17323. If( face.equal( 0.0 ), () => {
  17324. direction.assign( direction.zyx ); // ( 1, v, u ) pos x
  17325. } ).ElseIf( face.equal( 1.0 ), () => {
  17326. direction.assign( direction.xzy );
  17327. direction.xz.mulAssign( -1 ); // ( -u, 1, -v ) pos y
  17328. } ).ElseIf( face.equal( 2.0 ), () => {
  17329. direction.x.mulAssign( -1 ); // ( -u, v, 1 ) pos z
  17330. } ).ElseIf( face.equal( 3.0 ), () => {
  17331. direction.assign( direction.zyx );
  17332. direction.xz.mulAssign( -1 ); // ( -1, v, -u ) neg x
  17333. } ).ElseIf( face.equal( 4.0 ), () => {
  17334. direction.assign( direction.xzy );
  17335. direction.xy.mulAssign( -1 ); // ( -u, -1, v ) neg y
  17336. } ).ElseIf( face.equal( 5.0 ), () => {
  17337. direction.z.mulAssign( -1 ); // ( u, v, -1 ) neg zS
  17338. } );
  17339. return direction;
  17340. } ).setLayout( {
  17341. name: 'getDirection',
  17342. type: 'vec3',
  17343. inputs: [
  17344. { name: 'uv', type: 'vec2' },
  17345. { name: 'face', type: 'float' }
  17346. ]
  17347. } );
  17348. //
  17349. const textureCubeUV = /*@__PURE__*/ Fn( ( [ envMap, sampleDir_immutable, roughness_immutable, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP ] ) => {
  17350. const roughness = float( roughness_immutable );
  17351. const sampleDir = vec3( sampleDir_immutable );
  17352. const mip = clamp( roughnessToMip( roughness ), cubeUV_m0, CUBEUV_MAX_MIP );
  17353. const mipF = fract( mip );
  17354. const mipInt = floor( mip );
  17355. const color0 = vec3( bilinearCubeUV( envMap, sampleDir, mipInt, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP ) ).toVar();
  17356. If( mipF.notEqual( 0.0 ), () => {
  17357. const color1 = vec3( bilinearCubeUV( envMap, sampleDir, mipInt.add( 1.0 ), CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP ) ).toVar();
  17358. color0.assign( mix( color0, color1, mipF ) );
  17359. } );
  17360. return color0;
  17361. } );
  17362. const bilinearCubeUV = /*@__PURE__*/ Fn( ( [ envMap, direction_immutable, mipInt_immutable, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP ] ) => {
  17363. const mipInt = float( mipInt_immutable ).toVar();
  17364. const direction = vec3( direction_immutable );
  17365. const face = float( getFace( direction ) ).toVar();
  17366. const filterInt = float( max$1( cubeUV_minMipLevel.sub( mipInt ), 0.0 ) ).toVar();
  17367. mipInt.assign( max$1( mipInt, cubeUV_minMipLevel ) );
  17368. const faceSize = float( exp2( mipInt ) ).toVar();
  17369. const uv = vec2( getUV( direction, face ).mul( faceSize.sub( 2.0 ) ).add( 1.0 ) ).toVar();
  17370. If( face.greaterThan( 2.0 ), () => {
  17371. uv.y.addAssign( faceSize );
  17372. face.subAssign( 3.0 );
  17373. } );
  17374. uv.x.addAssign( face.mul( faceSize ) );
  17375. uv.x.addAssign( filterInt.mul( mul( 3.0, cubeUV_minTileSize ) ) );
  17376. uv.y.addAssign( mul( 4.0, exp2( CUBEUV_MAX_MIP ).sub( faceSize ) ) );
  17377. uv.x.mulAssign( CUBEUV_TEXEL_WIDTH );
  17378. uv.y.mulAssign( CUBEUV_TEXEL_HEIGHT );
  17379. return envMap.sample( uv ).grad( vec2(), vec2() ); // disable anisotropic filtering
  17380. } );
  17381. const getSample = /*@__PURE__*/ Fn( ( { envMap, mipInt, outputDirection, theta, axis, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP } ) => {
  17382. const cosTheta = cos( theta );
  17383. // Rodrigues' axis-angle rotation
  17384. const sampleDirection = outputDirection.mul( cosTheta )
  17385. .add( axis.cross( outputDirection ).mul( sin( theta ) ) )
  17386. .add( axis.mul( axis.dot( outputDirection ).mul( cosTheta.oneMinus() ) ) );
  17387. return bilinearCubeUV( envMap, sampleDirection, mipInt, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP );
  17388. } );
  17389. const blur = /*@__PURE__*/ Fn( ( { n, latitudinal, poleAxis, outputDirection, weights, samples, dTheta, mipInt, envMap, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP } ) => {
  17390. const axis = vec3( select( latitudinal, poleAxis, cross( poleAxis, outputDirection ) ) ).toVar();
  17391. If( axis.equal( vec3( 0.0 ) ), () => {
  17392. axis.assign( vec3( outputDirection.z, 0.0, outputDirection.x.negate() ) );
  17393. } );
  17394. axis.assign( normalize( axis ) );
  17395. const gl_FragColor = vec3().toVar();
  17396. gl_FragColor.addAssign( weights.element( 0 ).mul( getSample( { theta: 0.0, axis, outputDirection, mipInt, envMap, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP } ) ) );
  17397. Loop( { start: int( 1 ), end: n }, ( { i } ) => {
  17398. If( i.greaterThanEqual( samples ), () => {
  17399. Break();
  17400. } );
  17401. const theta = float( dTheta.mul( float( i ) ) ).toVar();
  17402. gl_FragColor.addAssign( weights.element( i ).mul( getSample( { theta: theta.mul( -1 ), axis, outputDirection, mipInt, envMap, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP } ) ) );
  17403. gl_FragColor.addAssign( weights.element( i ).mul( getSample( { theta, axis, outputDirection, mipInt, envMap, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP } ) ) );
  17404. } );
  17405. return vec4( gl_FragColor, 1 );
  17406. } );
  17407. // GGX VNDF importance sampling functions
  17408. // Van der Corput radical inverse for generating quasi-random sequences
  17409. const radicalInverse_VdC = /*@__PURE__*/ Fn( ( [ bits_immutable ] ) => {
  17410. const bits = uint( bits_immutable ).toVar();
  17411. bits.assign( bits.shiftLeft( uint( 16 ) ).bitOr( bits.shiftRight( uint( 16 ) ) ) );
  17412. bits.assign( bits.bitAnd( uint( 0x55555555 ) ).shiftLeft( uint( 1 ) ).bitOr( bits.bitAnd( uint( 0xAAAAAAAA ) ).shiftRight( uint( 1 ) ) ) );
  17413. bits.assign( bits.bitAnd( uint( 0x33333333 ) ).shiftLeft( uint( 2 ) ).bitOr( bits.bitAnd( uint( 0xCCCCCCCC ) ).shiftRight( uint( 2 ) ) ) );
  17414. bits.assign( bits.bitAnd( uint( 0x0F0F0F0F ) ).shiftLeft( uint( 4 ) ).bitOr( bits.bitAnd( uint( 0xF0F0F0F0 ) ).shiftRight( uint( 4 ) ) ) );
  17415. bits.assign( bits.bitAnd( uint( 0x00FF00FF ) ).shiftLeft( uint( 8 ) ).bitOr( bits.bitAnd( uint( 0xFF00FF00 ) ).shiftRight( uint( 8 ) ) ) );
  17416. return float( bits ).mul( 2.3283064365386963e-10 ); // / 0x100000000
  17417. } );
  17418. // Hammersley sequence for quasi-Monte Carlo sampling
  17419. const hammersley = /*@__PURE__*/ Fn( ( [ i, N ] ) => {
  17420. return vec2( float( i ).div( float( N ) ), radicalInverse_VdC( i ) );
  17421. } );
  17422. // GGX VNDF importance sampling (Eric Heitz 2018)
  17423. // "Sampling the GGX Distribution of Visible Normals"
  17424. // https://jcgt.org/published/0007/04/01/
  17425. const importanceSampleGGX_VNDF = /*@__PURE__*/ Fn( ( [ Xi, V_immutable, roughness_immutable ] ) => {
  17426. const V = vec3( V_immutable ).toVar();
  17427. const roughness = float( roughness_immutable );
  17428. const alpha = roughness.mul( roughness ).toVar();
  17429. // Section 3.2: Transform view direction to hemisphere configuration
  17430. const Vh = normalize( vec3( alpha.mul( V.x ), alpha.mul( V.y ), V.z ) ).toVar();
  17431. // Section 4.1: Orthonormal basis
  17432. const lensq = Vh.x.mul( Vh.x ).add( Vh.y.mul( Vh.y ) );
  17433. const T1 = select( lensq.greaterThan( 0.0 ), vec3( Vh.y.negate(), Vh.x, 0.0 ).div( sqrt( lensq ) ), vec3( 1.0, 0.0, 0.0 ) ).toVar();
  17434. const T2 = cross( Vh, T1 ).toVar();
  17435. // Section 4.2: Parameterization of projected area
  17436. const r = sqrt( Xi.x );
  17437. const phi = mul( 2.0, 3.14159265359 ).mul( Xi.y );
  17438. const t1 = r.mul( cos( phi ) ).toVar();
  17439. const t2 = r.mul( sin( phi ) ).toVar();
  17440. const s = mul( 0.5, Vh.z.add( 1.0 ) );
  17441. t2.assign( s.oneMinus().mul( sqrt( t1.mul( t1 ).oneMinus() ) ).add( s.mul( t2 ) ) );
  17442. // Section 4.3: Reprojection onto hemisphere
  17443. const Nh = T1.mul( t1 ).add( T2.mul( t2 ) ).add( Vh.mul( sqrt( max$1( 0.0, t1.mul( t1 ).add( t2.mul( t2 ) ).oneMinus() ) ) ) );
  17444. // Section 3.4: Transform back to ellipsoid configuration
  17445. return normalize( vec3( alpha.mul( Nh.x ), alpha.mul( Nh.y ), max$1( 0.0, Nh.z ) ) );
  17446. } );
  17447. // GGX convolution using VNDF importance sampling
  17448. const ggxConvolution = /*@__PURE__*/ Fn( ( { roughness, mipInt, envMap, N_immutable, GGX_SAMPLES, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP } ) => {
  17449. const N = vec3( N_immutable ).toVar();
  17450. const prefilteredColor = vec3( 0.0 ).toVar();
  17451. const totalWeight = float( 0.0 ).toVar();
  17452. // For very low roughness, just sample the environment directly
  17453. If( roughness.lessThan( 0.001 ), () => {
  17454. prefilteredColor.assign( bilinearCubeUV( envMap, N, mipInt, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP ) );
  17455. } ).Else( () => {
  17456. // Tangent space basis for VNDF sampling
  17457. const up = select( abs( N.z ).lessThan( 0.999 ), vec3( 0.0, 0.0, 1.0 ), vec3( 1.0, 0.0, 0.0 ) );
  17458. const tangent = normalize( cross( up, N ) ).toVar();
  17459. const bitangent = cross( N, tangent ).toVar();
  17460. Loop( { start: uint( 0 ), end: GGX_SAMPLES }, ( { i } ) => {
  17461. const Xi = hammersley( i, GGX_SAMPLES );
  17462. // For PMREM, V = N, so in tangent space V is always (0, 0, 1)
  17463. const H_tangent = importanceSampleGGX_VNDF( Xi, vec3( 0.0, 0.0, 1.0 ), roughness );
  17464. // Transform H back to world space
  17465. const H = normalize( tangent.mul( H_tangent.x ).add( bitangent.mul( H_tangent.y ) ).add( N.mul( H_tangent.z ) ) );
  17466. const L = normalize( H.mul( dot( N, H ).mul( 2.0 ) ).sub( N ) );
  17467. const NdotL = max$1( dot( N, L ), 0.0 );
  17468. If( NdotL.greaterThan( 0.0 ), () => {
  17469. // Sample environment at fixed mip level
  17470. // VNDF importance sampling handles the distribution filtering
  17471. const sampleColor = bilinearCubeUV( envMap, L, mipInt, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP );
  17472. // Weight by NdotL for the split-sum approximation
  17473. // VNDF PDF naturally accounts for the visible microfacet distribution
  17474. prefilteredColor.addAssign( sampleColor.mul( NdotL ) );
  17475. totalWeight.addAssign( NdotL );
  17476. } );
  17477. } );
  17478. If( totalWeight.greaterThan( 0.0 ), () => {
  17479. prefilteredColor.assign( prefilteredColor.div( totalWeight ) );
  17480. } );
  17481. } );
  17482. return vec4( prefilteredColor, 1.0 );
  17483. } );
  17484. const LOD_MIN = 4;
  17485. // The standard deviations (radians) associated with the extra mips.
  17486. // Used for scene blur in fromScene() method.
  17487. const EXTRA_LOD_SIGMA = [ 0.125, 0.215, 0.35, 0.446, 0.526, 0.582 ];
  17488. // The maximum length of the blur for loop. Smaller sigmas will use fewer
  17489. // samples and exit early, but not recompile the shader.
  17490. // Used for scene blur in fromScene() method.
  17491. const MAX_SAMPLES = 20;
  17492. // GGX VNDF importance sampling configuration
  17493. const GGX_SAMPLES = 512;
  17494. const _flatCamera = /*@__PURE__*/ new OrthographicCamera( -1, 1, 1, -1, 0, 1 );
  17495. const _cubeCamera = /*@__PURE__*/ new PerspectiveCamera( 90, 1 );
  17496. const _clearColor$2 = /*@__PURE__*/ new Color();
  17497. let _oldTarget = null;
  17498. let _oldActiveCubeFace = 0;
  17499. let _oldActiveMipmapLevel = 0;
  17500. const _origin = /*@__PURE__*/ new Vector3();
  17501. // maps blur materials to their uniforms dictionary
  17502. const _uniformsMap = new WeakMap();
  17503. // WebGPU Face indices
  17504. const _faceLib = [
  17505. 3, 1, 5,
  17506. 0, 4, 2
  17507. ];
  17508. const _direction = /*@__PURE__*/ getDirection( uv$1(), attribute( 'faceIndex' ) ).normalize();
  17509. const _outputDirection = /*@__PURE__*/ vec3( _direction.x, _direction.y, _direction.z );
  17510. /**
  17511. * This class generates a Prefiltered, Mipmapped Radiance Environment Map
  17512. * (PMREM) from a cubeMap environment texture. This allows different levels of
  17513. * blur to be quickly accessed based on material roughness. It is packed into a
  17514. * special CubeUV format that allows us to perform custom interpolation so that
  17515. * we can support nonlinear formats such as RGBE. Unlike a traditional mipmap
  17516. * chain, it only goes down to the LOD_MIN level (above), and then creates extra
  17517. * even more filtered 'mips' at the same LOD_MIN resolution, associated with
  17518. * higher roughness levels. In this way we maintain resolution to smoothly
  17519. * interpolate diffuse lighting while limiting sampling computation.
  17520. *
  17521. * The prefiltering uses GGX VNDF (Visible Normal Distribution Function)
  17522. * importance sampling based on "Sampling the GGX Distribution of Visible Normals"
  17523. * (Heitz, 2018) to generate environment maps that accurately match the GGX BRDF
  17524. * used in material rendering for physically-based image-based lighting.
  17525. */
  17526. class PMREMGenerator {
  17527. /**
  17528. * Constructs a new PMREM generator.
  17529. *
  17530. * @param {Renderer} renderer - The renderer.
  17531. */
  17532. constructor( renderer ) {
  17533. this._renderer = renderer;
  17534. this._pingPongRenderTarget = null;
  17535. this._lodMax = 0;
  17536. this._cubeSize = 0;
  17537. this._sizeLods = [];
  17538. this._sigmas = [];
  17539. this._lodMeshes = [];
  17540. this._blurMaterial = null;
  17541. this._ggxMaterial = null;
  17542. this._cubemapMaterial = null;
  17543. this._equirectMaterial = null;
  17544. this._backgroundBox = null;
  17545. }
  17546. get _hasInitialized() {
  17547. return this._renderer.hasInitialized();
  17548. }
  17549. /**
  17550. * Generates a PMREM from a supplied Scene, which can be faster than using an
  17551. * image if networking bandwidth is low. Optional sigma specifies a blur radius
  17552. * in radians to be applied to the scene before PMREM generation. Optional near
  17553. * and far planes ensure the scene is rendered in its entirety.
  17554. *
  17555. * @param {Scene} scene - The scene to be captured.
  17556. * @param {number} [sigma=0] - The blur radius in radians.
  17557. * @param {number} [near=0.1] - The near plane distance.
  17558. * @param {number} [far=100] - The far plane distance.
  17559. * @param {Object} [options={}] - The configuration options.
  17560. * @param {number} [options.size=256] - The texture size of the PMREM.
  17561. * @param {Vector3} [options.renderTarget=origin] - The position of the internal cube camera that renders the scene.
  17562. * @param {?RenderTarget} [options.renderTarget=null] - The render target to use.
  17563. * @return {RenderTarget} The resulting PMREM.
  17564. * @see {@link PMREMGenerator#fromScene}
  17565. */
  17566. fromScene( scene, sigma = 0, near = 0.1, far = 100, options = {} ) {
  17567. const {
  17568. size = 256,
  17569. position = _origin,
  17570. renderTarget = null,
  17571. } = options;
  17572. this._setSize( size );
  17573. if ( this._hasInitialized === false ) {
  17574. warn( 'PMREMGenerator: ".fromScene()" called before the backend is initialized. Try using "await renderer.init()" instead.' );
  17575. const cubeUVRenderTarget = renderTarget || this._allocateTarget();
  17576. options.renderTarget = cubeUVRenderTarget;
  17577. this.fromSceneAsync( scene, sigma, near, far, options );
  17578. return cubeUVRenderTarget;
  17579. }
  17580. _oldTarget = this._renderer.getRenderTarget();
  17581. _oldActiveCubeFace = this._renderer.getActiveCubeFace();
  17582. _oldActiveMipmapLevel = this._renderer.getActiveMipmapLevel();
  17583. const cubeUVRenderTarget = renderTarget || this._allocateTarget();
  17584. cubeUVRenderTarget.depthBuffer = true;
  17585. this._init( cubeUVRenderTarget );
  17586. this._sceneToCubeUV( scene, near, far, cubeUVRenderTarget, position );
  17587. if ( sigma > 0 ) {
  17588. this._blur( cubeUVRenderTarget, 0, 0, sigma );
  17589. }
  17590. this._applyPMREM( cubeUVRenderTarget );
  17591. this._cleanup( cubeUVRenderTarget );
  17592. return cubeUVRenderTarget;
  17593. }
  17594. /**
  17595. * Generates a PMREM from a supplied Scene, which can be faster than using an
  17596. * image if networking bandwidth is low. Optional sigma specifies a blur radius
  17597. * in radians to be applied to the scene before PMREM generation. Optional near
  17598. * and far planes ensure the scene is rendered in its entirety (the cubeCamera
  17599. * is placed at the origin).
  17600. *
  17601. * @deprecated
  17602. * @param {Scene} scene - The scene to be captured.
  17603. * @param {number} [sigma=0] - The blur radius in radians.
  17604. * @param {number} [near=0.1] - The near plane distance.
  17605. * @param {number} [far=100] - The far plane distance.
  17606. * @param {Object} [options={}] - The configuration options.
  17607. * @param {number} [options.size=256] - The texture size of the PMREM.
  17608. * @param {Vector3} [options.position=origin] - The position of the internal cube camera that renders the scene.
  17609. * @param {?RenderTarget} [options.renderTarget=null] - The render target to use.
  17610. * @return {Promise<RenderTarget>} A Promise that resolve with the PMREM when the generation has been finished.
  17611. * @see {@link PMREMGenerator#fromScene}
  17612. */
  17613. async fromSceneAsync( scene, sigma = 0, near = 0.1, far = 100, options = {} ) {
  17614. warnOnce( 'PMREMGenerator: ".fromSceneAsync()" is deprecated. Use "await renderer.init()" instead.' ); // @deprecated r181
  17615. await this._renderer.init();
  17616. return this.fromScene( scene, sigma, near, far, options );
  17617. }
  17618. /**
  17619. * Generates a PMREM from an equirectangular texture, which can be either LDR
  17620. * or HDR. The ideal input image size is 1k (1024 x 512),
  17621. * as this matches best with the 256 x 256 cubemap output.
  17622. *
  17623. * @param {Texture} equirectangular - The equirectangular texture to be converted.
  17624. * @param {?RenderTarget} [renderTarget=null] - The render target to use.
  17625. * @return {RenderTarget} The resulting PMREM.
  17626. * @see {@link PMREMGenerator#fromEquirectangularAsync}
  17627. */
  17628. fromEquirectangular( equirectangular, renderTarget = null ) {
  17629. if ( this._hasInitialized === false ) {
  17630. warn( 'PMREMGenerator: .fromEquirectangular() called before the backend is initialized. Try using "await renderer.init()" instead.' );
  17631. this._setSizeFromTexture( equirectangular );
  17632. const cubeUVRenderTarget = renderTarget || this._allocateTarget();
  17633. this.fromEquirectangularAsync( equirectangular, cubeUVRenderTarget );
  17634. return cubeUVRenderTarget;
  17635. }
  17636. return this._fromTexture( equirectangular, renderTarget );
  17637. }
  17638. /**
  17639. * Generates a PMREM from an equirectangular texture, which can be either LDR
  17640. * or HDR. The ideal input image size is 1k (1024 x 512),
  17641. * as this matches best with the 256 x 256 cubemap output.
  17642. *
  17643. * @deprecated
  17644. * @param {Texture} equirectangular - The equirectangular texture to be converted.
  17645. * @param {?RenderTarget} [renderTarget=null] - The render target to use.
  17646. * @return {Promise<RenderTarget>} The resulting PMREM.
  17647. * @see {@link PMREMGenerator#fromEquirectangular}
  17648. */
  17649. async fromEquirectangularAsync( equirectangular, renderTarget = null ) {
  17650. warnOnce( 'PMREMGenerator: ".fromEquirectangularAsync()" is deprecated. Use "await renderer.init()" instead.' ); // @deprecated r181
  17651. await this._renderer.init();
  17652. return this._fromTexture( equirectangular, renderTarget );
  17653. }
  17654. /**
  17655. * Generates a PMREM from an cubemap texture, which can be either LDR
  17656. * or HDR. The ideal input cube size is 256 x 256,
  17657. * as this matches best with the 256 x 256 cubemap output.
  17658. *
  17659. * @param {Texture} cubemap - The cubemap texture to be converted.
  17660. * @param {?RenderTarget} [renderTarget=null] - The render target to use.
  17661. * @return {RenderTarget} The resulting PMREM.
  17662. * @see {@link PMREMGenerator#fromCubemapAsync}
  17663. */
  17664. fromCubemap( cubemap, renderTarget = null ) {
  17665. if ( this._hasInitialized === false ) {
  17666. warn( 'PMREMGenerator: .fromCubemap() called before the backend is initialized. Try using .fromCubemapAsync() instead.' );
  17667. this._setSizeFromTexture( cubemap );
  17668. const cubeUVRenderTarget = renderTarget || this._allocateTarget();
  17669. this.fromCubemapAsync( cubemap, renderTarget );
  17670. return cubeUVRenderTarget;
  17671. }
  17672. return this._fromTexture( cubemap, renderTarget );
  17673. }
  17674. /**
  17675. * Generates a PMREM from an cubemap texture, which can be either LDR
  17676. * or HDR. The ideal input cube size is 256 x 256,
  17677. * with the 256 x 256 cubemap output.
  17678. *
  17679. * @deprecated
  17680. * @param {Texture} cubemap - The cubemap texture to be converted.
  17681. * @param {?RenderTarget} [renderTarget=null] - The render target to use.
  17682. * @return {Promise<RenderTarget>} The resulting PMREM.
  17683. * @see {@link PMREMGenerator#fromCubemap}
  17684. */
  17685. async fromCubemapAsync( cubemap, renderTarget = null ) {
  17686. warnOnce( 'PMREMGenerator: ".fromCubemapAsync()" is deprecated. Use "await renderer.init()" instead.' ); // @deprecated r181
  17687. await this._renderer.init();
  17688. return this._fromTexture( cubemap, renderTarget );
  17689. }
  17690. /**
  17691. * Pre-compiles the cubemap shader. You can get faster start-up by invoking this method during
  17692. * your texture's network fetch for increased concurrency.
  17693. *
  17694. * @returns {Promise}
  17695. */
  17696. async compileCubemapShader() {
  17697. if ( this._cubemapMaterial === null ) {
  17698. this._cubemapMaterial = _getCubemapMaterial();
  17699. await this._compileMaterial( this._cubemapMaterial );
  17700. }
  17701. }
  17702. /**
  17703. * Pre-compiles the equirectangular shader. You can get faster start-up by invoking this method during
  17704. * your texture's network fetch for increased concurrency.
  17705. *
  17706. * @returns {Promise}
  17707. */
  17708. async compileEquirectangularShader() {
  17709. if ( this._equirectMaterial === null ) {
  17710. this._equirectMaterial = _getEquirectMaterial();
  17711. await this._compileMaterial( this._equirectMaterial );
  17712. }
  17713. }
  17714. /**
  17715. * Disposes of the PMREMGenerator's internal memory. Note that PMREMGenerator is a static class,
  17716. * so you should not need more than one PMREMGenerator object. If you do, calling dispose() on
  17717. * one of them will cause any others to also become unusable.
  17718. */
  17719. dispose() {
  17720. this._dispose();
  17721. if ( this._cubemapMaterial !== null ) this._cubemapMaterial.dispose();
  17722. if ( this._equirectMaterial !== null ) this._equirectMaterial.dispose();
  17723. if ( this._backgroundBox !== null ) {
  17724. this._backgroundBox.geometry.dispose();
  17725. this._backgroundBox.material.dispose();
  17726. }
  17727. }
  17728. // private interface
  17729. _setSizeFromTexture( texture ) {
  17730. if ( texture.mapping === CubeReflectionMapping || texture.mapping === CubeRefractionMapping ) {
  17731. this._setSize( texture.image.length === 0 ? 16 : ( texture.image[ 0 ].width || texture.image[ 0 ].image.width ) );
  17732. } else { // Equirectangular
  17733. this._setSize( texture.image.width / 4 );
  17734. }
  17735. }
  17736. _setSize( cubeSize ) {
  17737. this._lodMax = Math.floor( Math.log2( cubeSize ) );
  17738. this._cubeSize = Math.pow( 2, this._lodMax );
  17739. }
  17740. _dispose() {
  17741. if ( this._blurMaterial !== null ) this._blurMaterial.dispose();
  17742. if ( this._ggxMaterial !== null ) this._ggxMaterial.dispose();
  17743. if ( this._pingPongRenderTarget !== null ) this._pingPongRenderTarget.dispose();
  17744. for ( let i = 0; i < this._lodMeshes.length; i ++ ) {
  17745. this._lodMeshes[ i ].geometry.dispose();
  17746. }
  17747. }
  17748. _cleanup( outputTarget ) {
  17749. this._renderer.setRenderTarget( _oldTarget, _oldActiveCubeFace, _oldActiveMipmapLevel );
  17750. outputTarget.scissorTest = false;
  17751. _setViewport( outputTarget, 0, 0, outputTarget.width, outputTarget.height );
  17752. }
  17753. _fromTexture( texture, renderTarget ) {
  17754. this._setSizeFromTexture( texture );
  17755. _oldTarget = this._renderer.getRenderTarget();
  17756. _oldActiveCubeFace = this._renderer.getActiveCubeFace();
  17757. _oldActiveMipmapLevel = this._renderer.getActiveMipmapLevel();
  17758. const cubeUVRenderTarget = renderTarget || this._allocateTarget();
  17759. this._init( cubeUVRenderTarget );
  17760. this._textureToCubeUV( texture, cubeUVRenderTarget );
  17761. this._applyPMREM( cubeUVRenderTarget );
  17762. this._cleanup( cubeUVRenderTarget );
  17763. return cubeUVRenderTarget;
  17764. }
  17765. _allocateTarget() {
  17766. const width = 3 * Math.max( this._cubeSize, 16 * 7 );
  17767. const height = 4 * this._cubeSize;
  17768. const cubeUVRenderTarget = _createRenderTarget( width, height );
  17769. return cubeUVRenderTarget;
  17770. }
  17771. _init( renderTarget ) {
  17772. if ( this._pingPongRenderTarget === null || this._pingPongRenderTarget.width !== renderTarget.width || this._pingPongRenderTarget.height !== renderTarget.height ) {
  17773. if ( this._pingPongRenderTarget !== null ) {
  17774. this._dispose();
  17775. }
  17776. this._pingPongRenderTarget = _createRenderTarget( renderTarget.width, renderTarget.height );
  17777. const { _lodMax } = this;
  17778. ( { lodMeshes: this._lodMeshes, sizeLods: this._sizeLods, sigmas: this._sigmas } = _createPlanes( _lodMax ) );
  17779. this._blurMaterial = _getBlurShader( _lodMax, renderTarget.width, renderTarget.height );
  17780. }
  17781. }
  17782. async _compileMaterial( material ) {
  17783. const mesh = new Mesh( new BufferGeometry(), material );
  17784. await this._renderer.compile( mesh, _flatCamera );
  17785. }
  17786. _sceneToCubeUV( scene, near, far, cubeUVRenderTarget, position ) {
  17787. const cubeCamera = _cubeCamera;
  17788. cubeCamera.near = near;
  17789. cubeCamera.far = far;
  17790. // px, py, pz, nx, ny, nz
  17791. const upSign = [ 1, 1, 1, 1, -1, 1 ];
  17792. const forwardSign = [ 1, -1, 1, -1, 1, -1 ];
  17793. const renderer = this._renderer;
  17794. const originalAutoClear = renderer.autoClear;
  17795. renderer.getClearColor( _clearColor$2 );
  17796. renderer.autoClear = false;
  17797. if ( this._backgroundBox === null ) {
  17798. this._backgroundBox = new Mesh(
  17799. new BoxGeometry(),
  17800. new MeshBasicMaterial( {
  17801. name: 'PMREM.Background',
  17802. side: BackSide,
  17803. depthWrite: false,
  17804. depthTest: false,
  17805. } )
  17806. );
  17807. }
  17808. const backgroundBox = this._backgroundBox;
  17809. const backgroundMaterial = backgroundBox.material;
  17810. let useSolidColor = false;
  17811. const background = scene.background;
  17812. if ( background ) {
  17813. if ( background.isColor ) {
  17814. backgroundMaterial.color.copy( background );
  17815. scene.background = null;
  17816. useSolidColor = true;
  17817. }
  17818. } else {
  17819. backgroundMaterial.color.copy( _clearColor$2 );
  17820. useSolidColor = true;
  17821. }
  17822. renderer.setRenderTarget( cubeUVRenderTarget );
  17823. renderer.clear();
  17824. if ( useSolidColor ) {
  17825. renderer.render( backgroundBox, cubeCamera );
  17826. }
  17827. for ( let i = 0; i < 6; i ++ ) {
  17828. const col = i % 3;
  17829. if ( col === 0 ) {
  17830. cubeCamera.up.set( 0, upSign[ i ], 0 );
  17831. cubeCamera.position.set( position.x, position.y, position.z );
  17832. cubeCamera.lookAt( position.x + forwardSign[ i ], position.y, position.z );
  17833. } else if ( col === 1 ) {
  17834. cubeCamera.up.set( 0, 0, upSign[ i ] );
  17835. cubeCamera.position.set( position.x, position.y, position.z );
  17836. cubeCamera.lookAt( position.x, position.y + forwardSign[ i ], position.z );
  17837. } else {
  17838. cubeCamera.up.set( 0, upSign[ i ], 0 );
  17839. cubeCamera.position.set( position.x, position.y, position.z );
  17840. cubeCamera.lookAt( position.x, position.y, position.z + forwardSign[ i ] );
  17841. }
  17842. const size = this._cubeSize;
  17843. _setViewport( cubeUVRenderTarget, col * size, i > 2 ? size : 0, size, size );
  17844. renderer.render( scene, cubeCamera );
  17845. }
  17846. renderer.autoClear = originalAutoClear;
  17847. scene.background = background;
  17848. }
  17849. _textureToCubeUV( texture, cubeUVRenderTarget ) {
  17850. const renderer = this._renderer;
  17851. const isCubeTexture = ( texture.mapping === CubeReflectionMapping || texture.mapping === CubeRefractionMapping );
  17852. if ( isCubeTexture ) {
  17853. if ( this._cubemapMaterial === null ) {
  17854. this._cubemapMaterial = _getCubemapMaterial( texture );
  17855. }
  17856. } else {
  17857. if ( this._equirectMaterial === null ) {
  17858. this._equirectMaterial = _getEquirectMaterial( texture );
  17859. }
  17860. }
  17861. const material = isCubeTexture ? this._cubemapMaterial : this._equirectMaterial;
  17862. material.fragmentNode.value = texture;
  17863. const mesh = this._lodMeshes[ 0 ];
  17864. mesh.material = material;
  17865. const size = this._cubeSize;
  17866. _setViewport( cubeUVRenderTarget, 0, 0, 3 * size, 2 * size );
  17867. renderer.setRenderTarget( cubeUVRenderTarget );
  17868. renderer.render( mesh, _flatCamera );
  17869. }
  17870. _applyPMREM( cubeUVRenderTarget ) {
  17871. const renderer = this._renderer;
  17872. const autoClear = renderer.autoClear;
  17873. renderer.autoClear = false;
  17874. const n = this._lodMeshes.length;
  17875. // Use GGX VNDF importance sampling
  17876. for ( let i = 1; i < n; i ++ ) {
  17877. this._applyGGXFilter( cubeUVRenderTarget, i - 1, i );
  17878. }
  17879. renderer.autoClear = autoClear;
  17880. }
  17881. /**
  17882. * Applies GGX VNDF importance sampling filter to generate a prefiltered environment map.
  17883. * Uses Monte Carlo integration with VNDF importance sampling to accurately represent the
  17884. * GGX BRDF for physically-based rendering. Reads from the previous LOD level and
  17885. * applies incremental roughness filtering to avoid over-blurring.
  17886. *
  17887. * @private
  17888. * @param {RenderTarget} cubeUVRenderTarget
  17889. * @param {number} lodIn - Source LOD level to read from
  17890. * @param {number} lodOut - Target LOD level to write to
  17891. */
  17892. _applyGGXFilter( cubeUVRenderTarget, lodIn, lodOut ) {
  17893. const renderer = this._renderer;
  17894. const pingPongRenderTarget = this._pingPongRenderTarget;
  17895. // Lazy create GGX material only when first used
  17896. if ( this._ggxMaterial === null ) {
  17897. this._ggxMaterial = _getGGXShader( this._lodMax, this._pingPongRenderTarget.width, this._pingPongRenderTarget.height );
  17898. }
  17899. const ggxMaterial = this._ggxMaterial;
  17900. const ggxMesh = this._lodMeshes[ lodOut ];
  17901. ggxMesh.material = ggxMaterial;
  17902. const ggxUniforms = _uniformsMap.get( ggxMaterial );
  17903. // Calculate incremental roughness between LOD levels
  17904. const targetRoughness = lodOut / ( this._lodMeshes.length - 1 );
  17905. const sourceRoughness = lodIn / ( this._lodMeshes.length - 1 );
  17906. const incrementalRoughness = Math.sqrt( targetRoughness * targetRoughness - sourceRoughness * sourceRoughness );
  17907. // Apply blur strength mapping for better quality across the roughness range
  17908. const blurStrength = 0.05 + targetRoughness * 0.95;
  17909. const adjustedRoughness = incrementalRoughness * blurStrength;
  17910. // Calculate viewport position based on output LOD level
  17911. const { _lodMax } = this;
  17912. const outputSize = this._sizeLods[ lodOut ];
  17913. const x = 3 * outputSize * ( lodOut > _lodMax - LOD_MIN ? lodOut - _lodMax + LOD_MIN : 0 );
  17914. const y = 4 * ( this._cubeSize - outputSize );
  17915. // Read from previous LOD with incremental roughness
  17916. cubeUVRenderTarget.texture.frame = ( cubeUVRenderTarget.texture.frame || 0 ) + 1;
  17917. ggxUniforms.envMap.value = cubeUVRenderTarget.texture;
  17918. ggxUniforms.roughness.value = adjustedRoughness;
  17919. ggxUniforms.mipInt.value = _lodMax - lodIn; // Sample from input LOD
  17920. _setViewport( pingPongRenderTarget, x, y, 3 * outputSize, 2 * outputSize );
  17921. renderer.setRenderTarget( pingPongRenderTarget );
  17922. renderer.render( ggxMesh, _flatCamera );
  17923. // Copy from pingPong back to cubeUV (simple direct copy)
  17924. pingPongRenderTarget.texture.frame = ( pingPongRenderTarget.texture.frame || 0 ) + 1;
  17925. ggxUniforms.envMap.value = pingPongRenderTarget.texture;
  17926. ggxUniforms.roughness.value = 0.0; // Direct copy
  17927. ggxUniforms.mipInt.value = _lodMax - lodOut; // Read from the level we just wrote
  17928. _setViewport( cubeUVRenderTarget, x, y, 3 * outputSize, 2 * outputSize );
  17929. renderer.setRenderTarget( cubeUVRenderTarget );
  17930. renderer.render( ggxMesh, _flatCamera );
  17931. }
  17932. /**
  17933. * This is a two-pass Gaussian blur for a cubemap. Normally this is done
  17934. * vertically and horizontally, but this breaks down on a cube. Here we apply
  17935. * the blur latitudinally (around the poles), and then longitudinally (towards
  17936. * the poles) to approximate the orthogonally-separable blur. It is least
  17937. * accurate at the poles, but still does a decent job.
  17938. *
  17939. * Used for initial scene blur in fromScene() method when sigma > 0.
  17940. *
  17941. * @private
  17942. * @param {RenderTarget} cubeUVRenderTarget - The cubemap render target.
  17943. * @param {number} lodIn - The input level-of-detail.
  17944. * @param {number} lodOut - The output level-of-detail.
  17945. * @param {number} sigma - The blur radius in radians.
  17946. * @param {Vector3} [poleAxis] - The pole axis.
  17947. */
  17948. _blur( cubeUVRenderTarget, lodIn, lodOut, sigma, poleAxis ) {
  17949. const pingPongRenderTarget = this._pingPongRenderTarget;
  17950. this._halfBlur(
  17951. cubeUVRenderTarget,
  17952. pingPongRenderTarget,
  17953. lodIn,
  17954. lodOut,
  17955. sigma,
  17956. 'latitudinal',
  17957. poleAxis );
  17958. this._halfBlur(
  17959. pingPongRenderTarget,
  17960. cubeUVRenderTarget,
  17961. lodOut,
  17962. lodOut,
  17963. sigma,
  17964. 'longitudinal',
  17965. poleAxis );
  17966. }
  17967. _halfBlur( targetIn, targetOut, lodIn, lodOut, sigmaRadians, direction, poleAxis ) {
  17968. const renderer = this._renderer;
  17969. const blurMaterial = this._blurMaterial;
  17970. if ( direction !== 'latitudinal' && direction !== 'longitudinal' ) {
  17971. error( 'blur direction must be either latitudinal or longitudinal!' );
  17972. }
  17973. // Number of standard deviations at which to cut off the discrete approximation.
  17974. const STANDARD_DEVIATIONS = 3;
  17975. const blurMesh = this._lodMeshes[ lodOut ];
  17976. blurMesh.material = blurMaterial;
  17977. const blurUniforms = _uniformsMap.get( blurMaterial );
  17978. const pixels = this._sizeLods[ lodIn ] - 1;
  17979. const radiansPerPixel = isFinite( sigmaRadians ) ? Math.PI / ( 2 * pixels ) : 2 * Math.PI / ( 2 * MAX_SAMPLES - 1 );
  17980. const sigmaPixels = sigmaRadians / radiansPerPixel;
  17981. const samples = isFinite( sigmaRadians ) ? 1 + Math.floor( STANDARD_DEVIATIONS * sigmaPixels ) : MAX_SAMPLES;
  17982. if ( samples > MAX_SAMPLES ) {
  17983. warn( `sigmaRadians, ${
  17984. sigmaRadians}, is too large and will clip, as it requested ${
  17985. samples} samples when the maximum is set to ${MAX_SAMPLES}` );
  17986. }
  17987. const weights = [];
  17988. let sum = 0;
  17989. for ( let i = 0; i < MAX_SAMPLES; ++ i ) {
  17990. const x = i / sigmaPixels;
  17991. const weight = Math.exp( - x * x / 2 );
  17992. weights.push( weight );
  17993. if ( i === 0 ) {
  17994. sum += weight;
  17995. } else if ( i < samples ) {
  17996. sum += 2 * weight;
  17997. }
  17998. }
  17999. for ( let i = 0; i < weights.length; i ++ ) {
  18000. weights[ i ] = weights[ i ] / sum;
  18001. }
  18002. targetIn.texture.frame = ( targetIn.texture.frame || 0 ) + 1;
  18003. blurUniforms.envMap.value = targetIn.texture;
  18004. blurUniforms.samples.value = samples;
  18005. blurUniforms.weights.array = weights;
  18006. blurUniforms.latitudinal.value = direction === 'latitudinal' ? 1 : 0;
  18007. if ( poleAxis ) {
  18008. blurUniforms.poleAxis.value = poleAxis;
  18009. }
  18010. const { _lodMax } = this;
  18011. blurUniforms.dTheta.value = radiansPerPixel;
  18012. blurUniforms.mipInt.value = _lodMax - lodIn;
  18013. const outputSize = this._sizeLods[ lodOut ];
  18014. const x = 3 * outputSize * ( lodOut > _lodMax - LOD_MIN ? lodOut - _lodMax + LOD_MIN : 0 );
  18015. const y = 4 * ( this._cubeSize - outputSize );
  18016. _setViewport( targetOut, x, y, 3 * outputSize, 2 * outputSize );
  18017. renderer.setRenderTarget( targetOut );
  18018. renderer.render( blurMesh, _flatCamera );
  18019. }
  18020. }
  18021. function _createPlanes( lodMax ) {
  18022. const sizeLods = [];
  18023. const sigmas = [];
  18024. const lodMeshes = [];
  18025. let lod = lodMax;
  18026. const totalLods = lodMax - LOD_MIN + 1 + EXTRA_LOD_SIGMA.length;
  18027. for ( let i = 0; i < totalLods; i ++ ) {
  18028. const sizeLod = Math.pow( 2, lod );
  18029. sizeLods.push( sizeLod );
  18030. let sigma = 1.0 / sizeLod;
  18031. if ( i > lodMax - LOD_MIN ) {
  18032. sigma = EXTRA_LOD_SIGMA[ i - lodMax + LOD_MIN - 1 ];
  18033. } else if ( i === 0 ) {
  18034. sigma = 0;
  18035. }
  18036. sigmas.push( sigma );
  18037. const texelSize = 1.0 / ( sizeLod - 2 );
  18038. const min = - texelSize;
  18039. const max = 1 + texelSize;
  18040. const uv1 = [ min, min, max, min, max, max, min, min, max, max, min, max ];
  18041. const cubeFaces = 6;
  18042. const vertices = 6;
  18043. const positionSize = 3;
  18044. const uvSize = 2;
  18045. const faceIndexSize = 1;
  18046. const position = new Float32Array( positionSize * vertices * cubeFaces );
  18047. const uv = new Float32Array( uvSize * vertices * cubeFaces );
  18048. const faceIndex = new Float32Array( faceIndexSize * vertices * cubeFaces );
  18049. for ( let face = 0; face < cubeFaces; face ++ ) {
  18050. const x = ( face % 3 ) * 2 / 3 - 1;
  18051. const y = face > 2 ? 0 : -1;
  18052. const coordinates = [
  18053. x, y, 0,
  18054. x + 2 / 3, y, 0,
  18055. x + 2 / 3, y + 1, 0,
  18056. x, y, 0,
  18057. x + 2 / 3, y + 1, 0,
  18058. x, y + 1, 0
  18059. ];
  18060. const faceIdx = _faceLib[ face ];
  18061. position.set( coordinates, positionSize * vertices * faceIdx );
  18062. uv.set( uv1, uvSize * vertices * faceIdx );
  18063. const fill = [ faceIdx, faceIdx, faceIdx, faceIdx, faceIdx, faceIdx ];
  18064. faceIndex.set( fill, faceIndexSize * vertices * faceIdx );
  18065. }
  18066. const planes = new BufferGeometry();
  18067. planes.setAttribute( 'position', new BufferAttribute( position, positionSize ) );
  18068. planes.setAttribute( 'uv', new BufferAttribute( uv, uvSize ) );
  18069. planes.setAttribute( 'faceIndex', new BufferAttribute( faceIndex, faceIndexSize ) );
  18070. lodMeshes.push( new Mesh( planes, null ) );
  18071. if ( lod > LOD_MIN ) {
  18072. lod --;
  18073. }
  18074. }
  18075. return { lodMeshes, sizeLods, sigmas };
  18076. }
  18077. function _createRenderTarget( width, height ) {
  18078. const params = {
  18079. magFilter: LinearFilter,
  18080. minFilter: LinearFilter,
  18081. generateMipmaps: false,
  18082. type: HalfFloatType,
  18083. format: RGBAFormat,
  18084. colorSpace: LinearSRGBColorSpace,
  18085. //depthBuffer: false
  18086. };
  18087. const cubeUVRenderTarget = new RenderTarget( width, height, params );
  18088. cubeUVRenderTarget.texture.mapping = CubeUVReflectionMapping;
  18089. cubeUVRenderTarget.texture.name = 'PMREM.cubeUv';
  18090. cubeUVRenderTarget.texture.isPMREMTexture = true;
  18091. cubeUVRenderTarget.scissorTest = true;
  18092. return cubeUVRenderTarget;
  18093. }
  18094. function _setViewport( target, x, y, width, height ) {
  18095. target.viewport.set( x, y, width, height );
  18096. target.scissor.set( x, y, width, height );
  18097. }
  18098. function _getMaterial( type ) {
  18099. const material = new NodeMaterial();
  18100. material.depthTest = false;
  18101. material.depthWrite = false;
  18102. material.blending = NoBlending;
  18103. material.name = `PMREM_${ type }`;
  18104. return material;
  18105. }
  18106. function _getBlurShader( lodMax, width, height ) {
  18107. const weights = uniformArray( new Array( MAX_SAMPLES ).fill( 0 ) );
  18108. const poleAxis = uniform( new Vector3( 0, 1, 0 ) );
  18109. const dTheta = uniform( 0 );
  18110. const n = float( MAX_SAMPLES );
  18111. const latitudinal = uniform( 0 ); // false, bool
  18112. const samples = uniform( 1 ); // int
  18113. const envMap = texture();
  18114. const mipInt = uniform( 0 ); // int
  18115. const CUBEUV_TEXEL_WIDTH = float( 1 / width );
  18116. const CUBEUV_TEXEL_HEIGHT = float( 1 / height );
  18117. const CUBEUV_MAX_MIP = float( lodMax );
  18118. const materialUniforms = {
  18119. n,
  18120. latitudinal,
  18121. weights,
  18122. poleAxis,
  18123. outputDirection: _outputDirection,
  18124. dTheta,
  18125. samples,
  18126. envMap,
  18127. mipInt,
  18128. CUBEUV_TEXEL_WIDTH,
  18129. CUBEUV_TEXEL_HEIGHT,
  18130. CUBEUV_MAX_MIP
  18131. };
  18132. const material = _getMaterial( 'blur' );
  18133. material.fragmentNode = blur( { ...materialUniforms, latitudinal: latitudinal.equal( 1 ) } );
  18134. _uniformsMap.set( material, materialUniforms );
  18135. return material;
  18136. }
  18137. function _getGGXShader( lodMax, width, height ) {
  18138. const envMap = texture();
  18139. const roughness = uniform( 0 );
  18140. const mipInt = uniform( 0 );
  18141. const CUBEUV_TEXEL_WIDTH = float( 1 / width );
  18142. const CUBEUV_TEXEL_HEIGHT = float( 1 / height );
  18143. const CUBEUV_MAX_MIP = float( lodMax );
  18144. const materialUniforms = {
  18145. envMap,
  18146. roughness,
  18147. mipInt,
  18148. CUBEUV_TEXEL_WIDTH,
  18149. CUBEUV_TEXEL_HEIGHT,
  18150. CUBEUV_MAX_MIP
  18151. };
  18152. const material = _getMaterial( 'ggx' );
  18153. material.fragmentNode = ggxConvolution( {
  18154. ...materialUniforms,
  18155. N_immutable: _outputDirection,
  18156. GGX_SAMPLES: uint( GGX_SAMPLES )
  18157. } );
  18158. _uniformsMap.set( material, materialUniforms );
  18159. return material;
  18160. }
  18161. function _getCubemapMaterial( envTexture ) {
  18162. const material = _getMaterial( 'cubemap' );
  18163. material.fragmentNode = cubeTexture( envTexture, _outputDirection );
  18164. return material;
  18165. }
  18166. function _getEquirectMaterial( envTexture ) {
  18167. const material = _getMaterial( 'equirect' );
  18168. material.fragmentNode = texture( envTexture, equirectUV( _outputDirection ), 0 );
  18169. return material;
  18170. }
  18171. const _cache = new WeakMap();
  18172. /**
  18173. * Generates the cubeUV size based on the given image height.
  18174. *
  18175. * @private
  18176. * @param {number} imageHeight - The image height.
  18177. * @return {{texelWidth: number,texelHeight: number, maxMip: number}} The result object.
  18178. */
  18179. function _generateCubeUVSize( imageHeight ) {
  18180. const maxMip = Math.log2( imageHeight ) - 2;
  18181. const texelHeight = 1.0 / imageHeight;
  18182. const texelWidth = 1.0 / ( 3 * Math.max( Math.pow( 2, maxMip ), 7 * 16 ) );
  18183. return { texelWidth, texelHeight, maxMip };
  18184. }
  18185. /**
  18186. * Generates a PMREM from the given texture.
  18187. *
  18188. * @private
  18189. * @param {Texture} texture - The texture to create the PMREM for.
  18190. * @param {Renderer} renderer - The renderer.
  18191. * @param {PMREMGenerator} generator - The PMREM generator.
  18192. * @return {?Texture} The PMREM.
  18193. */
  18194. function _getPMREMFromTexture( texture, renderer, generator ) {
  18195. const cache = _getCache( renderer );
  18196. let cacheTexture = cache.get( texture );
  18197. const pmremVersion = cacheTexture !== undefined ? cacheTexture.pmremVersion : -1;
  18198. if ( pmremVersion !== texture.pmremVersion ) {
  18199. const image = texture.image;
  18200. if ( texture.isCubeTexture ) {
  18201. if ( isCubeMapReady( image ) ) {
  18202. cacheTexture = generator.fromCubemap( texture, cacheTexture );
  18203. } else {
  18204. return null;
  18205. }
  18206. } else {
  18207. if ( isEquirectangularMapReady( image ) ) {
  18208. cacheTexture = generator.fromEquirectangular( texture, cacheTexture );
  18209. } else {
  18210. return null;
  18211. }
  18212. }
  18213. cacheTexture.pmremVersion = texture.pmremVersion;
  18214. cache.set( texture, cacheTexture );
  18215. }
  18216. return cacheTexture.texture;
  18217. }
  18218. /**
  18219. * Returns a cache that stores generated PMREMs for the respective textures.
  18220. * A cache must be maintained per renderer since PMREMs are render target textures
  18221. * which can't be shared across render contexts.
  18222. *
  18223. * @private
  18224. * @param {Renderer} renderer - The renderer.
  18225. * @return {WeakMap<Texture, Texture>} The PMREM cache.
  18226. */
  18227. function _getCache( renderer ) {
  18228. let rendererCache = _cache.get( renderer );
  18229. if ( rendererCache === undefined ) {
  18230. rendererCache = new WeakMap();
  18231. _cache.set( renderer, rendererCache );
  18232. }
  18233. return rendererCache;
  18234. }
  18235. /**
  18236. * This node represents a PMREM which is a special type of preprocessed
  18237. * environment map intended for PBR materials.
  18238. *
  18239. * ```js
  18240. * const material = new MeshStandardNodeMaterial();
  18241. * material.envNode = pmremTexture( envMap );
  18242. * ```
  18243. *
  18244. * @augments TempNode
  18245. */
  18246. class PMREMNode extends TempNode {
  18247. static get type() {
  18248. return 'PMREMNode';
  18249. }
  18250. /**
  18251. * Constructs a new function overloading node.
  18252. *
  18253. * @param {Texture} value - The input texture.
  18254. * @param {Node<vec2>} [uvNode=null] - The uv node.
  18255. * @param {Node<float>} [levelNode=null] - The level node.
  18256. */
  18257. constructor( value, uvNode = null, levelNode = null ) {
  18258. super( 'vec3' );
  18259. /**
  18260. * Reference to the input texture.
  18261. *
  18262. * @private
  18263. * @type {Texture}
  18264. */
  18265. this._value = value;
  18266. /**
  18267. * Reference to the generated PMREM.
  18268. *
  18269. * @private
  18270. * @type {Texture | null}
  18271. * @default null
  18272. */
  18273. this._pmrem = null;
  18274. /**
  18275. * The uv node.
  18276. *
  18277. * @type {Node<vec2>}
  18278. */
  18279. this.uvNode = uvNode;
  18280. /**
  18281. * The level node.
  18282. *
  18283. * @type {Node<float>}
  18284. */
  18285. this.levelNode = levelNode;
  18286. /**
  18287. * Reference to a PMREM generator.
  18288. *
  18289. * @private
  18290. * @type {?PMREMGenerator}
  18291. * @default null
  18292. */
  18293. this._generator = null;
  18294. const defaultTexture = new Texture();
  18295. defaultTexture.isRenderTargetTexture = true;
  18296. /**
  18297. * The texture node holding the generated PMREM.
  18298. *
  18299. * @private
  18300. * @type {TextureNode}
  18301. */
  18302. this._texture = texture( defaultTexture );
  18303. /**
  18304. * A uniform representing the PMREM's width.
  18305. *
  18306. * @private
  18307. * @type {UniformNode<float>}
  18308. */
  18309. this._width = uniform( 0 );
  18310. /**
  18311. * A uniform representing the PMREM's height.
  18312. *
  18313. * @private
  18314. * @type {UniformNode<float>}
  18315. */
  18316. this._height = uniform( 0 );
  18317. /**
  18318. * A uniform representing the PMREM's max Mip.
  18319. *
  18320. * @private
  18321. * @type {UniformNode<float>}
  18322. */
  18323. this._maxMip = uniform( 0 );
  18324. /**
  18325. * The `updateBeforeType` is set to `NodeUpdateType.RENDER`.
  18326. *
  18327. * @type {string}
  18328. * @default 'render'
  18329. */
  18330. this.updateBeforeType = NodeUpdateType.RENDER;
  18331. }
  18332. set value( value ) {
  18333. this._value = value;
  18334. this._pmrem = null;
  18335. }
  18336. /**
  18337. * The node's texture value.
  18338. *
  18339. * @type {Texture}
  18340. */
  18341. get value() {
  18342. return this._value;
  18343. }
  18344. /**
  18345. * Uses the given PMREM texture to update internal values.
  18346. *
  18347. * @param {Texture} texture - The PMREM texture.
  18348. */
  18349. updateFromTexture( texture ) {
  18350. const cubeUVSize = _generateCubeUVSize( texture.image.height );
  18351. this._texture.value = texture;
  18352. this._width.value = cubeUVSize.texelWidth;
  18353. this._height.value = cubeUVSize.texelHeight;
  18354. this._maxMip.value = cubeUVSize.maxMip;
  18355. }
  18356. updateBefore( frame ) {
  18357. let pmrem = this._pmrem;
  18358. const pmremVersion = pmrem ? pmrem.pmremVersion : -1;
  18359. const texture = this._value;
  18360. if ( pmremVersion !== texture.pmremVersion ) {
  18361. if ( texture.isPMREMTexture === true ) {
  18362. pmrem = texture;
  18363. } else {
  18364. pmrem = _getPMREMFromTexture( texture, frame.renderer, this._generator );
  18365. }
  18366. if ( pmrem !== null ) {
  18367. this._pmrem = pmrem;
  18368. this.updateFromTexture( pmrem );
  18369. }
  18370. }
  18371. }
  18372. setup( builder ) {
  18373. if ( this._generator === null ) {
  18374. this._generator = new PMREMGenerator( builder.renderer );
  18375. }
  18376. this.updateBefore( builder );
  18377. //
  18378. let uvNode = this.uvNode;
  18379. if ( uvNode === null && builder.context.getUV ) {
  18380. uvNode = builder.context.getUV( this );
  18381. }
  18382. //
  18383. uvNode = materialEnvRotation.mul( vec3( uvNode.x, uvNode.y.negate(), uvNode.z ) );
  18384. //
  18385. let levelNode = this.levelNode;
  18386. if ( levelNode === null && builder.context.getTextureLevel ) {
  18387. levelNode = builder.context.getTextureLevel( this );
  18388. }
  18389. //
  18390. return textureCubeUV( this._texture, uvNode, levelNode, this._width, this._height, this._maxMip );
  18391. }
  18392. dispose() {
  18393. super.dispose();
  18394. if ( this._generator !== null ) this._generator.dispose();
  18395. }
  18396. }
  18397. /**
  18398. * Returns `true` if the given cube map image has been fully loaded.
  18399. *
  18400. * @private
  18401. * @param {?Array<(Image|Object)>} [image] - The cube map image.
  18402. * @return {boolean} Whether the given cube map is ready or not.
  18403. */
  18404. function isCubeMapReady( image ) {
  18405. if ( image === null || image === undefined ) return false;
  18406. let count = 0;
  18407. const length = 6;
  18408. for ( let i = 0; i < length; i ++ ) {
  18409. if ( image[ i ] !== undefined ) count ++;
  18410. }
  18411. return count === length;
  18412. }
  18413. /**
  18414. * Returns `true` if the given equirectangular image has been fully loaded.
  18415. *
  18416. * @private
  18417. * @param {(Image|Object)} image - The equirectangular image.
  18418. * @return {boolean} Whether the given cube map is ready or not.
  18419. */
  18420. function isEquirectangularMapReady( image ) {
  18421. if ( image === null || image === undefined ) return false;
  18422. return image.height > 0;
  18423. }
  18424. /**
  18425. * TSL function for creating a PMREM node.
  18426. *
  18427. * @tsl
  18428. * @function
  18429. * @param {Texture} value - The input texture.
  18430. * @param {?Node<vec2>} [uvNode=null] - The uv node.
  18431. * @param {?Node<float>} [levelNode=null] - The level node.
  18432. * @returns {PMREMNode}
  18433. */
  18434. const pmremTexture = /*@__PURE__*/ nodeProxy( PMREMNode ).setParameterLength( 1, 3 );
  18435. const _envNodeCache = new WeakMap();
  18436. /**
  18437. * Represents a physical model for Image-based lighting (IBL). The environment
  18438. * is defined via environment maps in the equirectangular, cube map or cubeUV (PMREM) format.
  18439. * `EnvironmentNode` is intended for PBR materials like {@link MeshStandardNodeMaterial}.
  18440. *
  18441. * @augments LightingNode
  18442. */
  18443. class EnvironmentNode extends LightingNode {
  18444. static get type() {
  18445. return 'EnvironmentNode';
  18446. }
  18447. /**
  18448. * Constructs a new environment node.
  18449. *
  18450. * @param {Node} [envNode=null] - A node representing the environment.
  18451. */
  18452. constructor( envNode = null ) {
  18453. super();
  18454. /**
  18455. * A node representing the environment.
  18456. *
  18457. * @type {?Node}
  18458. * @default null
  18459. */
  18460. this.envNode = envNode;
  18461. }
  18462. setup( builder ) {
  18463. const { material } = builder;
  18464. let envNode = this.envNode;
  18465. if ( envNode.isTextureNode || envNode.isMaterialReferenceNode ) {
  18466. const value = ( envNode.isTextureNode ) ? envNode.value : material[ envNode.property ];
  18467. let cacheEnvNode = _envNodeCache.get( value );
  18468. if ( cacheEnvNode === undefined ) {
  18469. cacheEnvNode = pmremTexture( value );
  18470. _envNodeCache.set( value, cacheEnvNode );
  18471. }
  18472. envNode = cacheEnvNode;
  18473. }
  18474. //
  18475. const useAnisotropy = material.useAnisotropy === true || material.anisotropy > 0;
  18476. const radianceNormalView = useAnisotropy ? bentNormalView : normalView;
  18477. const radiance = envNode.context( createRadianceContext( roughness, radianceNormalView ) ).mul( materialEnvIntensity );
  18478. const irradiance = envNode.context( createIrradianceContext( normalWorld ) ).mul( Math.PI ).mul( materialEnvIntensity );
  18479. const isolateRadiance = isolate( radiance );
  18480. const isolateIrradiance = isolate( irradiance );
  18481. //
  18482. builder.context.radiance.addAssign( isolateRadiance );
  18483. builder.context.iblIrradiance.addAssign( isolateIrradiance );
  18484. //
  18485. const clearcoatRadiance = builder.context.lightingModel.clearcoatRadiance;
  18486. if ( clearcoatRadiance ) {
  18487. const clearcoatRadianceContext = envNode.context( createRadianceContext( clearcoatRoughness, clearcoatNormalView ) ).mul( materialEnvIntensity );
  18488. const isolateClearcoatRadiance = isolate( clearcoatRadianceContext );
  18489. clearcoatRadiance.addAssign( isolateClearcoatRadiance );
  18490. }
  18491. }
  18492. }
  18493. const createRadianceContext = ( roughnessNode, normalViewNode ) => {
  18494. let reflectVec = null;
  18495. return {
  18496. getUV: () => {
  18497. if ( reflectVec === null ) {
  18498. reflectVec = positionViewDirection.negate().reflect( normalViewNode );
  18499. // Mixing the reflection with the normal is more accurate and keeps rough objects from gathering light from behind their tangent plane.
  18500. reflectVec = pow4( roughnessNode ).mix( reflectVec, normalViewNode ).normalize();
  18501. reflectVec = reflectVec.transformDirection( cameraViewMatrix );
  18502. }
  18503. return reflectVec;
  18504. },
  18505. getTextureLevel: () => {
  18506. return roughnessNode;
  18507. }
  18508. };
  18509. };
  18510. const createIrradianceContext = ( normalWorldNode ) => {
  18511. return {
  18512. getUV: () => {
  18513. return normalWorldNode;
  18514. },
  18515. getTextureLevel: () => {
  18516. return float( 1.0 );
  18517. }
  18518. };
  18519. };
  18520. const _defaultValues$6 = /*@__PURE__*/ new MeshStandardMaterial();
  18521. /**
  18522. * Node material version of {@link MeshStandardMaterial}.
  18523. *
  18524. * @augments NodeMaterial
  18525. */
  18526. class MeshStandardNodeMaterial extends NodeMaterial {
  18527. static get type() {
  18528. return 'MeshStandardNodeMaterial';
  18529. }
  18530. /**
  18531. * Constructs a new mesh standard node material.
  18532. *
  18533. * @param {Object} [parameters] - The configuration parameter.
  18534. */
  18535. constructor( parameters ) {
  18536. super();
  18537. /**
  18538. * This flag can be used for type testing.
  18539. *
  18540. * @type {boolean}
  18541. * @readonly
  18542. * @default true
  18543. */
  18544. this.isMeshStandardNodeMaterial = true;
  18545. /**
  18546. * Set to `true` because standard materials react on lights.
  18547. *
  18548. * @type {boolean}
  18549. * @default true
  18550. */
  18551. this.lights = true;
  18552. /**
  18553. * The emissive color of standard materials is by default inferred from the `emissive`,
  18554. * `emissiveIntensity` and `emissiveMap` properties. This node property allows to
  18555. * overwrite the default and define the emissive color with a node instead.
  18556. *
  18557. * If you don't want to overwrite the emissive color but modify the existing
  18558. * value instead, use {@link materialEmissive}.
  18559. *
  18560. * @type {?Node<vec3>}
  18561. * @default null
  18562. */
  18563. this.emissiveNode = null;
  18564. /**
  18565. * The metalness of standard materials is by default inferred from the `metalness`,
  18566. * and `metalnessMap` properties. This node property allows to
  18567. * overwrite the default and define the metalness with a node instead.
  18568. *
  18569. * If you don't want to overwrite the metalness but modify the existing
  18570. * value instead, use {@link materialMetalness}.
  18571. *
  18572. * @type {?Node<float>}
  18573. * @default null
  18574. */
  18575. this.metalnessNode = null;
  18576. /**
  18577. * The roughness of standard materials is by default inferred from the `roughness`,
  18578. * and `roughnessMap` properties. This node property allows to
  18579. * overwrite the default and define the roughness with a node instead.
  18580. *
  18581. * If you don't want to overwrite the roughness but modify the existing
  18582. * value instead, use {@link materialRoughness}.
  18583. *
  18584. * @type {?Node<float>}
  18585. * @default null
  18586. */
  18587. this.roughnessNode = null;
  18588. this.setDefaultValues( _defaultValues$6 );
  18589. this.setValues( parameters );
  18590. }
  18591. /**
  18592. * Overwritten since this type of material uses {@link EnvironmentNode}
  18593. * to implement the PBR (PMREM based) environment mapping. Besides, the
  18594. * method honors `Scene.environment`.
  18595. *
  18596. * @param {NodeBuilder} builder - The current node builder.
  18597. * @return {?EnvironmentNode<vec3>} The environment node.
  18598. */
  18599. setupEnvironment( builder ) {
  18600. let envNode = super.setupEnvironment( builder );
  18601. if ( envNode === null && builder.environmentNode ) {
  18602. envNode = builder.environmentNode;
  18603. }
  18604. return envNode ? new EnvironmentNode( envNode ) : null;
  18605. }
  18606. /**
  18607. * Setups the lighting model.
  18608. *
  18609. * @return {PhysicalLightingModel} The lighting model.
  18610. */
  18611. setupLightingModel( /*builder*/ ) {
  18612. return new PhysicalLightingModel();
  18613. }
  18614. /**
  18615. * Setups the specular related node variables.
  18616. */
  18617. setupSpecular() {
  18618. const specularColorNode = mix( vec3( 0.04 ), diffuseColor.rgb, metalness );
  18619. specularColor.assign( vec3( 0.04 ) );
  18620. specularColorBlended.assign( specularColorNode );
  18621. specularF90.assign( 1.0 );
  18622. }
  18623. /**
  18624. * Setups the standard specific node variables.
  18625. *
  18626. * @param {NodeBuilder} builder - The current node builder.
  18627. */
  18628. setupVariants() {
  18629. // METALNESS
  18630. const metalnessNode = this.metalnessNode ? float( this.metalnessNode ) : materialMetalness;
  18631. metalness.assign( metalnessNode );
  18632. // ROUGHNESS
  18633. let roughnessNode = this.roughnessNode ? float( this.roughnessNode ) : materialRoughness;
  18634. roughnessNode = getRoughness( { roughness: roughnessNode } );
  18635. roughness.assign( roughnessNode );
  18636. // SPECULAR COLOR
  18637. this.setupSpecular();
  18638. // DIFFUSE COLOR
  18639. diffuseContribution.assign( diffuseColor.rgb.mul( metalnessNode.oneMinus() ) );
  18640. }
  18641. copy( source ) {
  18642. this.emissiveNode = source.emissiveNode;
  18643. this.metalnessNode = source.metalnessNode;
  18644. this.roughnessNode = source.roughnessNode;
  18645. return super.copy( source );
  18646. }
  18647. }
  18648. const _defaultValues$5 = /*@__PURE__*/ new MeshPhysicalMaterial();
  18649. /**
  18650. * Node material version of {@link MeshPhysicalMaterial}.
  18651. *
  18652. * @augments MeshStandardNodeMaterial
  18653. */
  18654. class MeshPhysicalNodeMaterial extends MeshStandardNodeMaterial {
  18655. static get type() {
  18656. return 'MeshPhysicalNodeMaterial';
  18657. }
  18658. /**
  18659. * Constructs a new mesh physical node material.
  18660. *
  18661. * @param {Object} [parameters] - The configuration parameter.
  18662. */
  18663. constructor( parameters ) {
  18664. super();
  18665. /**
  18666. * This flag can be used for type testing.
  18667. *
  18668. * @type {boolean}
  18669. * @readonly
  18670. * @default true
  18671. */
  18672. this.isMeshPhysicalNodeMaterial = true;
  18673. /**
  18674. * The clearcoat of physical materials is by default inferred from the `clearcoat`
  18675. * and `clearcoatMap` properties. This node property allows to overwrite the default
  18676. * and define the clearcoat with a node instead.
  18677. *
  18678. * If you don't want to overwrite the clearcoat but modify the existing
  18679. * value instead, use {@link materialClearcoat}.
  18680. *
  18681. * @type {?Node<float>}
  18682. * @default null
  18683. */
  18684. this.clearcoatNode = null;
  18685. /**
  18686. * The clearcoat roughness of physical materials is by default inferred from the `clearcoatRoughness`
  18687. * and `clearcoatRoughnessMap` properties. This node property allows to overwrite the default
  18688. * and define the clearcoat roughness with a node instead.
  18689. *
  18690. * If you don't want to overwrite the clearcoat roughness but modify the existing
  18691. * value instead, use {@link materialClearcoatRoughness}.
  18692. *
  18693. * @type {?Node<float>}
  18694. * @default null
  18695. */
  18696. this.clearcoatRoughnessNode = null;
  18697. /**
  18698. * The clearcoat normal of physical materials is by default inferred from the `clearcoatNormalMap`
  18699. * property. This node property allows to overwrite the default
  18700. * and define the clearcoat normal with a node instead.
  18701. *
  18702. * If you don't want to overwrite the clearcoat normal but modify the existing
  18703. * value instead, use {@link materialClearcoatNormal}.
  18704. *
  18705. * @type {?Node<vec3>}
  18706. * @default null
  18707. */
  18708. this.clearcoatNormalNode = null;
  18709. /**
  18710. * The sheen of physical materials is by default inferred from the `sheen`, `sheenColor`
  18711. * and `sheenColorMap` properties. This node property allows to overwrite the default
  18712. * and define the sheen with a node instead.
  18713. *
  18714. * If you don't want to overwrite the sheen but modify the existing
  18715. * value instead, use {@link materialSheen}.
  18716. *
  18717. * @type {?Node<vec3>}
  18718. * @default null
  18719. */
  18720. this.sheenNode = null;
  18721. /**
  18722. * The sheen roughness of physical materials is by default inferred from the `sheenRoughness` and
  18723. * `sheenRoughnessMap` properties. This node property allows to overwrite the default
  18724. * and define the sheen roughness with a node instead.
  18725. *
  18726. * If you don't want to overwrite the sheen roughness but modify the existing
  18727. * value instead, use {@link materialSheenRoughness}.
  18728. *
  18729. * @type {?Node<float>}
  18730. * @default null
  18731. */
  18732. this.sheenRoughnessNode = null;
  18733. /**
  18734. * The iridescence of physical materials is by default inferred from the `iridescence`
  18735. * property. This node property allows to overwrite the default
  18736. * and define the iridescence with a node instead.
  18737. *
  18738. * If you don't want to overwrite the iridescence but modify the existing
  18739. * value instead, use {@link materialIridescence}.
  18740. *
  18741. * @type {?Node<float>}
  18742. * @default null
  18743. */
  18744. this.iridescenceNode = null;
  18745. /**
  18746. * The iridescence IOR of physical materials is by default inferred from the `iridescenceIOR`
  18747. * property. This node property allows to overwrite the default
  18748. * and define the iridescence IOR with a node instead.
  18749. *
  18750. * If you don't want to overwrite the iridescence IOR but modify the existing
  18751. * value instead, use {@link materialIridescenceIOR}.
  18752. *
  18753. * @type {?Node<float>}
  18754. * @default null
  18755. */
  18756. this.iridescenceIORNode = null;
  18757. /**
  18758. * The iridescence thickness of physical materials is by default inferred from the `iridescenceThicknessRange`
  18759. * and `iridescenceThicknessMap` properties. This node property allows to overwrite the default
  18760. * and define the iridescence thickness with a node instead.
  18761. *
  18762. * If you don't want to overwrite the iridescence thickness but modify the existing
  18763. * value instead, use {@link materialIridescenceThickness}.
  18764. *
  18765. * @type {?Node<float>}
  18766. * @default null
  18767. */
  18768. this.iridescenceThicknessNode = null;
  18769. /**
  18770. * The specular intensity of physical materials is by default inferred from the `specularIntensity`
  18771. * and `specularIntensityMap` properties. This node property allows to overwrite the default
  18772. * and define the specular intensity with a node instead.
  18773. *
  18774. * If you don't want to overwrite the specular intensity but modify the existing
  18775. * value instead, use {@link materialSpecularIntensity}.
  18776. *
  18777. * @type {?Node<float>}
  18778. * @default null
  18779. */
  18780. this.specularIntensityNode = null;
  18781. /**
  18782. * The specular color of physical materials is by default inferred from the `specularColor`
  18783. * and `specularColorMap` properties. This node property allows to overwrite the default
  18784. * and define the specular color with a node instead.
  18785. *
  18786. * If you don't want to overwrite the specular color but modify the existing
  18787. * value instead, use {@link materialSpecularColor}.
  18788. *
  18789. * @type {?Node<vec3>}
  18790. * @default null
  18791. */
  18792. this.specularColorNode = null;
  18793. /**
  18794. * The ior of physical materials is by default inferred from the `ior`
  18795. * property. This node property allows to overwrite the default
  18796. * and define the ior with a node instead.
  18797. *
  18798. * If you don't want to overwrite the ior but modify the existing
  18799. * value instead, use {@link materialIOR}.
  18800. *
  18801. * @type {?Node<float>}
  18802. * @default null
  18803. */
  18804. this.iorNode = null;
  18805. /**
  18806. * The transmission of physical materials is by default inferred from the `transmission` and
  18807. * `transmissionMap` properties. This node property allows to overwrite the default
  18808. * and define the transmission with a node instead.
  18809. *
  18810. * If you don't want to overwrite the transmission but modify the existing
  18811. * value instead, use {@link materialTransmission}.
  18812. *
  18813. * @type {?Node<float>}
  18814. * @default null
  18815. */
  18816. this.transmissionNode = null;
  18817. /**
  18818. * The thickness of physical materials is by default inferred from the `thickness` and
  18819. * `thicknessMap` properties. This node property allows to overwrite the default
  18820. * and define the thickness with a node instead.
  18821. *
  18822. * If you don't want to overwrite the thickness but modify the existing
  18823. * value instead, use {@link materialThickness}.
  18824. *
  18825. * @type {?Node<float>}
  18826. * @default null
  18827. */
  18828. this.thicknessNode = null;
  18829. /**
  18830. * The attenuation distance of physical materials is by default inferred from the
  18831. * `attenuationDistance` property. This node property allows to overwrite the default
  18832. * and define the attenuation distance with a node instead.
  18833. *
  18834. * If you don't want to overwrite the attenuation distance but modify the existing
  18835. * value instead, use {@link materialAttenuationDistance}.
  18836. *
  18837. * @type {?Node<float>}
  18838. * @default null
  18839. */
  18840. this.attenuationDistanceNode = null;
  18841. /**
  18842. * The attenuation color of physical materials is by default inferred from the
  18843. * `attenuationColor` property. This node property allows to overwrite the default
  18844. * and define the attenuation color with a node instead.
  18845. *
  18846. * If you don't want to overwrite the attenuation color but modify the existing
  18847. * value instead, use {@link materialAttenuationColor}.
  18848. *
  18849. * @type {?Node<vec3>}
  18850. * @default null
  18851. */
  18852. this.attenuationColorNode = null;
  18853. /**
  18854. * The dispersion of physical materials is by default inferred from the
  18855. * `dispersion` property. This node property allows to overwrite the default
  18856. * and define the dispersion with a node instead.
  18857. *
  18858. * If you don't want to overwrite the dispersion but modify the existing
  18859. * value instead, use {@link materialDispersion}.
  18860. *
  18861. * @type {?Node<float>}
  18862. * @default null
  18863. */
  18864. this.dispersionNode = null;
  18865. /**
  18866. * The anisotropy of physical materials is by default inferred from the
  18867. * `anisotropy` property. This node property allows to overwrite the default
  18868. * and define the anisotropy with a node instead.
  18869. *
  18870. * If you don't want to overwrite the anisotropy but modify the existing
  18871. * value instead, use {@link materialAnisotropy}.
  18872. *
  18873. * @type {?Node<float>}
  18874. * @default null
  18875. */
  18876. this.anisotropyNode = null;
  18877. this.setDefaultValues( _defaultValues$5 );
  18878. this.setValues( parameters );
  18879. }
  18880. /**
  18881. * Whether the lighting model should use clearcoat or not.
  18882. *
  18883. * @type {boolean}
  18884. * @default true
  18885. */
  18886. get useClearcoat() {
  18887. return this.clearcoat > 0 || this.clearcoatNode !== null;
  18888. }
  18889. /**
  18890. * Whether the lighting model should use iridescence or not.
  18891. *
  18892. * @type {boolean}
  18893. * @default true
  18894. */
  18895. get useIridescence() {
  18896. return this.iridescence > 0 || this.iridescenceNode !== null;
  18897. }
  18898. /**
  18899. * Whether the lighting model should use sheen or not.
  18900. *
  18901. * @type {boolean}
  18902. * @default true
  18903. */
  18904. get useSheen() {
  18905. return this.sheen > 0 || this.sheenNode !== null;
  18906. }
  18907. /**
  18908. * Whether the lighting model should use anisotropy or not.
  18909. *
  18910. * @type {boolean}
  18911. * @default true
  18912. */
  18913. get useAnisotropy() {
  18914. return this.anisotropy > 0 || this.anisotropyNode !== null;
  18915. }
  18916. /**
  18917. * Whether the lighting model should use transmission or not.
  18918. *
  18919. * @type {boolean}
  18920. * @default true
  18921. */
  18922. get useTransmission() {
  18923. return this.transmission > 0 || this.transmissionNode !== null;
  18924. }
  18925. /**
  18926. * Whether the lighting model should use dispersion or not.
  18927. *
  18928. * @type {boolean}
  18929. * @default true
  18930. */
  18931. get useDispersion() {
  18932. return this.dispersion > 0 || this.dispersionNode !== null;
  18933. }
  18934. /**
  18935. * Setups the specular related node variables.
  18936. */
  18937. setupSpecular() {
  18938. const iorNode = this.iorNode ? float( this.iorNode ) : materialIOR;
  18939. ior.assign( iorNode );
  18940. specularColor.assign( min$1( pow2( ior.sub( 1.0 ).div( ior.add( 1.0 ) ) ).mul( materialSpecularColor ), vec3( 1.0 ) ).mul( materialSpecularIntensity ) );
  18941. specularColorBlended.assign( mix( specularColor, diffuseColor.rgb, metalness ) );
  18942. specularF90.assign( mix( materialSpecularIntensity, 1.0, metalness ) );
  18943. }
  18944. /**
  18945. * Setups the lighting model.
  18946. *
  18947. * @return {PhysicalLightingModel} The lighting model.
  18948. */
  18949. setupLightingModel( /*builder*/ ) {
  18950. return new PhysicalLightingModel( this.useClearcoat, this.useSheen, this.useIridescence, this.useAnisotropy, this.useTransmission, this.useDispersion );
  18951. }
  18952. /**
  18953. * Setups the physical specific node variables.
  18954. *
  18955. * @param {NodeBuilder} builder - The current node builder.
  18956. */
  18957. setupVariants( builder ) {
  18958. super.setupVariants( builder );
  18959. // CLEARCOAT
  18960. if ( this.useClearcoat ) {
  18961. const clearcoatNode = this.clearcoatNode ? float( this.clearcoatNode ) : materialClearcoat;
  18962. const clearcoatRoughnessNode = this.clearcoatRoughnessNode ? float( this.clearcoatRoughnessNode ) : materialClearcoatRoughness;
  18963. clearcoat.assign( clearcoatNode );
  18964. clearcoatRoughness.assign( getRoughness( { roughness: clearcoatRoughnessNode } ) );
  18965. }
  18966. // SHEEN
  18967. if ( this.useSheen ) {
  18968. const sheenNode = this.sheenNode ? vec3( this.sheenNode ) : materialSheen;
  18969. const sheenRoughnessNode = this.sheenRoughnessNode ? float( this.sheenRoughnessNode ) : materialSheenRoughness;
  18970. sheen.assign( sheenNode );
  18971. sheenRoughness.assign( sheenRoughnessNode );
  18972. }
  18973. // IRIDESCENCE
  18974. if ( this.useIridescence ) {
  18975. const iridescenceNode = this.iridescenceNode ? float( this.iridescenceNode ) : materialIridescence;
  18976. const iridescenceIORNode = this.iridescenceIORNode ? float( this.iridescenceIORNode ) : materialIridescenceIOR;
  18977. const iridescenceThicknessNode = this.iridescenceThicknessNode ? float( this.iridescenceThicknessNode ) : materialIridescenceThickness;
  18978. iridescence.assign( iridescenceNode );
  18979. iridescenceIOR.assign( iridescenceIORNode );
  18980. iridescenceThickness.assign( iridescenceThicknessNode );
  18981. }
  18982. // ANISOTROPY
  18983. if ( this.useAnisotropy ) {
  18984. const anisotropyV = ( this.anisotropyNode ? vec2( this.anisotropyNode ) : materialAnisotropy ).toVar();
  18985. anisotropy.assign( anisotropyV.length() );
  18986. If( anisotropy.equal( 0.0 ), () => {
  18987. anisotropyV.assign( vec2( 1.0, 0.0 ) );
  18988. } ).Else( () => {
  18989. anisotropyV.divAssign( vec2( anisotropy ) );
  18990. anisotropy.assign( anisotropy.saturate() );
  18991. } );
  18992. // Roughness along the anisotropy bitangent is the material roughness, while the tangent roughness increases with anisotropy.
  18993. alphaT.assign( anisotropy.pow2().mix( roughness.pow2(), 1.0 ) );
  18994. anisotropyT.assign( TBNViewMatrix[ 0 ].mul( anisotropyV.x ).add( TBNViewMatrix[ 1 ].mul( anisotropyV.y ) ) );
  18995. anisotropyB.assign( TBNViewMatrix[ 1 ].mul( anisotropyV.x ).sub( TBNViewMatrix[ 0 ].mul( anisotropyV.y ) ) );
  18996. }
  18997. // TRANSMISSION
  18998. if ( this.useTransmission ) {
  18999. const transmissionNode = this.transmissionNode ? float( this.transmissionNode ) : materialTransmission;
  19000. const thicknessNode = this.thicknessNode ? float( this.thicknessNode ) : materialThickness;
  19001. const attenuationDistanceNode = this.attenuationDistanceNode ? float( this.attenuationDistanceNode ) : materialAttenuationDistance;
  19002. const attenuationColorNode = this.attenuationColorNode ? vec3( this.attenuationColorNode ) : materialAttenuationColor;
  19003. transmission.assign( transmissionNode );
  19004. thickness.assign( thicknessNode );
  19005. attenuationDistance.assign( attenuationDistanceNode );
  19006. attenuationColor.assign( attenuationColorNode );
  19007. if ( this.useDispersion ) {
  19008. const dispersionNode = this.dispersionNode ? float( this.dispersionNode ) : materialDispersion;
  19009. dispersion.assign( dispersionNode );
  19010. }
  19011. }
  19012. }
  19013. /**
  19014. * Setups the clearcoat normal node.
  19015. *
  19016. * @return {Node<vec3>} The clearcoat normal.
  19017. */
  19018. setupClearcoatNormal() {
  19019. return this.clearcoatNormalNode ? vec3( this.clearcoatNormalNode ) : materialClearcoatNormal;
  19020. }
  19021. setup( builder ) {
  19022. builder.context.setupClearcoatNormal = () => subBuild( this.setupClearcoatNormal( builder ), 'NORMAL', 'vec3' );
  19023. super.setup( builder );
  19024. }
  19025. copy( source ) {
  19026. this.clearcoatNode = source.clearcoatNode;
  19027. this.clearcoatRoughnessNode = source.clearcoatRoughnessNode;
  19028. this.clearcoatNormalNode = source.clearcoatNormalNode;
  19029. this.sheenNode = source.sheenNode;
  19030. this.sheenRoughnessNode = source.sheenRoughnessNode;
  19031. this.iridescenceNode = source.iridescenceNode;
  19032. this.iridescenceIORNode = source.iridescenceIORNode;
  19033. this.iridescenceThicknessNode = source.iridescenceThicknessNode;
  19034. this.specularIntensityNode = source.specularIntensityNode;
  19035. this.specularColorNode = source.specularColorNode;
  19036. this.transmissionNode = source.transmissionNode;
  19037. this.thicknessNode = source.thicknessNode;
  19038. this.attenuationDistanceNode = source.attenuationDistanceNode;
  19039. this.attenuationColorNode = source.attenuationColorNode;
  19040. this.dispersionNode = source.dispersionNode;
  19041. this.anisotropyNode = source.anisotropyNode;
  19042. return super.copy( source );
  19043. }
  19044. }
  19045. /**
  19046. * Represents the lighting model for {@link MeshSSSNodeMaterial}.
  19047. *
  19048. * @augments PhysicalLightingModel
  19049. */
  19050. class SSSLightingModel extends PhysicalLightingModel {
  19051. /**
  19052. * Constructs a new physical lighting model.
  19053. *
  19054. * @param {boolean} [clearcoat=false] - Whether clearcoat is supported or not.
  19055. * @param {boolean} [sheen=false] - Whether sheen is supported or not.
  19056. * @param {boolean} [iridescence=false] - Whether iridescence is supported or not.
  19057. * @param {boolean} [anisotropy=false] - Whether anisotropy is supported or not.
  19058. * @param {boolean} [transmission=false] - Whether transmission is supported or not.
  19059. * @param {boolean} [dispersion=false] - Whether dispersion is supported or not.
  19060. * @param {boolean} [sss=false] - Whether SSS is supported or not.
  19061. */
  19062. constructor( clearcoat = false, sheen = false, iridescence = false, anisotropy = false, transmission = false, dispersion = false, sss = false ) {
  19063. super( clearcoat, sheen, iridescence, anisotropy, transmission, dispersion );
  19064. /**
  19065. * Whether the lighting model should use SSS or not.
  19066. *
  19067. * @type {boolean}
  19068. * @default false
  19069. */
  19070. this.useSSS = sss;
  19071. }
  19072. /**
  19073. * Extends the default implementation with a SSS term.
  19074. *
  19075. * Reference: [Approximating Translucency for a Fast, Cheap and Convincing Subsurface Scattering Look](https://colinbarrebrisebois.com/2011/03/07/gdc-2011-approximating-translucency-for-a-fast-cheap-and-convincing-subsurface-scattering-look/)
  19076. *
  19077. * @param {Object} input - The input data.
  19078. * @param {NodeBuilder} builder - The current node builder.
  19079. */
  19080. direct( { lightDirection, lightColor, reflectedLight }, builder ) {
  19081. if ( this.useSSS === true ) {
  19082. const material = builder.material;
  19083. const { thicknessColorNode, thicknessDistortionNode, thicknessAmbientNode, thicknessAttenuationNode, thicknessPowerNode, thicknessScaleNode } = material;
  19084. const scatteringHalf = lightDirection.add( normalView.mul( thicknessDistortionNode ) ).normalize();
  19085. const scatteringDot = float( positionViewDirection.dot( scatteringHalf.negate() ).saturate().pow( thicknessPowerNode ).mul( thicknessScaleNode ) );
  19086. const scatteringIllu = vec3( scatteringDot.add( thicknessAmbientNode ).mul( thicknessColorNode ) );
  19087. reflectedLight.directDiffuse.addAssign( scatteringIllu.mul( thicknessAttenuationNode.mul( lightColor ) ) );
  19088. }
  19089. super.direct( { lightDirection, lightColor, reflectedLight }, builder );
  19090. }
  19091. }
  19092. /**
  19093. * This node material is an experimental extension of {@link MeshPhysicalNodeMaterial}
  19094. * that implements a Subsurface scattering (SSS) term.
  19095. *
  19096. * @augments MeshPhysicalNodeMaterial
  19097. */
  19098. class MeshSSSNodeMaterial extends MeshPhysicalNodeMaterial {
  19099. static get type() {
  19100. return 'MeshSSSNodeMaterial';
  19101. }
  19102. /**
  19103. * Constructs a new mesh SSS node material.
  19104. *
  19105. * @param {Object} [parameters] - The configuration parameter.
  19106. */
  19107. constructor( parameters ) {
  19108. super( parameters );
  19109. /**
  19110. * Represents the thickness color.
  19111. *
  19112. * @type {?Node<vec3>}
  19113. * @default null
  19114. */
  19115. this.thicknessColorNode = null;
  19116. /**
  19117. * Represents the distortion factor.
  19118. *
  19119. * @type {?Node<float>}
  19120. */
  19121. this.thicknessDistortionNode = float( 0.1 );
  19122. /**
  19123. * Represents the thickness ambient factor.
  19124. *
  19125. * @type {?Node<float>}
  19126. */
  19127. this.thicknessAmbientNode = float( 0.0 );
  19128. /**
  19129. * Represents the thickness attenuation.
  19130. *
  19131. * @type {?Node<float>}
  19132. */
  19133. this.thicknessAttenuationNode = float( .1 );
  19134. /**
  19135. * Represents the thickness power.
  19136. *
  19137. * @type {?Node<float>}
  19138. */
  19139. this.thicknessPowerNode = float( 2.0 );
  19140. /**
  19141. * Represents the thickness scale.
  19142. *
  19143. * @type {?Node<float>}
  19144. */
  19145. this.thicknessScaleNode = float( 10.0 );
  19146. }
  19147. /**
  19148. * Whether the lighting model should use SSS or not.
  19149. *
  19150. * @type {boolean}
  19151. * @default true
  19152. */
  19153. get useSSS() {
  19154. return this.thicknessColorNode !== null;
  19155. }
  19156. /**
  19157. * Setups the lighting model.
  19158. *
  19159. * @return {SSSLightingModel} The lighting model.
  19160. */
  19161. setupLightingModel( /*builder*/ ) {
  19162. return new SSSLightingModel( this.useClearcoat, this.useSheen, this.useIridescence, this.useAnisotropy, this.useTransmission, this.useDispersion, this.useSSS );
  19163. }
  19164. copy( source ) {
  19165. this.thicknessColorNode = source.thicknessColorNode;
  19166. this.thicknessDistortionNode = source.thicknessDistortionNode;
  19167. this.thicknessAmbientNode = source.thicknessAmbientNode;
  19168. this.thicknessAttenuationNode = source.thicknessAttenuationNode;
  19169. this.thicknessPowerNode = source.thicknessPowerNode;
  19170. this.thicknessScaleNode = source.thicknessScaleNode;
  19171. return super.copy( source );
  19172. }
  19173. }
  19174. const getGradientIrradiance = /*@__PURE__*/ Fn( ( { normal, lightDirection, builder } ) => {
  19175. // dotNL will be from -1.0 to 1.0
  19176. const dotNL = normal.dot( lightDirection );
  19177. const coord = vec2( dotNL.mul( 0.5 ).add( 0.5 ), 0.0 );
  19178. if ( builder.material.gradientMap ) {
  19179. const gradientMap = materialReference( 'gradientMap', 'texture' ).context( { getUV: () => coord } );
  19180. return vec3( gradientMap.r );
  19181. } else {
  19182. const fw = coord.fwidth().mul( 0.5 );
  19183. return mix( vec3( 0.7 ), vec3( 1.0 ), smoothstep( float( 0.7 ).sub( fw.x ), float( 0.7 ).add( fw.x ), coord.x ) );
  19184. }
  19185. } );
  19186. /**
  19187. * Represents the lighting model for a toon material. Used in {@link MeshToonNodeMaterial}.
  19188. *
  19189. * @augments LightingModel
  19190. */
  19191. class ToonLightingModel extends LightingModel {
  19192. /**
  19193. * Implements the direct lighting. Instead of using a conventional smooth irradiance, the irradiance is
  19194. * reduced to a small number of discrete shades to create a comic-like, flat look.
  19195. *
  19196. * @param {Object} lightData - The light data.
  19197. * @param {NodeBuilder} builder - The current node builder.
  19198. */
  19199. direct( { lightDirection, lightColor, reflectedLight }, builder ) {
  19200. const irradiance = getGradientIrradiance( { normal: normalGeometry, lightDirection, builder } ).mul( lightColor );
  19201. reflectedLight.directDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor: diffuseColor.rgb } ) ) );
  19202. }
  19203. /**
  19204. * Implements the indirect lighting.
  19205. *
  19206. * @param {NodeBuilder} builder - The current node builder.
  19207. */
  19208. indirect( builder ) {
  19209. const { ambientOcclusion, irradiance, reflectedLight } = builder.context;
  19210. reflectedLight.indirectDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor } ) ) );
  19211. reflectedLight.indirectDiffuse.mulAssign( ambientOcclusion );
  19212. }
  19213. }
  19214. const _defaultValues$4 = /*@__PURE__*/ new MeshToonMaterial();
  19215. /**
  19216. * Node material version of {@link MeshToonMaterial}.
  19217. *
  19218. * @augments NodeMaterial
  19219. */
  19220. class MeshToonNodeMaterial extends NodeMaterial {
  19221. static get type() {
  19222. return 'MeshToonNodeMaterial';
  19223. }
  19224. /**
  19225. * Constructs a new mesh toon node material.
  19226. *
  19227. * @param {Object} [parameters] - The configuration parameter.
  19228. */
  19229. constructor( parameters ) {
  19230. super();
  19231. /**
  19232. * This flag can be used for type testing.
  19233. *
  19234. * @type {boolean}
  19235. * @readonly
  19236. * @default true
  19237. */
  19238. this.isMeshToonNodeMaterial = true;
  19239. /**
  19240. * Set to `true` because toon materials react on lights.
  19241. *
  19242. * @type {boolean}
  19243. * @default true
  19244. */
  19245. this.lights = true;
  19246. this.setDefaultValues( _defaultValues$4 );
  19247. this.setValues( parameters );
  19248. }
  19249. /**
  19250. * Setups the lighting model.
  19251. *
  19252. * @return {ToonLightingModel} The lighting model.
  19253. */
  19254. setupLightingModel( /*builder*/ ) {
  19255. return new ToonLightingModel();
  19256. }
  19257. }
  19258. /**
  19259. * TSL function for creating a matcap uv node.
  19260. *
  19261. * Can be used to compute texture coordinates for projecting a
  19262. * matcap onto a mesh. Used by {@link MeshMatcapNodeMaterial}.
  19263. *
  19264. * @tsl
  19265. * @function
  19266. * @returns {Node<vec2>} The matcap UV coordinates.
  19267. */
  19268. const matcapUV = /*@__PURE__*/ Fn( () => {
  19269. const x = vec3( positionViewDirection.z, 0, positionViewDirection.x.negate() ).normalize();
  19270. const y = positionViewDirection.cross( x );
  19271. return vec2( x.dot( normalView ), y.dot( normalView ) ).mul( 0.495 ).add( 0.5 ); // 0.495 to remove artifacts caused by undersized matcap disks
  19272. } ).once( [ 'NORMAL', 'VERTEX' ] )().toVar( 'matcapUV' );
  19273. const _defaultValues$3 = /*@__PURE__*/ new MeshMatcapMaterial();
  19274. /**
  19275. * Node material version of {@link MeshMatcapMaterial}.
  19276. *
  19277. * @augments NodeMaterial
  19278. */
  19279. class MeshMatcapNodeMaterial extends NodeMaterial {
  19280. static get type() {
  19281. return 'MeshMatcapNodeMaterial';
  19282. }
  19283. /**
  19284. * Constructs a new mesh normal node material.
  19285. *
  19286. * @param {Object} [parameters] - The configuration parameter.
  19287. */
  19288. constructor( parameters ) {
  19289. super();
  19290. /**
  19291. * This flag can be used for type testing.
  19292. *
  19293. * @type {boolean}
  19294. * @readonly
  19295. * @default true
  19296. */
  19297. this.isMeshMatcapNodeMaterial = true;
  19298. this.setDefaultValues( _defaultValues$3 );
  19299. this.setValues( parameters );
  19300. }
  19301. /**
  19302. * Setups the matcap specific node variables.
  19303. *
  19304. * @param {NodeBuilder} builder - The current node builder.
  19305. */
  19306. setupVariants( builder ) {
  19307. const uv = matcapUV;
  19308. let matcapColor;
  19309. if ( builder.material.matcap ) {
  19310. matcapColor = materialReference( 'matcap', 'texture' ).context( { getUV: () => uv } );
  19311. } else {
  19312. matcapColor = vec3( mix( 0.2, 0.8, uv.y ) ); // default if matcap is missing
  19313. }
  19314. diffuseColor.rgb.mulAssign( matcapColor.rgb );
  19315. }
  19316. }
  19317. /**
  19318. * Applies a rotation to the given position node.
  19319. *
  19320. * @augments TempNode
  19321. */
  19322. class RotateNode extends TempNode {
  19323. static get type() {
  19324. return 'RotateNode';
  19325. }
  19326. /**
  19327. * Constructs a new rotate node.
  19328. *
  19329. * @param {Node} positionNode - The position node.
  19330. * @param {Node} rotationNode - Represents the rotation that is applied to the position node. Depending
  19331. * on whether the position data are 2D or 3D, the rotation is expressed a single float value or an Euler value.
  19332. */
  19333. constructor( positionNode, rotationNode ) {
  19334. super();
  19335. /**
  19336. * The position node.
  19337. *
  19338. * @type {Node}
  19339. */
  19340. this.positionNode = positionNode;
  19341. /**
  19342. * Represents the rotation that is applied to the position node.
  19343. * Depending on whether the position data are 2D or 3D, the rotation is expressed a single float value or an Euler value.
  19344. *
  19345. * @type {Node}
  19346. */
  19347. this.rotationNode = rotationNode;
  19348. }
  19349. /**
  19350. * The type of the {@link RotateNode#positionNode} defines the node's type.
  19351. *
  19352. * @param {NodeBuilder} builder - The current node builder.
  19353. * @return {string} The node's type.
  19354. */
  19355. getNodeType( builder ) {
  19356. return this.positionNode.getNodeType( builder );
  19357. }
  19358. setup( builder ) {
  19359. const { rotationNode, positionNode } = this;
  19360. const nodeType = this.getNodeType( builder );
  19361. if ( nodeType === 'vec2' ) {
  19362. const cosAngle = rotationNode.cos();
  19363. const sinAngle = rotationNode.sin();
  19364. const rotationMatrix = mat2(
  19365. cosAngle, sinAngle,
  19366. sinAngle.negate(), cosAngle
  19367. );
  19368. return rotationMatrix.mul( positionNode );
  19369. } else {
  19370. const rotation = rotationNode;
  19371. 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 ) );
  19372. 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 ) );
  19373. 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 ) );
  19374. return rotationXMatrix.mul( rotationYMatrix ).mul( rotationZMatrix ).mul( vec4( positionNode, 1.0 ) ).xyz;
  19375. }
  19376. }
  19377. }
  19378. /**
  19379. * TSL function for creating a rotate node.
  19380. *
  19381. * @tsl
  19382. * @function
  19383. * @param {Node} positionNode - The position node.
  19384. * @param {Node} rotationNode - Represents the rotation that is applied to the position node. Depending
  19385. * on whether the position data are 2D or 3D, the rotation is expressed a single float value or an Euler value.
  19386. * @returns {RotateNode}
  19387. */
  19388. const rotate = /*@__PURE__*/ nodeProxy( RotateNode ).setParameterLength( 2 );
  19389. const _defaultValues$2 = /*@__PURE__*/ new SpriteMaterial();
  19390. /**
  19391. * Node material version of {@link SpriteMaterial}.
  19392. *
  19393. * @augments NodeMaterial
  19394. */
  19395. class SpriteNodeMaterial extends NodeMaterial {
  19396. static get type() {
  19397. return 'SpriteNodeMaterial';
  19398. }
  19399. /**
  19400. * Constructs a new sprite node material.
  19401. *
  19402. * @param {Object} [parameters] - The configuration parameter.
  19403. */
  19404. constructor( parameters ) {
  19405. super();
  19406. /**
  19407. * This flag can be used for type testing.
  19408. *
  19409. * @type {boolean}
  19410. * @readonly
  19411. * @default true
  19412. */
  19413. this.isSpriteNodeMaterial = true;
  19414. this._useSizeAttenuation = true;
  19415. /**
  19416. * This property makes it possible to define the position of the sprite with a
  19417. * node. That can be useful when the material is used with instanced rendering
  19418. * and node data are defined with an instanced attribute node:
  19419. * ```js
  19420. * const positionAttribute = new InstancedBufferAttribute( new Float32Array( positions ), 3 );
  19421. * material.positionNode = instancedBufferAttribute( positionAttribute );
  19422. * ```
  19423. * Another possibility is to compute the instanced data with a compute shader:
  19424. * ```js
  19425. * const positionBuffer = instancedArray( particleCount, 'vec3' );
  19426. * particleMaterial.positionNode = positionBuffer.toAttribute();
  19427. * ```
  19428. *
  19429. * @type {?Node<vec2>}
  19430. * @default null
  19431. */
  19432. this.positionNode = null;
  19433. /**
  19434. * The rotation of sprite materials is by default inferred from the `rotation`,
  19435. * property. This node property allows to overwrite the default and define
  19436. * the rotation with a node instead.
  19437. *
  19438. * If you don't want to overwrite the rotation but modify the existing
  19439. * value instead, use {@link materialRotation}.
  19440. *
  19441. * @type {?Node<float>}
  19442. * @default null
  19443. */
  19444. this.rotationNode = null;
  19445. /**
  19446. * This node property provides an additional way to scale sprites next to
  19447. * `Object3D.scale`. The scale transformation based in `Object3D.scale`
  19448. * is multiplied with the scale value of this node in the vertex shader.
  19449. *
  19450. * @type {?Node<vec2>}
  19451. * @default null
  19452. */
  19453. this.scaleNode = null;
  19454. /**
  19455. * In Sprites, the transparent property is enabled by default.
  19456. *
  19457. * @type {boolean}
  19458. * @default true
  19459. */
  19460. this.transparent = true;
  19461. this.setDefaultValues( _defaultValues$2 );
  19462. this.setValues( parameters );
  19463. }
  19464. /**
  19465. * Setups the position node in view space. This method implements
  19466. * the sprite specific vertex shader.
  19467. *
  19468. * @param {NodeBuilder} builder - The current node builder.
  19469. * @return {Node<vec3>} The position in view space.
  19470. */
  19471. setupPositionView( builder ) {
  19472. const { object, camera } = builder;
  19473. const { positionNode, rotationNode, scaleNode, sizeAttenuation } = this;
  19474. const mvPosition = modelViewMatrix.mul( vec3( positionNode || 0 ) );
  19475. let scale = vec2( modelWorldMatrix[ 0 ].xyz.length(), modelWorldMatrix[ 1 ].xyz.length() );
  19476. if ( scaleNode !== null ) {
  19477. scale = scale.mul( vec2( scaleNode ) );
  19478. }
  19479. if ( camera.isPerspectiveCamera && sizeAttenuation === false ) {
  19480. scale = scale.mul( mvPosition.z.negate() );
  19481. }
  19482. let alignedPosition = positionGeometry.xy;
  19483. if ( object.center && object.center.isVector2 === true ) {
  19484. const center = reference$1( 'center', 'vec2', object );
  19485. alignedPosition = alignedPosition.sub( center.sub( 0.5 ) );
  19486. }
  19487. alignedPosition = alignedPosition.mul( scale );
  19488. const rotation = float( rotationNode || materialRotation );
  19489. const rotatedPosition = rotate( alignedPosition, rotation );
  19490. return vec4( mvPosition.xy.add( rotatedPosition ), mvPosition.zw );
  19491. }
  19492. copy( source ) {
  19493. this.positionNode = source.positionNode;
  19494. this.rotationNode = source.rotationNode;
  19495. this.scaleNode = source.scaleNode;
  19496. return super.copy( source );
  19497. }
  19498. /**
  19499. * Whether to use size attenuation or not.
  19500. *
  19501. * @type {boolean}
  19502. * @default true
  19503. */
  19504. get sizeAttenuation() {
  19505. return this._useSizeAttenuation;
  19506. }
  19507. set sizeAttenuation( value ) {
  19508. if ( this._useSizeAttenuation !== value ) {
  19509. this._useSizeAttenuation = value;
  19510. this.needsUpdate = true;
  19511. }
  19512. }
  19513. }
  19514. const _defaultValues$1 = /*@__PURE__*/ new PointsMaterial();
  19515. const _size$4 = /*@__PURE__*/ new Vector2();
  19516. /**
  19517. * Node material version of {@link PointsMaterial}.
  19518. *
  19519. * This material can be used in two ways:
  19520. *
  19521. * - By rendering point primitives with {@link Points}. Since WebGPU only supports point primitives
  19522. * with a pixel size of `1`, it's not possible to define a size.
  19523. *
  19524. * ```js
  19525. * const pointCloud = new THREE.Points( geometry, new THREE.PointsNodeMaterial() );
  19526. * ```
  19527. *
  19528. * - By rendering point primitives with {@link Sprites}. In this case, size is honored,
  19529. * see {@link PointsNodeMaterial#sizeNode}.
  19530. *
  19531. * ```js
  19532. * const instancedPoints = new THREE.Sprite( new THREE.PointsNodeMaterial( { positionNode: instancedBufferAttribute( positionAttribute ) } ) );
  19533. * ```
  19534. *
  19535. * @augments SpriteNodeMaterial
  19536. */
  19537. class PointsNodeMaterial extends SpriteNodeMaterial {
  19538. static get type() {
  19539. return 'PointsNodeMaterial';
  19540. }
  19541. /**
  19542. * Constructs a new points node material.
  19543. *
  19544. * @param {Object} [parameters] - The configuration parameter.
  19545. */
  19546. constructor( parameters ) {
  19547. super();
  19548. /**
  19549. * This node property provides an additional way to set the point size.
  19550. *
  19551. * Note that WebGPU only supports point primitives with 1 pixel size. Consequently,
  19552. * this node has no effect when the material is used with {@link Points} and a WebGPU
  19553. * backend. If an application wants to render points with a size larger than 1 pixel,
  19554. * the material should be used with {@link Sprite} and instancing.
  19555. *
  19556. * @type {?Node<vec2>}
  19557. * @default null
  19558. */
  19559. this.sizeNode = null;
  19560. /**
  19561. * This flag can be used for type testing.
  19562. *
  19563. * @type {boolean}
  19564. * @readonly
  19565. * @default true
  19566. */
  19567. this.isPointsNodeMaterial = true;
  19568. this.setDefaultValues( _defaultValues$1 );
  19569. this.setValues( parameters );
  19570. }
  19571. setupPositionView() {
  19572. const { positionNode } = this;
  19573. return modelViewMatrix.mul( vec3( positionNode || positionLocal ) ).xyz;
  19574. }
  19575. setupVertexSprite( builder ) {
  19576. const { material, camera } = builder;
  19577. const { rotationNode, scaleNode, sizeNode, sizeAttenuation } = this;
  19578. let mvp = super.setupVertex( builder );
  19579. // skip further processing if the material is not a node material
  19580. if ( material.isNodeMaterial !== true ) {
  19581. return mvp;
  19582. }
  19583. // point size
  19584. let pointSize = sizeNode !== null ? vec2( sizeNode ) : materialPointSize;
  19585. pointSize = pointSize.mul( screenDPR );
  19586. // size attenuation
  19587. if ( camera.isPerspectiveCamera && sizeAttenuation === true ) {
  19588. // follow WebGLRenderer's implementation, and scale by half the canvas height in logical units
  19589. pointSize = pointSize.mul( scale.div( positionView.z.negate() ) );
  19590. }
  19591. // scale
  19592. if ( scaleNode && scaleNode.isNode ) {
  19593. pointSize = pointSize.mul( vec2( scaleNode ) );
  19594. }
  19595. // compute offset
  19596. let offset = positionGeometry.xy;
  19597. // apply rotation
  19598. if ( rotationNode && rotationNode.isNode ) {
  19599. const rotation = float( rotationNode );
  19600. offset = rotate( offset, rotation );
  19601. }
  19602. // account for point size
  19603. offset = offset.mul( pointSize );
  19604. // scale by viewport size
  19605. offset = offset.div( viewportSize.div( 2 ) );
  19606. // compensate for the perspective divide
  19607. offset = offset.mul( mvp.w );
  19608. // add offset
  19609. mvp = mvp.add( vec4( offset, 0, 0 ) );
  19610. return mvp;
  19611. }
  19612. setupVertex( builder ) {
  19613. if ( builder.object.isPoints ) {
  19614. return super.setupVertex( builder );
  19615. } else {
  19616. return this.setupVertexSprite( builder );
  19617. }
  19618. }
  19619. /**
  19620. * Whether alpha to coverage should be used or not.
  19621. *
  19622. * @type {boolean}
  19623. * @default true
  19624. */
  19625. get alphaToCoverage() {
  19626. return this._useAlphaToCoverage;
  19627. }
  19628. set alphaToCoverage( value ) {
  19629. if ( this._useAlphaToCoverage !== value ) {
  19630. this._useAlphaToCoverage = value;
  19631. this.needsUpdate = true;
  19632. }
  19633. }
  19634. }
  19635. const scale = /*@__PURE__*/ uniform( 1 ).onFrameUpdate( function ( { renderer } ) {
  19636. const size = renderer.getSize( _size$4 ); // logical units
  19637. this.value = 0.5 * size.y;
  19638. } );
  19639. /**
  19640. * Represents lighting model for a shadow material. Used in {@link ShadowNodeMaterial}.
  19641. *
  19642. * @augments LightingModel
  19643. */
  19644. class ShadowMaskModel extends LightingModel {
  19645. /**
  19646. * Constructs a new shadow mask model.
  19647. */
  19648. constructor() {
  19649. super();
  19650. /**
  19651. * The shadow mask node.
  19652. *
  19653. * @type {Node}
  19654. */
  19655. this.shadowNode = float( 1 ).toVar( 'shadowMask' );
  19656. }
  19657. /**
  19658. * Only used to save the shadow mask.
  19659. *
  19660. * @param {Object} input - The input data.
  19661. */
  19662. direct( { lightNode } ) {
  19663. if ( lightNode.shadowNode !== null ) {
  19664. this.shadowNode.mulAssign( lightNode.shadowNode );
  19665. }
  19666. }
  19667. /**
  19668. * Uses the shadow mask to produce the final color.
  19669. *
  19670. * @param {NodeBuilder} builder - The current node builder.
  19671. */
  19672. finish( { context } ) {
  19673. diffuseColor.a.mulAssign( this.shadowNode.oneMinus() );
  19674. context.outgoingLight.rgb.assign( diffuseColor.rgb ); // TODO: Optimize LightsNode to avoid this assignment
  19675. }
  19676. }
  19677. const _defaultValues = /*@__PURE__*/ new ShadowMaterial();
  19678. /**
  19679. * Node material version of {@link ShadowMaterial}.
  19680. *
  19681. * @augments NodeMaterial
  19682. */
  19683. class ShadowNodeMaterial extends NodeMaterial {
  19684. static get type() {
  19685. return 'ShadowNodeMaterial';
  19686. }
  19687. /**
  19688. * Constructs a new shadow node material.
  19689. *
  19690. * @param {Object} [parameters] - The configuration parameter.
  19691. */
  19692. constructor( parameters ) {
  19693. super();
  19694. /**
  19695. * This flag can be used for type testing.
  19696. *
  19697. * @type {boolean}
  19698. * @readonly
  19699. * @default true
  19700. */
  19701. this.isShadowNodeMaterial = true;
  19702. /**
  19703. * Set to `true` because so it's possible to implement
  19704. * the shadow mask effect.
  19705. *
  19706. * @type {boolean}
  19707. * @default true
  19708. */
  19709. this.lights = true;
  19710. /**
  19711. * Overwritten since shadow materials are transparent
  19712. * by default.
  19713. *
  19714. * @type {boolean}
  19715. * @default true
  19716. */
  19717. this.transparent = true;
  19718. this.setDefaultValues( _defaultValues );
  19719. this.setValues( parameters );
  19720. }
  19721. /**
  19722. * Setups the lighting model.
  19723. *
  19724. * @return {ShadowMaskModel} The lighting model.
  19725. */
  19726. setupLightingModel( /*builder*/ ) {
  19727. return new ShadowMaskModel();
  19728. }
  19729. }
  19730. const scatteringDensity = property( 'vec3' );
  19731. const linearDepthRay = property( 'vec3' );
  19732. const outgoingRayLight = property( 'vec3' );
  19733. /**
  19734. * VolumetricLightingModel class extends the LightingModel to implement volumetric lighting effects.
  19735. * This model calculates the scattering and transmittance of light through a volumetric medium.
  19736. * It dynamically adjusts the direction of the ray based on the camera and object positions.
  19737. * The model supports custom scattering and depth nodes to enhance the lighting effects.
  19738. *
  19739. * @augments LightingModel
  19740. */
  19741. class VolumetricLightingModel extends LightingModel {
  19742. constructor() {
  19743. super();
  19744. }
  19745. start( builder ) {
  19746. const { material } = builder;
  19747. const startPos = property( 'vec3' );
  19748. const endPos = property( 'vec3' );
  19749. // This approach dynamically changes the direction of the ray,
  19750. // prioritizing the ray from the camera to the object if it is inside the mesh, and from the object to the camera if it is far away.
  19751. If( cameraPosition.sub( positionWorld ).length().greaterThan( modelRadius.mul( 2 ) ), () => {
  19752. startPos.assign( cameraPosition );
  19753. endPos.assign( positionWorld );
  19754. } ).Else( () => {
  19755. startPos.assign( positionWorld );
  19756. endPos.assign( cameraPosition );
  19757. } );
  19758. //
  19759. const viewVector = endPos.sub( startPos );
  19760. const steps = uniform( 'int' ).onRenderUpdate( ( { material } ) => material.steps );
  19761. const stepSize = viewVector.length().div( steps ).toVar();
  19762. const rayDir = viewVector.normalize().toVar(); // TODO: toVar() should be automatic here ( in loop )
  19763. const distTravelled = float( 0.0 ).toVar();
  19764. const transmittance = vec3( 1 ).toVar();
  19765. if ( material.offsetNode ) {
  19766. // reduce banding
  19767. distTravelled.addAssign( material.offsetNode.mul( stepSize ) );
  19768. }
  19769. Loop( steps, () => {
  19770. const positionRay = startPos.add( rayDir.mul( distTravelled ) );
  19771. const positionViewRay = cameraViewMatrix.mul( vec4( positionRay, 1 ) ).xyz;
  19772. if ( material.depthNode !== null ) {
  19773. linearDepthRay.assign( linearDepth( viewZToPerspectiveDepth( positionViewRay.z, cameraNear, cameraFar ) ) );
  19774. builder.context.sceneDepthNode = linearDepth( material.depthNode ).toVar();
  19775. }
  19776. builder.context.positionWorld = positionRay;
  19777. builder.context.shadowPositionWorld = positionRay;
  19778. builder.context.positionView = positionViewRay;
  19779. scatteringDensity.assign( 0 );
  19780. let scatteringNode;
  19781. if ( material.scatteringNode ) {
  19782. scatteringNode = material.scatteringNode( {
  19783. positionRay
  19784. } );
  19785. }
  19786. super.start( builder );
  19787. if ( scatteringNode ) {
  19788. scatteringDensity.mulAssign( scatteringNode );
  19789. }
  19790. // beer's law
  19791. const falloff = scatteringDensity.mul( .01 ).negate().mul( stepSize ).exp();
  19792. transmittance.mulAssign( falloff );
  19793. // move along the ray
  19794. distTravelled.addAssign( stepSize );
  19795. } );
  19796. outgoingRayLight.addAssign( transmittance.saturate().oneMinus() );
  19797. }
  19798. scatteringLight( lightColor, builder ) {
  19799. const sceneDepthNode = builder.context.sceneDepthNode;
  19800. if ( sceneDepthNode ) {
  19801. If( sceneDepthNode.greaterThanEqual( linearDepthRay ), () => {
  19802. scatteringDensity.addAssign( lightColor );
  19803. } );
  19804. } else {
  19805. scatteringDensity.addAssign( lightColor );
  19806. }
  19807. }
  19808. direct( { lightNode, lightColor }, builder ) {
  19809. // Ignore lights with infinite distance
  19810. if ( lightNode.light.distance === undefined ) return;
  19811. // TODO: We need a viewportOpaque*() ( output, depth ) to fit with modern rendering approaches
  19812. const directLight = lightColor.xyz.toVar();
  19813. directLight.mulAssign( lightNode.shadowNode ); // it no should be necessary if used in the same render pass
  19814. this.scatteringLight( directLight, builder );
  19815. }
  19816. directRectArea( { lightColor, lightPosition, halfWidth, halfHeight }, builder ) {
  19817. const p0 = lightPosition.add( halfWidth ).sub( halfHeight ); // counterclockwise; light shines in local neg z direction
  19818. const p1 = lightPosition.sub( halfWidth ).sub( halfHeight );
  19819. const p2 = lightPosition.sub( halfWidth ).add( halfHeight );
  19820. const p3 = lightPosition.add( halfWidth ).add( halfHeight );
  19821. const P = builder.context.positionView;
  19822. const directLight = lightColor.xyz.mul( LTC_Evaluate_Volume( { P, p0, p1, p2, p3 } ) ).pow( 1.5 );
  19823. this.scatteringLight( directLight, builder );
  19824. }
  19825. finish( builder ) {
  19826. builder.context.outgoingLight.assign( outgoingRayLight );
  19827. }
  19828. }
  19829. /**
  19830. * Volume node material.
  19831. *
  19832. * @augments NodeMaterial
  19833. */
  19834. class VolumeNodeMaterial extends NodeMaterial {
  19835. static get type() {
  19836. return 'VolumeNodeMaterial';
  19837. }
  19838. /**
  19839. * Constructs a new volume node material.
  19840. *
  19841. * @param {Object} [parameters] - The configuration parameter.
  19842. */
  19843. constructor( parameters ) {
  19844. super();
  19845. /**
  19846. * This flag can be used for type testing.
  19847. *
  19848. * @type {boolean}
  19849. * @readonly
  19850. * @default true
  19851. */
  19852. this.isVolumeNodeMaterial = true;
  19853. /**
  19854. * Number of steps used for raymarching.
  19855. *
  19856. * @type {number}
  19857. * @default 25
  19858. */
  19859. this.steps = 25;
  19860. /**
  19861. * Offsets the distance a ray has been traveled through a volume.
  19862. * Can be used to implement dithering to reduce banding.
  19863. *
  19864. * @type {Node<float>}
  19865. * @default null
  19866. */
  19867. this.offsetNode = null;
  19868. /**
  19869. * Node used for scattering calculations.
  19870. *
  19871. * @type {Function|FunctionNode<vec4>}
  19872. * @default null
  19873. */
  19874. this.scatteringNode = null;
  19875. this.lights = true;
  19876. this.transparent = true;
  19877. this.side = BackSide;
  19878. this.depthTest = false;
  19879. this.depthWrite = false;
  19880. this.setValues( parameters );
  19881. }
  19882. setupLightingModel() {
  19883. return new VolumetricLightingModel();
  19884. }
  19885. }
  19886. /**
  19887. * This module manages the internal animation loop of the renderer.
  19888. *
  19889. * @private
  19890. */
  19891. class Animation {
  19892. /**
  19893. * Constructs a new animation loop management component.
  19894. *
  19895. * @param {Renderer} renderer - A reference to the main renderer.
  19896. * @param {Nodes} nodes - Renderer component for managing nodes related logic.
  19897. * @param {Info} info - Renderer component for managing metrics and monitoring data.
  19898. */
  19899. constructor( renderer, nodes, info ) {
  19900. /**
  19901. * A reference to the main renderer.
  19902. *
  19903. * @type {Renderer}
  19904. */
  19905. this.renderer = renderer;
  19906. /**
  19907. * Renderer component for managing nodes related logic.
  19908. *
  19909. * @type {Nodes}
  19910. */
  19911. this.nodes = nodes;
  19912. /**
  19913. * Renderer component for managing metrics and monitoring data.
  19914. *
  19915. * @type {Info}
  19916. */
  19917. this.info = info;
  19918. /**
  19919. * A reference to the context from `requestAnimationFrame()` can
  19920. * be called (usually `window`).
  19921. *
  19922. * @type {?(Window|XRSession)}
  19923. */
  19924. this._context = typeof self !== 'undefined' ? self : null;
  19925. /**
  19926. * The user-defined animation loop.
  19927. *
  19928. * @type {?Function}
  19929. * @default null
  19930. */
  19931. this._animationLoop = null;
  19932. /**
  19933. * The requestId which is returned from the `requestAnimationFrame()` call.
  19934. * Can be used to cancel the stop the animation loop.
  19935. *
  19936. * @type {?number}
  19937. * @default null
  19938. */
  19939. this._requestId = null;
  19940. }
  19941. /**
  19942. * Starts the internal animation loop.
  19943. */
  19944. start() {
  19945. const update = ( time, xrFrame ) => {
  19946. this._requestId = this._context.requestAnimationFrame( update );
  19947. if ( this.info.autoReset === true ) this.info.reset();
  19948. this.nodes.nodeFrame.update();
  19949. this.info.frame = this.nodes.nodeFrame.frameId;
  19950. this.renderer._inspector.begin();
  19951. if ( this._animationLoop !== null ) this._animationLoop( time, xrFrame );
  19952. this.renderer._inspector.finish();
  19953. };
  19954. update();
  19955. }
  19956. /**
  19957. * Stops the internal animation loop.
  19958. */
  19959. stop() {
  19960. this._context.cancelAnimationFrame( this._requestId );
  19961. this._requestId = null;
  19962. }
  19963. /**
  19964. * Returns the user-level animation loop.
  19965. *
  19966. * @return {?Function} The animation loop.
  19967. */
  19968. getAnimationLoop() {
  19969. return this._animationLoop;
  19970. }
  19971. /**
  19972. * Defines the user-level animation loop.
  19973. *
  19974. * @param {?Function} callback - The animation loop.
  19975. */
  19976. setAnimationLoop( callback ) {
  19977. this._animationLoop = callback;
  19978. }
  19979. /**
  19980. * Returns the animation context.
  19981. *
  19982. * @return {Window|XRSession} The animation context.
  19983. */
  19984. getContext() {
  19985. return this._context;
  19986. }
  19987. /**
  19988. * Defines the context in which `requestAnimationFrame()` is executed.
  19989. *
  19990. * @param {Window|XRSession} context - The context to set.
  19991. */
  19992. setContext( context ) {
  19993. this._context = context;
  19994. }
  19995. /**
  19996. * Frees all internal resources and stops the animation loop.
  19997. */
  19998. dispose() {
  19999. this.stop();
  20000. }
  20001. }
  20002. /**
  20003. * Data structure for the renderer. It allows defining values
  20004. * with chained, hierarchical keys. Keys are meant to be
  20005. * objects since the module internally works with Weak Maps
  20006. * for performance reasons.
  20007. *
  20008. * @private
  20009. */
  20010. class ChainMap {
  20011. /**
  20012. * Constructs a new Chain Map.
  20013. */
  20014. constructor() {
  20015. /**
  20016. * The root Weak Map.
  20017. *
  20018. * @type {WeakMap<Object, WeakMap>}
  20019. */
  20020. this.weakMap = new WeakMap();
  20021. }
  20022. /**
  20023. * Returns the value for the given array of keys.
  20024. *
  20025. * @param {Array<Object>} keys - List of keys.
  20026. * @return {any} The value. Returns `undefined` if no value was found.
  20027. */
  20028. get( keys ) {
  20029. let map = this.weakMap;
  20030. for ( let i = 0; i < keys.length - 1; i ++ ) {
  20031. map = map.get( keys[ i ] );
  20032. if ( map === undefined ) return undefined;
  20033. }
  20034. return map.get( keys[ keys.length - 1 ] );
  20035. }
  20036. /**
  20037. * Sets the value for the given keys.
  20038. *
  20039. * @param {Array<Object>} keys - List of keys.
  20040. * @param {any} value - The value to set.
  20041. * @return {ChainMap} A reference to this Chain Map.
  20042. */
  20043. set( keys, value ) {
  20044. let map = this.weakMap;
  20045. for ( let i = 0; i < keys.length - 1; i ++ ) {
  20046. const key = keys[ i ];
  20047. if ( map.has( key ) === false ) map.set( key, new WeakMap() );
  20048. map = map.get( key );
  20049. }
  20050. map.set( keys[ keys.length - 1 ], value );
  20051. return this;
  20052. }
  20053. /**
  20054. * Deletes a value for the given keys.
  20055. *
  20056. * @param {Array<Object>} keys - The keys.
  20057. * @return {boolean} Returns `true` if the value has been removed successfully and `false` if the value has not be found.
  20058. */
  20059. delete( keys ) {
  20060. let map = this.weakMap;
  20061. for ( let i = 0; i < keys.length - 1; i ++ ) {
  20062. map = map.get( keys[ i ] );
  20063. if ( map === undefined ) return false;
  20064. }
  20065. return map.delete( keys[ keys.length - 1 ] );
  20066. }
  20067. }
  20068. let _id$a = 0;
  20069. function getKeys( obj ) {
  20070. const keys = Object.keys( obj );
  20071. let proto = Object.getPrototypeOf( obj );
  20072. while ( proto ) {
  20073. const descriptors = Object.getOwnPropertyDescriptors( proto );
  20074. for ( const key in descriptors ) {
  20075. if ( descriptors[ key ] !== undefined ) {
  20076. const descriptor = descriptors[ key ];
  20077. if ( descriptor && typeof descriptor.get === 'function' ) {
  20078. keys.push( key );
  20079. }
  20080. }
  20081. }
  20082. proto = Object.getPrototypeOf( proto );
  20083. }
  20084. return keys;
  20085. }
  20086. /**
  20087. * A render object is the renderer's representation of single entity that gets drawn
  20088. * with a draw command. There is no unique mapping of render objects to 3D objects in the
  20089. * scene since render objects also depend from the used material, the current render context
  20090. * and the current scene's lighting.
  20091. *
  20092. * In general, the basic process of the renderer is:
  20093. *
  20094. * - Analyze the 3D objects in the scene and generate render lists containing render items.
  20095. * - Process the render lists by calling one or more render commands for each render item.
  20096. * - For each render command, request a render object and perform the draw.
  20097. *
  20098. * The module provides an interface to get data required for the draw command like the actual
  20099. * draw parameters or vertex buffers. It also holds a series of caching related methods since
  20100. * creating render objects should only be done when necessary.
  20101. *
  20102. * @private
  20103. */
  20104. class RenderObject {
  20105. /**
  20106. * Constructs a new render object.
  20107. *
  20108. * @param {Nodes} nodes - Renderer component for managing nodes related logic.
  20109. * @param {Geometries} geometries - Renderer component for managing geometries.
  20110. * @param {Renderer} renderer - The renderer.
  20111. * @param {Object3D} object - The 3D object.
  20112. * @param {Material} material - The 3D object's material.
  20113. * @param {Scene} scene - The scene the 3D object belongs to.
  20114. * @param {Camera} camera - The camera the object should be rendered with.
  20115. * @param {LightsNode} lightsNode - The lights node.
  20116. * @param {RenderContext} renderContext - The render context.
  20117. * @param {ClippingContext} clippingContext - The clipping context.
  20118. */
  20119. constructor( nodes, geometries, renderer, object, material, scene, camera, lightsNode, renderContext, clippingContext ) {
  20120. this.id = _id$a ++;
  20121. /**
  20122. * Renderer component for managing nodes related logic.
  20123. *
  20124. * @type {Nodes}
  20125. * @private
  20126. */
  20127. this._nodes = nodes;
  20128. /**
  20129. * Renderer component for managing geometries.
  20130. *
  20131. * @type {Geometries}
  20132. * @private
  20133. */
  20134. this._geometries = geometries;
  20135. /**
  20136. * The renderer.
  20137. *
  20138. * @type {Renderer}
  20139. */
  20140. this.renderer = renderer;
  20141. /**
  20142. * The 3D object.
  20143. *
  20144. * @type {Object3D}
  20145. */
  20146. this.object = object;
  20147. /**
  20148. * The 3D object's material.
  20149. *
  20150. * @type {Material}
  20151. */
  20152. this.material = material;
  20153. /**
  20154. * The scene the 3D object belongs to.
  20155. *
  20156. * @type {Scene}
  20157. */
  20158. this.scene = scene;
  20159. /**
  20160. * The camera the 3D object should be rendered with.
  20161. *
  20162. * @type {Camera}
  20163. */
  20164. this.camera = camera;
  20165. /**
  20166. * The lights node.
  20167. *
  20168. * @type {LightsNode}
  20169. */
  20170. this.lightsNode = lightsNode;
  20171. /**
  20172. * The render context.
  20173. *
  20174. * @type {RenderContext}
  20175. */
  20176. this.context = renderContext;
  20177. /**
  20178. * The 3D object's geometry.
  20179. *
  20180. * @type {BufferGeometry}
  20181. */
  20182. this.geometry = object.geometry;
  20183. /**
  20184. * The render object's version.
  20185. *
  20186. * @type {number}
  20187. */
  20188. this.version = material.version;
  20189. /**
  20190. * The draw range of the geometry.
  20191. *
  20192. * @type {?Object}
  20193. * @default null
  20194. */
  20195. this.drawRange = null;
  20196. /**
  20197. * An array holding the buffer attributes
  20198. * of the render object. This entails attribute
  20199. * definitions on geometry and node level.
  20200. *
  20201. * @type {?Array<BufferAttribute>}
  20202. * @default null
  20203. */
  20204. this.attributes = null;
  20205. /**
  20206. * An object holding the version of the
  20207. * attributes. The keys are the attribute names
  20208. * and the values are the attribute versions.
  20209. *
  20210. * @type {?Object<string, number>}
  20211. * @default null
  20212. */
  20213. this.attributesId = null;
  20214. /**
  20215. * A reference to a render pipeline the render
  20216. * object is processed with.
  20217. *
  20218. * @type {RenderPipeline}
  20219. * @default null
  20220. */
  20221. this.pipeline = null;
  20222. /**
  20223. * Only relevant for objects using
  20224. * multiple materials. This represents a group entry
  20225. * from the respective `BufferGeometry`.
  20226. *
  20227. * @type {?{start: number, count: number}}
  20228. * @default null
  20229. */
  20230. this.group = null;
  20231. /**
  20232. * An array holding the vertex buffers which can
  20233. * be buffer attributes but also interleaved buffers.
  20234. *
  20235. * @type {?Array<BufferAttribute|InterleavedBuffer>}
  20236. * @default null
  20237. */
  20238. this.vertexBuffers = null;
  20239. /**
  20240. * The parameters for the draw command.
  20241. *
  20242. * @type {?Object}
  20243. * @default null
  20244. */
  20245. this.drawParams = null;
  20246. /**
  20247. * If this render object is used inside a render bundle,
  20248. * this property points to the respective bundle group.
  20249. *
  20250. * @type {?BundleGroup}
  20251. * @default null
  20252. */
  20253. this.bundle = null;
  20254. /**
  20255. * The clipping context.
  20256. *
  20257. * @type {ClippingContext}
  20258. */
  20259. this.clippingContext = clippingContext;
  20260. /**
  20261. * The clipping context's cache key.
  20262. *
  20263. * @type {string}
  20264. */
  20265. this.clippingContextCacheKey = clippingContext !== null ? clippingContext.cacheKey : '';
  20266. /**
  20267. * The initial node cache key.
  20268. *
  20269. * @type {number}
  20270. */
  20271. this.initialNodesCacheKey = this.getDynamicCacheKey();
  20272. /**
  20273. * The initial cache key.
  20274. *
  20275. * @type {number}
  20276. */
  20277. this.initialCacheKey = this.getCacheKey();
  20278. /**
  20279. * The node builder state.
  20280. *
  20281. * @type {?NodeBuilderState}
  20282. * @private
  20283. * @default null
  20284. */
  20285. this._nodeBuilderState = null;
  20286. /**
  20287. * An array of bindings.
  20288. *
  20289. * @type {?Array<BindGroup>}
  20290. * @private
  20291. * @default null
  20292. */
  20293. this._bindings = null;
  20294. /**
  20295. * Reference to the node material observer.
  20296. *
  20297. * @type {?NodeMaterialObserver}
  20298. * @private
  20299. * @default null
  20300. */
  20301. this._monitor = null;
  20302. /**
  20303. * An event listener which is defined by `RenderObjects`. It performs
  20304. * clean up tasks when `dispose()` on this render object.
  20305. *
  20306. * @method
  20307. */
  20308. this.onDispose = null;
  20309. /**
  20310. * This flag can be used for type testing.
  20311. *
  20312. * @type {boolean}
  20313. * @readonly
  20314. * @default true
  20315. */
  20316. this.isRenderObject = true;
  20317. /**
  20318. * An event listener which is executed when `dispose()` is called on
  20319. * the material of this render object.
  20320. *
  20321. * @method
  20322. */
  20323. this.onMaterialDispose = () => {
  20324. this.dispose();
  20325. };
  20326. /**
  20327. * An event listener which is executed when `dispose()` is called on
  20328. * the geometry of this render object.
  20329. *
  20330. * @method
  20331. */
  20332. this.onGeometryDispose = () => {
  20333. // clear geometry cache attributes
  20334. this.attributes = null;
  20335. this.attributesId = null;
  20336. };
  20337. this.material.addEventListener( 'dispose', this.onMaterialDispose );
  20338. this.geometry.addEventListener( 'dispose', this.onGeometryDispose );
  20339. }
  20340. /**
  20341. * Updates the clipping context.
  20342. *
  20343. * @param {ClippingContext} context - The clipping context to set.
  20344. */
  20345. updateClipping( context ) {
  20346. this.clippingContext = context;
  20347. }
  20348. /**
  20349. * Whether the clipping requires an update or not.
  20350. *
  20351. * @type {boolean}
  20352. * @readonly
  20353. */
  20354. get clippingNeedsUpdate() {
  20355. if ( this.clippingContext === null || this.clippingContext.cacheKey === this.clippingContextCacheKey ) return false;
  20356. this.clippingContextCacheKey = this.clippingContext.cacheKey;
  20357. return true;
  20358. }
  20359. /**
  20360. * The number of clipping planes defined in context of hardware clipping.
  20361. *
  20362. * @type {number}
  20363. * @readonly
  20364. */
  20365. get hardwareClippingPlanes() {
  20366. return this.material.hardwareClipping === true ? this.clippingContext.unionClippingCount : 0;
  20367. }
  20368. /**
  20369. * Returns the node builder state of this render object.
  20370. *
  20371. * @return {NodeBuilderState} The node builder state.
  20372. */
  20373. getNodeBuilderState() {
  20374. return this._nodeBuilderState || ( this._nodeBuilderState = this._nodes.getForRender( this ) );
  20375. }
  20376. /**
  20377. * Returns the node material observer of this render object.
  20378. *
  20379. * @return {NodeMaterialObserver} The node material observer.
  20380. */
  20381. getMonitor() {
  20382. return this._monitor || ( this._monitor = this.getNodeBuilderState().observer );
  20383. }
  20384. /**
  20385. * Returns an array of bind groups of this render object.
  20386. *
  20387. * @return {Array<BindGroup>} The bindings.
  20388. */
  20389. getBindings() {
  20390. return this._bindings || ( this._bindings = this.getNodeBuilderState().createBindings() );
  20391. }
  20392. /**
  20393. * Returns a binding group by group name of this render object.
  20394. *
  20395. * @param {string} name - The name of the binding group.
  20396. * @return {?BindGroup} The bindings.
  20397. */
  20398. getBindingGroup( name ) {
  20399. for ( const bindingGroup of this.getBindings() ) {
  20400. if ( bindingGroup.name === name ) {
  20401. return bindingGroup;
  20402. }
  20403. }
  20404. }
  20405. /**
  20406. * Returns the index of the render object's geometry.
  20407. *
  20408. * @return {?BufferAttribute} The index. Returns `null` for non-indexed geometries.
  20409. */
  20410. getIndex() {
  20411. return this._geometries.getIndex( this );
  20412. }
  20413. /**
  20414. * Returns the indirect buffer attribute.
  20415. *
  20416. * @return {?BufferAttribute} The indirect attribute. `null` if no indirect drawing is used.
  20417. */
  20418. getIndirect() {
  20419. return this._geometries.getIndirect( this );
  20420. }
  20421. /**
  20422. * Returns an array that acts as a key for identifying the render object in a chain map.
  20423. *
  20424. * @return {Array<Object>} An array with object references.
  20425. */
  20426. getChainArray() {
  20427. return [ this.object, this.material, this.context, this.lightsNode ];
  20428. }
  20429. /**
  20430. * This method is used when the geometry of a 3D object has been exchanged and the
  20431. * respective render object now requires an update.
  20432. *
  20433. * @param {BufferGeometry} geometry - The geometry to set.
  20434. */
  20435. setGeometry( geometry ) {
  20436. this.geometry = geometry;
  20437. this.attributes = null;
  20438. this.attributesId = null;
  20439. }
  20440. /**
  20441. * Returns the buffer attributes of the render object. The returned array holds
  20442. * attribute definitions on geometry and node level.
  20443. *
  20444. * @return {Array<BufferAttribute>} An array with buffer attributes.
  20445. */
  20446. getAttributes() {
  20447. if ( this.attributes !== null ) return this.attributes;
  20448. const nodeAttributes = this.getNodeBuilderState().nodeAttributes;
  20449. const geometry = this.geometry;
  20450. const attributes = [];
  20451. const vertexBuffers = new Set();
  20452. const attributesId = {};
  20453. for ( const nodeAttribute of nodeAttributes ) {
  20454. let attribute;
  20455. if ( nodeAttribute.node && nodeAttribute.node.attribute ) {
  20456. // node attribute
  20457. attribute = nodeAttribute.node.attribute;
  20458. } else {
  20459. // geometry attribute
  20460. attribute = geometry.getAttribute( nodeAttribute.name );
  20461. attributesId[ nodeAttribute.name ] = attribute.version;
  20462. }
  20463. if ( attribute === undefined ) continue;
  20464. attributes.push( attribute );
  20465. const bufferAttribute = attribute.isInterleavedBufferAttribute ? attribute.data : attribute;
  20466. vertexBuffers.add( bufferAttribute );
  20467. }
  20468. this.attributes = attributes;
  20469. this.attributesId = attributesId;
  20470. this.vertexBuffers = Array.from( vertexBuffers.values() );
  20471. return attributes;
  20472. }
  20473. /**
  20474. * Returns the vertex buffers of the render object.
  20475. *
  20476. * @return {Array<BufferAttribute|InterleavedBuffer>} An array with buffer attribute or interleaved buffers.
  20477. */
  20478. getVertexBuffers() {
  20479. if ( this.vertexBuffers === null ) this.getAttributes();
  20480. return this.vertexBuffers;
  20481. }
  20482. /**
  20483. * Returns the draw parameters for the render object.
  20484. *
  20485. * @return {?{vertexCount: number, firstVertex: number, instanceCount: number, firstInstance: number}} The draw parameters.
  20486. */
  20487. getDrawParameters() {
  20488. const { object, material, geometry, group, drawRange } = this;
  20489. const drawParams = this.drawParams || ( this.drawParams = {
  20490. vertexCount: 0,
  20491. firstVertex: 0,
  20492. instanceCount: 0,
  20493. firstInstance: 0
  20494. } );
  20495. const index = this.getIndex();
  20496. const hasIndex = ( index !== null );
  20497. let instanceCount = 1;
  20498. if ( geometry.isInstancedBufferGeometry === true ) {
  20499. instanceCount = geometry.instanceCount;
  20500. } else if ( object.count !== undefined ) {
  20501. instanceCount = Math.max( 0, object.count );
  20502. }
  20503. if ( instanceCount === 0 ) return null;
  20504. drawParams.instanceCount = instanceCount;
  20505. if ( object.isBatchedMesh === true ) return drawParams;
  20506. let rangeFactor = 1;
  20507. if ( material.wireframe === true && ! object.isPoints && ! object.isLineSegments && ! object.isLine && ! object.isLineLoop ) {
  20508. rangeFactor = 2;
  20509. }
  20510. let firstVertex = drawRange.start * rangeFactor;
  20511. let lastVertex = ( drawRange.start + drawRange.count ) * rangeFactor;
  20512. if ( group !== null ) {
  20513. firstVertex = Math.max( firstVertex, group.start * rangeFactor );
  20514. lastVertex = Math.min( lastVertex, ( group.start + group.count ) * rangeFactor );
  20515. }
  20516. const position = geometry.attributes.position;
  20517. let itemCount = Infinity;
  20518. if ( hasIndex ) {
  20519. itemCount = index.count;
  20520. } else if ( position !== undefined && position !== null ) {
  20521. itemCount = position.count;
  20522. }
  20523. firstVertex = Math.max( firstVertex, 0 );
  20524. lastVertex = Math.min( lastVertex, itemCount );
  20525. const count = lastVertex - firstVertex;
  20526. if ( count < 0 || count === Infinity ) return null;
  20527. drawParams.vertexCount = count;
  20528. drawParams.firstVertex = firstVertex;
  20529. return drawParams;
  20530. }
  20531. /**
  20532. * Returns the render object's geometry cache key.
  20533. *
  20534. * The geometry cache key is part of the material cache key.
  20535. *
  20536. * @return {string} The geometry cache key.
  20537. */
  20538. getGeometryCacheKey() {
  20539. const { geometry } = this;
  20540. let cacheKey = '';
  20541. for ( const name of Object.keys( geometry.attributes ).sort() ) {
  20542. const attribute = geometry.attributes[ name ];
  20543. cacheKey += name + ',';
  20544. if ( attribute.data ) cacheKey += attribute.data.stride + ',';
  20545. if ( attribute.offset ) cacheKey += attribute.offset + ',';
  20546. if ( attribute.itemSize ) cacheKey += attribute.itemSize + ',';
  20547. if ( attribute.normalized ) cacheKey += 'n,';
  20548. }
  20549. // structural equality isn't sufficient for morph targets since the
  20550. // data are maintained in textures. only if the targets are all equal
  20551. // the texture and thus the instance of `MorphNode` can be shared.
  20552. for ( const name of Object.keys( geometry.morphAttributes ).sort() ) {
  20553. const targets = geometry.morphAttributes[ name ];
  20554. cacheKey += 'morph-' + name + ',';
  20555. for ( let i = 0, l = targets.length; i < l; i ++ ) {
  20556. const attribute = targets[ i ];
  20557. cacheKey += attribute.id + ',';
  20558. }
  20559. }
  20560. if ( geometry.index ) {
  20561. cacheKey += 'index,';
  20562. }
  20563. return cacheKey;
  20564. }
  20565. /**
  20566. * Returns the render object's material cache key.
  20567. *
  20568. * The material cache key is part of the render object cache key.
  20569. *
  20570. * @return {number} The material cache key.
  20571. */
  20572. getMaterialCacheKey() {
  20573. const { object, material, renderer } = this;
  20574. let cacheKey = material.customProgramCacheKey();
  20575. for ( const property of getKeys( material ) ) {
  20576. if ( /^(is[A-Z]|_)|^(visible|version|uuid|name|opacity|userData)$/.test( property ) ) continue;
  20577. const value = material[ property ];
  20578. let valueKey;
  20579. if ( value !== null ) {
  20580. // some material values require a formatting
  20581. const type = typeof value;
  20582. if ( type === 'number' ) {
  20583. valueKey = value !== 0 ? '1' : '0'; // Convert to on/off, important for clearcoat, transmission, etc
  20584. } else if ( type === 'object' ) {
  20585. valueKey = '{';
  20586. if ( value.isTexture ) {
  20587. valueKey += value.mapping;
  20588. // WebGPU must honor the sampler data because they are part of the bindings
  20589. if ( renderer.backend.isWebGPUBackend === true ) {
  20590. valueKey += value.magFilter;
  20591. valueKey += value.minFilter;
  20592. valueKey += value.wrapS;
  20593. valueKey += value.wrapT;
  20594. valueKey += value.wrapR;
  20595. }
  20596. }
  20597. valueKey += '}';
  20598. } else {
  20599. valueKey = String( value );
  20600. }
  20601. } else {
  20602. valueKey = String( value );
  20603. }
  20604. cacheKey += /*property + ':' +*/ valueKey + ',';
  20605. }
  20606. cacheKey += this.clippingContextCacheKey + ',';
  20607. if ( object.geometry ) {
  20608. cacheKey += this.getGeometryCacheKey();
  20609. }
  20610. if ( object.skeleton ) {
  20611. cacheKey += object.skeleton.bones.length + ',';
  20612. }
  20613. if ( object.isBatchedMesh ) {
  20614. cacheKey += object._matricesTexture.uuid + ',';
  20615. if ( object._colorsTexture !== null ) {
  20616. cacheKey += object._colorsTexture.uuid + ',';
  20617. }
  20618. }
  20619. if ( object.isInstancedMesh || object.count > 1 || Array.isArray( object.morphTargetInfluences ) ) {
  20620. // TODO: https://github.com/mrdoob/three.js/pull/29066#issuecomment-2269400850
  20621. cacheKey += object.uuid + ',';
  20622. }
  20623. cacheKey += object.receiveShadow + ',';
  20624. return hashString( cacheKey );
  20625. }
  20626. /**
  20627. * Whether the geometry requires an update or not.
  20628. *
  20629. * @type {boolean}
  20630. * @readonly
  20631. */
  20632. get needsGeometryUpdate() {
  20633. if ( this.geometry.id !== this.object.geometry.id ) return true;
  20634. if ( this.attributes !== null ) {
  20635. const attributesId = this.attributesId;
  20636. for ( const name in attributesId ) {
  20637. const attribute = this.geometry.getAttribute( name );
  20638. if ( attribute === undefined || attributesId[ name ] !== attribute.id ) {
  20639. return true;
  20640. }
  20641. }
  20642. }
  20643. return false;
  20644. }
  20645. /**
  20646. * Whether the render object requires an update or not.
  20647. *
  20648. * Note: There are two distinct places where render objects are checked for an update.
  20649. *
  20650. * 1. In `RenderObjects.get()` which is executed when the render object is request. This
  20651. * method checks the `needsUpdate` flag and recreates the render object if necessary.
  20652. * 2. In `Renderer._renderObjectDirect()` right after getting the render object via
  20653. * `RenderObjects.get()`. The render object's NodeMaterialObserver is then used to detect
  20654. * a need for a refresh due to material, geometry or object related value changes.
  20655. *
  20656. * TODO: Investigate if it's possible to merge both steps so there is only a single place
  20657. * that performs the 'needsUpdate' check.
  20658. *
  20659. * @type {boolean}
  20660. * @readonly
  20661. */
  20662. get needsUpdate() {
  20663. return /*this.object.static !== true &&*/ ( this.initialNodesCacheKey !== this.getDynamicCacheKey() || this.clippingNeedsUpdate );
  20664. }
  20665. /**
  20666. * Returns the dynamic cache key which represents a key that is computed per draw command.
  20667. *
  20668. * @return {number} The cache key.
  20669. */
  20670. getDynamicCacheKey() {
  20671. let cacheKey = 0;
  20672. // `Nodes.getCacheKey()` returns an environment cache key which is not relevant when
  20673. // the renderer is inside a shadow pass.
  20674. if ( this.material.isShadowPassMaterial !== true ) {
  20675. cacheKey = this._nodes.getCacheKey( this.scene, this.lightsNode );
  20676. }
  20677. if ( this.camera.isArrayCamera ) {
  20678. cacheKey = hash$1( cacheKey, this.camera.cameras.length );
  20679. }
  20680. if ( this.object.receiveShadow ) {
  20681. cacheKey = hash$1( cacheKey, 1 );
  20682. }
  20683. cacheKey = hash$1( cacheKey, this.camera.id );
  20684. return cacheKey;
  20685. }
  20686. /**
  20687. * Returns the render object's cache key.
  20688. *
  20689. * @return {number} The cache key.
  20690. */
  20691. getCacheKey() {
  20692. return this.getMaterialCacheKey() + this.getDynamicCacheKey();
  20693. }
  20694. /**
  20695. * Frees internal resources.
  20696. */
  20697. dispose() {
  20698. this.material.removeEventListener( 'dispose', this.onMaterialDispose );
  20699. this.geometry.removeEventListener( 'dispose', this.onGeometryDispose );
  20700. this.onDispose();
  20701. }
  20702. }
  20703. const _chainKeys$5 = [];
  20704. /**
  20705. * This module manages the render objects of the renderer.
  20706. *
  20707. * @private
  20708. */
  20709. class RenderObjects {
  20710. /**
  20711. * Constructs a new render object management component.
  20712. *
  20713. * @param {Renderer} renderer - The renderer.
  20714. * @param {Nodes} nodes - Renderer component for managing nodes related logic.
  20715. * @param {Geometries} geometries - Renderer component for managing geometries.
  20716. * @param {Pipelines} pipelines - Renderer component for managing pipelines.
  20717. * @param {Bindings} bindings - Renderer component for managing bindings.
  20718. * @param {Info} info - Renderer component for managing metrics and monitoring data.
  20719. */
  20720. constructor( renderer, nodes, geometries, pipelines, bindings, info ) {
  20721. /**
  20722. * The renderer.
  20723. *
  20724. * @type {Renderer}
  20725. */
  20726. this.renderer = renderer;
  20727. /**
  20728. * Renderer component for managing nodes related logic.
  20729. *
  20730. * @type {Nodes}
  20731. */
  20732. this.nodes = nodes;
  20733. /**
  20734. * Renderer component for managing geometries.
  20735. *
  20736. * @type {Geometries}
  20737. */
  20738. this.geometries = geometries;
  20739. /**
  20740. * Renderer component for managing pipelines.
  20741. *
  20742. * @type {Pipelines}
  20743. */
  20744. this.pipelines = pipelines;
  20745. /**
  20746. * Renderer component for managing bindings.
  20747. *
  20748. * @type {Bindings}
  20749. */
  20750. this.bindings = bindings;
  20751. /**
  20752. * Renderer component for managing metrics and monitoring data.
  20753. *
  20754. * @type {Info}
  20755. */
  20756. this.info = info;
  20757. /**
  20758. * A dictionary that manages render contexts in chain maps
  20759. * for each pass ID.
  20760. *
  20761. * @type {Object<string,ChainMap>}
  20762. */
  20763. this.chainMaps = {};
  20764. }
  20765. /**
  20766. * Returns a render object for the given object and state data.
  20767. *
  20768. * @param {Object3D} object - The 3D object.
  20769. * @param {Material} material - The 3D object's material.
  20770. * @param {Scene} scene - The scene the 3D object belongs to.
  20771. * @param {Camera} camera - The camera the 3D object should be rendered with.
  20772. * @param {LightsNode} lightsNode - The lights node.
  20773. * @param {RenderContext} renderContext - The render context.
  20774. * @param {ClippingContext} clippingContext - The clipping context.
  20775. * @param {string} [passId] - An optional ID for identifying the pass.
  20776. * @return {RenderObject} The render object.
  20777. */
  20778. get( object, material, scene, camera, lightsNode, renderContext, clippingContext, passId ) {
  20779. const chainMap = this.getChainMap( passId );
  20780. // reuse chainArray
  20781. _chainKeys$5[ 0 ] = object;
  20782. _chainKeys$5[ 1 ] = material;
  20783. _chainKeys$5[ 2 ] = renderContext;
  20784. _chainKeys$5[ 3 ] = lightsNode;
  20785. let renderObject = chainMap.get( _chainKeys$5 );
  20786. if ( renderObject === undefined ) {
  20787. renderObject = this.createRenderObject( this.nodes, this.geometries, this.renderer, object, material, scene, camera, lightsNode, renderContext, clippingContext, passId );
  20788. chainMap.set( _chainKeys$5, renderObject );
  20789. } else {
  20790. renderObject.updateClipping( clippingContext );
  20791. if ( renderObject.needsGeometryUpdate ) {
  20792. renderObject.setGeometry( object.geometry );
  20793. }
  20794. if ( renderObject.version !== material.version || renderObject.needsUpdate ) {
  20795. if ( renderObject.initialCacheKey !== renderObject.getCacheKey() ) {
  20796. renderObject.dispose();
  20797. renderObject = this.get( object, material, scene, camera, lightsNode, renderContext, clippingContext, passId );
  20798. } else {
  20799. renderObject.version = material.version;
  20800. }
  20801. }
  20802. }
  20803. _chainKeys$5.length = 0;
  20804. return renderObject;
  20805. }
  20806. /**
  20807. * Returns a chain map for the given pass ID.
  20808. *
  20809. * @param {string} [passId='default'] - The pass ID.
  20810. * @return {ChainMap} The chain map.
  20811. */
  20812. getChainMap( passId = 'default' ) {
  20813. return this.chainMaps[ passId ] || ( this.chainMaps[ passId ] = new ChainMap() );
  20814. }
  20815. /**
  20816. * Frees internal resources.
  20817. */
  20818. dispose() {
  20819. this.chainMaps = {};
  20820. }
  20821. /**
  20822. * Factory method for creating render objects with the given list of parameters.
  20823. *
  20824. * @param {Nodes} nodes - Renderer component for managing nodes related logic.
  20825. * @param {Geometries} geometries - Renderer component for managing geometries.
  20826. * @param {Renderer} renderer - The renderer.
  20827. * @param {Object3D} object - The 3D object.
  20828. * @param {Material} material - The object's material.
  20829. * @param {Scene} scene - The scene the 3D object belongs to.
  20830. * @param {Camera} camera - The camera the object should be rendered with.
  20831. * @param {LightsNode} lightsNode - The lights node.
  20832. * @param {RenderContext} renderContext - The render context.
  20833. * @param {ClippingContext} clippingContext - The clipping context.
  20834. * @param {string} [passId] - An optional ID for identifying the pass.
  20835. * @return {RenderObject} The render object.
  20836. */
  20837. createRenderObject( nodes, geometries, renderer, object, material, scene, camera, lightsNode, renderContext, clippingContext, passId ) {
  20838. const chainMap = this.getChainMap( passId );
  20839. const renderObject = new RenderObject( nodes, geometries, renderer, object, material, scene, camera, lightsNode, renderContext, clippingContext );
  20840. renderObject.onDispose = () => {
  20841. this.pipelines.delete( renderObject );
  20842. this.bindings.deleteForRender( renderObject );
  20843. this.nodes.delete( renderObject );
  20844. chainMap.delete( renderObject.getChainArray() );
  20845. };
  20846. return renderObject;
  20847. }
  20848. }
  20849. /**
  20850. * Data structure for the renderer. It is intended to manage
  20851. * data of objects in dictionaries.
  20852. *
  20853. * @private
  20854. */
  20855. class DataMap {
  20856. /**
  20857. * Constructs a new data map.
  20858. */
  20859. constructor() {
  20860. /**
  20861. * `DataMap` internally uses a weak map
  20862. * to manage its data.
  20863. *
  20864. * @type {WeakMap<Object, Object>}
  20865. */
  20866. this.data = new WeakMap();
  20867. }
  20868. /**
  20869. * Returns the dictionary for the given object.
  20870. *
  20871. * @param {Object} object - The object.
  20872. * @return {Object} The dictionary.
  20873. */
  20874. get( object ) {
  20875. let map = this.data.get( object );
  20876. if ( map === undefined ) {
  20877. map = {};
  20878. this.data.set( object, map );
  20879. }
  20880. return map;
  20881. }
  20882. /**
  20883. * Deletes the dictionary for the given object.
  20884. *
  20885. * @param {Object} object - The object.
  20886. * @return {?Object} The deleted dictionary.
  20887. */
  20888. delete( object ) {
  20889. let map = null;
  20890. if ( this.data.has( object ) ) {
  20891. map = this.data.get( object );
  20892. this.data.delete( object );
  20893. }
  20894. return map;
  20895. }
  20896. /**
  20897. * Returns `true` if the given object has a dictionary defined.
  20898. *
  20899. * @param {Object} object - The object to test.
  20900. * @return {boolean} Whether a dictionary is defined or not.
  20901. */
  20902. has( object ) {
  20903. return this.data.has( object );
  20904. }
  20905. /**
  20906. * Frees internal resources.
  20907. */
  20908. dispose() {
  20909. this.data = new WeakMap();
  20910. }
  20911. }
  20912. const AttributeType = {
  20913. VERTEX: 1,
  20914. INDEX: 2,
  20915. STORAGE: 3,
  20916. INDIRECT: 4
  20917. };
  20918. // size of a chunk in bytes (STD140 layout)
  20919. const GPU_CHUNK_BYTES = 16;
  20920. // @TODO: Move to src/constants.js
  20921. const BlendColorFactor = 211;
  20922. const OneMinusBlendColorFactor = 212;
  20923. /**
  20924. * This renderer module manages geometry attributes.
  20925. *
  20926. * @private
  20927. * @augments DataMap
  20928. */
  20929. class Attributes extends DataMap {
  20930. /**
  20931. * Constructs a new attribute management component.
  20932. *
  20933. * @param {Backend} backend - The renderer's backend.
  20934. */
  20935. constructor( backend ) {
  20936. super();
  20937. /**
  20938. * The renderer's backend.
  20939. *
  20940. * @type {Backend}
  20941. */
  20942. this.backend = backend;
  20943. }
  20944. /**
  20945. * Deletes the data for the given attribute.
  20946. *
  20947. * @param {BufferAttribute} attribute - The attribute.
  20948. * @return {?Object} The deleted attribute data.
  20949. */
  20950. delete( attribute ) {
  20951. const attributeData = super.delete( attribute );
  20952. if ( attributeData !== null ) {
  20953. this.backend.destroyAttribute( attribute );
  20954. }
  20955. return attributeData;
  20956. }
  20957. /**
  20958. * Updates the given attribute. This method creates attribute buffers
  20959. * for new attributes and updates data for existing ones.
  20960. *
  20961. * @param {BufferAttribute} attribute - The attribute to update.
  20962. * @param {number} type - The attribute type.
  20963. */
  20964. update( attribute, type ) {
  20965. const data = this.get( attribute );
  20966. if ( data.version === undefined ) {
  20967. if ( type === AttributeType.VERTEX ) {
  20968. this.backend.createAttribute( attribute );
  20969. } else if ( type === AttributeType.INDEX ) {
  20970. this.backend.createIndexAttribute( attribute );
  20971. } else if ( type === AttributeType.STORAGE ) {
  20972. this.backend.createStorageAttribute( attribute );
  20973. } else if ( type === AttributeType.INDIRECT ) {
  20974. this.backend.createIndirectStorageAttribute( attribute );
  20975. }
  20976. data.version = this._getBufferAttribute( attribute ).version;
  20977. } else {
  20978. const bufferAttribute = this._getBufferAttribute( attribute );
  20979. if ( data.version < bufferAttribute.version || bufferAttribute.usage === DynamicDrawUsage ) {
  20980. this.backend.updateAttribute( attribute );
  20981. data.version = bufferAttribute.version;
  20982. }
  20983. }
  20984. }
  20985. /**
  20986. * Utility method for handling interleaved buffer attributes correctly.
  20987. * To process them, their `InterleavedBuffer` is returned.
  20988. *
  20989. * @param {BufferAttribute} attribute - The attribute.
  20990. * @return {BufferAttribute|InterleavedBuffer}
  20991. */
  20992. _getBufferAttribute( attribute ) {
  20993. if ( attribute.isInterleavedBufferAttribute ) attribute = attribute.data;
  20994. return attribute;
  20995. }
  20996. }
  20997. /**
  20998. * Returns the wireframe version for the given geometry.
  20999. *
  21000. * @private
  21001. * @function
  21002. * @param {BufferGeometry} geometry - The geometry.
  21003. * @return {number} The version.
  21004. */
  21005. function getWireframeVersion( geometry ) {
  21006. return ( geometry.index !== null ) ? geometry.index.version : geometry.attributes.position.version;
  21007. }
  21008. /**
  21009. * Returns a wireframe index attribute for the given geometry.
  21010. *
  21011. * @private
  21012. * @function
  21013. * @param {BufferGeometry} geometry - The geometry.
  21014. * @return {BufferAttribute} The wireframe index attribute.
  21015. */
  21016. function getWireframeIndex( geometry ) {
  21017. const indices = [];
  21018. const geometryIndex = geometry.index;
  21019. const geometryPosition = geometry.attributes.position;
  21020. if ( geometryIndex !== null ) {
  21021. const array = geometryIndex.array;
  21022. for ( let i = 0, l = array.length; i < l; i += 3 ) {
  21023. const a = array[ i + 0 ];
  21024. const b = array[ i + 1 ];
  21025. const c = array[ i + 2 ];
  21026. indices.push( a, b, b, c, c, a );
  21027. }
  21028. } else {
  21029. const array = geometryPosition.array;
  21030. for ( let i = 0, l = ( array.length / 3 ) - 1; i < l; i += 3 ) {
  21031. const a = i + 0;
  21032. const b = i + 1;
  21033. const c = i + 2;
  21034. indices.push( a, b, b, c, c, a );
  21035. }
  21036. }
  21037. const attribute = new ( arrayNeedsUint32( indices ) ? Uint32BufferAttribute : Uint16BufferAttribute )( indices, 1 );
  21038. attribute.version = getWireframeVersion( geometry );
  21039. return attribute;
  21040. }
  21041. /**
  21042. * This renderer module manages geometries.
  21043. *
  21044. * @private
  21045. * @augments DataMap
  21046. */
  21047. class Geometries extends DataMap {
  21048. /**
  21049. * Constructs a new geometry management component.
  21050. *
  21051. * @param {Attributes} attributes - Renderer component for managing attributes.
  21052. * @param {Info} info - Renderer component for managing metrics and monitoring data.
  21053. */
  21054. constructor( attributes, info ) {
  21055. super();
  21056. /**
  21057. * Renderer component for managing attributes.
  21058. *
  21059. * @type {Attributes}
  21060. */
  21061. this.attributes = attributes;
  21062. /**
  21063. * Renderer component for managing metrics and monitoring data.
  21064. *
  21065. * @type {Info}
  21066. */
  21067. this.info = info;
  21068. /**
  21069. * Weak Map for managing attributes for wireframe rendering.
  21070. *
  21071. * @type {WeakMap<BufferGeometry,BufferAttribute>}
  21072. */
  21073. this.wireframes = new WeakMap();
  21074. /**
  21075. * This Weak Map is used to make sure buffer attributes are
  21076. * updated only once per render call.
  21077. *
  21078. * @type {WeakMap<BufferAttribute,number>}
  21079. */
  21080. this.attributeCall = new WeakMap();
  21081. /**
  21082. * Stores the event listeners attached to geometries.
  21083. *
  21084. * @private
  21085. * @type {Map<BufferGeometry,Function>}
  21086. */
  21087. this._geometryDisposeListeners = new Map();
  21088. }
  21089. /**
  21090. * Returns `true` if the given render object has an initialized geometry.
  21091. *
  21092. * @param {RenderObject} renderObject - The render object.
  21093. * @return {boolean} Whether if the given render object has an initialized geometry or not.
  21094. */
  21095. has( renderObject ) {
  21096. const geometry = renderObject.geometry;
  21097. return super.has( geometry ) && this.get( geometry ).initialized === true;
  21098. }
  21099. /**
  21100. * Prepares the geometry of the given render object for rendering.
  21101. *
  21102. * @param {RenderObject} renderObject - The render object.
  21103. */
  21104. updateForRender( renderObject ) {
  21105. if ( this.has( renderObject ) === false ) this.initGeometry( renderObject );
  21106. this.updateAttributes( renderObject );
  21107. }
  21108. /**
  21109. * Initializes the geometry of the given render object.
  21110. *
  21111. * @param {RenderObject} renderObject - The render object.
  21112. */
  21113. initGeometry( renderObject ) {
  21114. const geometry = renderObject.geometry;
  21115. const geometryData = this.get( geometry );
  21116. geometryData.initialized = true;
  21117. this.info.memory.geometries ++;
  21118. const onDispose = () => {
  21119. this.info.memory.geometries --;
  21120. const index = geometry.index;
  21121. const geometryAttributes = renderObject.getAttributes();
  21122. if ( index !== null ) {
  21123. this.attributes.delete( index );
  21124. }
  21125. for ( const geometryAttribute of geometryAttributes ) {
  21126. this.attributes.delete( geometryAttribute );
  21127. }
  21128. const wireframeAttribute = this.wireframes.get( geometry );
  21129. if ( wireframeAttribute !== undefined ) {
  21130. this.attributes.delete( wireframeAttribute );
  21131. }
  21132. geometry.removeEventListener( 'dispose', onDispose );
  21133. this._geometryDisposeListeners.delete( geometry );
  21134. };
  21135. geometry.addEventListener( 'dispose', onDispose );
  21136. // see #31798 why tracking separate remove listeners is required right now
  21137. // TODO: Re-evaluate how onDispose() is managed in this component
  21138. this._geometryDisposeListeners.set( geometry, onDispose );
  21139. }
  21140. /**
  21141. * Updates the geometry attributes of the given render object.
  21142. *
  21143. * @param {RenderObject} renderObject - The render object.
  21144. */
  21145. updateAttributes( renderObject ) {
  21146. // attributes
  21147. const attributes = renderObject.getAttributes();
  21148. for ( const attribute of attributes ) {
  21149. if ( attribute.isStorageBufferAttribute || attribute.isStorageInstancedBufferAttribute ) {
  21150. this.updateAttribute( attribute, AttributeType.STORAGE );
  21151. } else {
  21152. this.updateAttribute( attribute, AttributeType.VERTEX );
  21153. }
  21154. }
  21155. // indexes
  21156. const index = this.getIndex( renderObject );
  21157. if ( index !== null ) {
  21158. this.updateAttribute( index, AttributeType.INDEX );
  21159. }
  21160. // indirect
  21161. const indirect = renderObject.geometry.indirect;
  21162. if ( indirect !== null ) {
  21163. this.updateAttribute( indirect, AttributeType.INDIRECT );
  21164. }
  21165. }
  21166. /**
  21167. * Updates the given attribute.
  21168. *
  21169. * @param {BufferAttribute} attribute - The attribute to update.
  21170. * @param {number} type - The attribute type.
  21171. */
  21172. updateAttribute( attribute, type ) {
  21173. const callId = this.info.render.calls;
  21174. if ( ! attribute.isInterleavedBufferAttribute ) {
  21175. if ( this.attributeCall.get( attribute ) !== callId ) {
  21176. this.attributes.update( attribute, type );
  21177. this.attributeCall.set( attribute, callId );
  21178. }
  21179. } else {
  21180. if ( this.attributeCall.get( attribute ) === undefined ) {
  21181. this.attributes.update( attribute, type );
  21182. this.attributeCall.set( attribute, callId );
  21183. } else if ( this.attributeCall.get( attribute.data ) !== callId ) {
  21184. this.attributes.update( attribute, type );
  21185. this.attributeCall.set( attribute.data, callId );
  21186. this.attributeCall.set( attribute, callId );
  21187. }
  21188. }
  21189. }
  21190. /**
  21191. * Returns the indirect buffer attribute of the given render object.
  21192. *
  21193. * @param {RenderObject} renderObject - The render object.
  21194. * @return {?BufferAttribute} The indirect attribute. `null` if no indirect drawing is used.
  21195. */
  21196. getIndirect( renderObject ) {
  21197. return renderObject.geometry.indirect;
  21198. }
  21199. /**
  21200. * Returns the index of the given render object's geometry. This is implemented
  21201. * in a method to return a wireframe index if necessary.
  21202. *
  21203. * @param {RenderObject} renderObject - The render object.
  21204. * @return {?BufferAttribute} The index. Returns `null` for non-indexed geometries.
  21205. */
  21206. getIndex( renderObject ) {
  21207. const { geometry, material } = renderObject;
  21208. let index = geometry.index;
  21209. if ( material.wireframe === true ) {
  21210. const wireframes = this.wireframes;
  21211. let wireframeAttribute = wireframes.get( geometry );
  21212. if ( wireframeAttribute === undefined ) {
  21213. wireframeAttribute = getWireframeIndex( geometry );
  21214. wireframes.set( geometry, wireframeAttribute );
  21215. } else if ( wireframeAttribute.version !== getWireframeVersion( geometry ) ) {
  21216. this.attributes.delete( wireframeAttribute );
  21217. wireframeAttribute = getWireframeIndex( geometry );
  21218. wireframes.set( geometry, wireframeAttribute );
  21219. }
  21220. index = wireframeAttribute;
  21221. }
  21222. return index;
  21223. }
  21224. dispose() {
  21225. for ( const [ geometry, onDispose ] of this._geometryDisposeListeners.entries() ) {
  21226. geometry.removeEventListener( 'dispose', onDispose );
  21227. }
  21228. this._geometryDisposeListeners.clear();
  21229. }
  21230. }
  21231. /**
  21232. * This renderer module provides a series of statistical information
  21233. * about the GPU memory and the rendering process. Useful for debugging
  21234. * and monitoring.
  21235. */
  21236. class Info {
  21237. /**
  21238. * Constructs a new info component.
  21239. */
  21240. constructor() {
  21241. /**
  21242. * Whether frame related metrics should automatically
  21243. * be resetted or not. This property should be set to `false`
  21244. * by apps which manage their own animation loop. They must
  21245. * then call `renderer.info.reset()` once per frame manually.
  21246. *
  21247. * @type {boolean}
  21248. * @default true
  21249. */
  21250. this.autoReset = true;
  21251. /**
  21252. * The current frame ID. This ID is managed
  21253. * by `NodeFrame`.
  21254. *
  21255. * @type {number}
  21256. * @readonly
  21257. * @default 0
  21258. */
  21259. this.frame = 0;
  21260. /**
  21261. * The number of render calls since the
  21262. * app has been started.
  21263. *
  21264. * @type {number}
  21265. * @readonly
  21266. * @default 0
  21267. */
  21268. this.calls = 0;
  21269. /**
  21270. * Render related metrics.
  21271. *
  21272. * @type {Object}
  21273. * @readonly
  21274. * @property {number} calls - The number of render calls since the app has been started.
  21275. * @property {number} frameCalls - The number of render calls of the current frame.
  21276. * @property {number} drawCalls - The number of draw calls of the current frame.
  21277. * @property {number} triangles - The number of rendered triangle primitives of the current frame.
  21278. * @property {number} points - The number of rendered point primitives of the current frame.
  21279. * @property {number} lines - The number of rendered line primitives of the current frame.
  21280. * @property {number} timestamp - The timestamp of the frame.
  21281. */
  21282. this.render = {
  21283. calls: 0,
  21284. frameCalls: 0,
  21285. drawCalls: 0,
  21286. triangles: 0,
  21287. points: 0,
  21288. lines: 0,
  21289. timestamp: 0,
  21290. };
  21291. /**
  21292. * Compute related metrics.
  21293. *
  21294. * @type {Object}
  21295. * @readonly
  21296. * @property {number} calls - The number of compute calls since the app has been started.
  21297. * @property {number} frameCalls - The number of compute calls of the current frame.
  21298. * @property {number} timestamp - The timestamp of the frame when using `renderer.computeAsync()`.
  21299. */
  21300. this.compute = {
  21301. calls: 0,
  21302. frameCalls: 0,
  21303. timestamp: 0
  21304. };
  21305. /**
  21306. * Memory related metrics.
  21307. *
  21308. * @type {Object}
  21309. * @readonly
  21310. * @property {number} geometries - The number of active geometries.
  21311. * @property {number} frameCalls - The number of active textures.
  21312. */
  21313. this.memory = {
  21314. geometries: 0,
  21315. textures: 0
  21316. };
  21317. }
  21318. /**
  21319. * This method should be executed per draw call and updates the corresponding metrics.
  21320. *
  21321. * @param {Object3D} object - The 3D object that is going to be rendered.
  21322. * @param {number} count - The vertex or index count.
  21323. * @param {number} instanceCount - The instance count.
  21324. */
  21325. update( object, count, instanceCount ) {
  21326. this.render.drawCalls ++;
  21327. if ( object.isMesh || object.isSprite ) {
  21328. this.render.triangles += instanceCount * ( count / 3 );
  21329. } else if ( object.isPoints ) {
  21330. this.render.points += instanceCount * count;
  21331. } else if ( object.isLineSegments ) {
  21332. this.render.lines += instanceCount * ( count / 2 );
  21333. } else if ( object.isLine ) {
  21334. this.render.lines += instanceCount * ( count - 1 );
  21335. } else {
  21336. error( 'WebGPUInfo: Unknown object type.' );
  21337. }
  21338. }
  21339. /**
  21340. * Resets frame related metrics.
  21341. */
  21342. reset() {
  21343. this.render.drawCalls = 0;
  21344. this.render.frameCalls = 0;
  21345. this.compute.frameCalls = 0;
  21346. this.render.triangles = 0;
  21347. this.render.points = 0;
  21348. this.render.lines = 0;
  21349. }
  21350. /**
  21351. * Performs a complete reset of the object.
  21352. */
  21353. dispose() {
  21354. this.reset();
  21355. this.calls = 0;
  21356. this.render.calls = 0;
  21357. this.compute.calls = 0;
  21358. this.render.timestamp = 0;
  21359. this.compute.timestamp = 0;
  21360. this.memory.geometries = 0;
  21361. this.memory.textures = 0;
  21362. }
  21363. }
  21364. /**
  21365. * Abstract class for representing pipelines.
  21366. *
  21367. * @private
  21368. * @abstract
  21369. */
  21370. class Pipeline {
  21371. /**
  21372. * Constructs a new pipeline.
  21373. *
  21374. * @param {string} cacheKey - The pipeline's cache key.
  21375. */
  21376. constructor( cacheKey ) {
  21377. /**
  21378. * The pipeline's cache key.
  21379. *
  21380. * @type {string}
  21381. */
  21382. this.cacheKey = cacheKey;
  21383. /**
  21384. * How often the pipeline is currently in use.
  21385. *
  21386. * @type {number}
  21387. * @default 0
  21388. */
  21389. this.usedTimes = 0;
  21390. }
  21391. }
  21392. /**
  21393. * Class for representing render pipelines.
  21394. *
  21395. * @private
  21396. * @augments Pipeline
  21397. */
  21398. class RenderPipeline extends Pipeline {
  21399. /**
  21400. * Constructs a new render pipeline.
  21401. *
  21402. * @param {string} cacheKey - The pipeline's cache key.
  21403. * @param {ProgrammableStage} vertexProgram - The pipeline's vertex shader.
  21404. * @param {ProgrammableStage} fragmentProgram - The pipeline's fragment shader.
  21405. */
  21406. constructor( cacheKey, vertexProgram, fragmentProgram ) {
  21407. super( cacheKey );
  21408. /**
  21409. * The pipeline's vertex shader.
  21410. *
  21411. * @type {ProgrammableStage}
  21412. */
  21413. this.vertexProgram = vertexProgram;
  21414. /**
  21415. * The pipeline's fragment shader.
  21416. *
  21417. * @type {ProgrammableStage}
  21418. */
  21419. this.fragmentProgram = fragmentProgram;
  21420. }
  21421. }
  21422. /**
  21423. * Class for representing compute pipelines.
  21424. *
  21425. * @private
  21426. * @augments Pipeline
  21427. */
  21428. class ComputePipeline extends Pipeline {
  21429. /**
  21430. * Constructs a new render pipeline.
  21431. *
  21432. * @param {string} cacheKey - The pipeline's cache key.
  21433. * @param {ProgrammableStage} computeProgram - The pipeline's compute shader.
  21434. */
  21435. constructor( cacheKey, computeProgram ) {
  21436. super( cacheKey );
  21437. /**
  21438. * The pipeline's compute shader.
  21439. *
  21440. * @type {ProgrammableStage}
  21441. */
  21442. this.computeProgram = computeProgram;
  21443. /**
  21444. * This flag can be used for type testing.
  21445. *
  21446. * @type {boolean}
  21447. * @readonly
  21448. * @default true
  21449. */
  21450. this.isComputePipeline = true;
  21451. }
  21452. }
  21453. let _id$9 = 0;
  21454. /**
  21455. * Class for representing programmable stages which are vertex,
  21456. * fragment or compute shaders. Unlike fixed-function states (like blending),
  21457. * they represent the programmable part of a pipeline.
  21458. *
  21459. * @private
  21460. */
  21461. class ProgrammableStage {
  21462. /**
  21463. * Constructs a new programmable stage.
  21464. *
  21465. * @param {string} code - The shader code.
  21466. * @param {('vertex'|'fragment'|'compute')} stage - The type of stage.
  21467. * @param {string} name - The name of the shader.
  21468. * @param {?Array<Object>} [transforms=null] - The transforms (only relevant for compute stages with WebGL 2 which uses Transform Feedback).
  21469. * @param {?Array<Object>} [attributes=null] - The attributes (only relevant for compute stages with WebGL 2 which uses Transform Feedback).
  21470. */
  21471. constructor( code, stage, name, transforms = null, attributes = null ) {
  21472. /**
  21473. * The id of the programmable stage.
  21474. *
  21475. * @type {number}
  21476. */
  21477. this.id = _id$9 ++;
  21478. /**
  21479. * The shader code.
  21480. *
  21481. * @type {string}
  21482. */
  21483. this.code = code;
  21484. /**
  21485. * The type of stage.
  21486. *
  21487. * @type {string}
  21488. */
  21489. this.stage = stage;
  21490. /**
  21491. * The name of the stage.
  21492. * This is used for debugging purposes.
  21493. *
  21494. * @type {string}
  21495. */
  21496. this.name = name;
  21497. /**
  21498. * The transforms (only relevant for compute stages with WebGL 2 which uses Transform Feedback).
  21499. *
  21500. * @type {?Array<Object>}
  21501. */
  21502. this.transforms = transforms;
  21503. /**
  21504. * The attributes (only relevant for compute stages with WebGL 2 which uses Transform Feedback).
  21505. *
  21506. * @type {?Array<Object>}
  21507. */
  21508. this.attributes = attributes;
  21509. /**
  21510. * How often the programmable stage is currently in use.
  21511. *
  21512. * @type {number}
  21513. * @default 0
  21514. */
  21515. this.usedTimes = 0;
  21516. }
  21517. }
  21518. /**
  21519. * This renderer module manages the pipelines of the renderer.
  21520. *
  21521. * @private
  21522. * @augments DataMap
  21523. */
  21524. class Pipelines extends DataMap {
  21525. /**
  21526. * Constructs a new pipeline management component.
  21527. *
  21528. * @param {Backend} backend - The renderer's backend.
  21529. * @param {Nodes} nodes - Renderer component for managing nodes related logic.
  21530. */
  21531. constructor( backend, nodes ) {
  21532. super();
  21533. /**
  21534. * The renderer's backend.
  21535. *
  21536. * @type {Backend}
  21537. */
  21538. this.backend = backend;
  21539. /**
  21540. * Renderer component for managing nodes related logic.
  21541. *
  21542. * @type {Nodes}
  21543. */
  21544. this.nodes = nodes;
  21545. /**
  21546. * A references to the bindings management component.
  21547. * This reference will be set inside the `Bindings`
  21548. * constructor.
  21549. *
  21550. * @type {?Bindings}
  21551. * @default null
  21552. */
  21553. this.bindings = null;
  21554. /**
  21555. * Internal cache for maintaining pipelines.
  21556. * The key of the map is a cache key, the value the pipeline.
  21557. *
  21558. * @type {Map<string,Pipeline>}
  21559. */
  21560. this.caches = new Map();
  21561. /**
  21562. * This dictionary maintains for each shader stage type (vertex,
  21563. * fragment and compute) the programmable stage objects which
  21564. * represent the actual shader code.
  21565. *
  21566. * @type {Object<string,Map<string, ProgrammableStage>>}
  21567. */
  21568. this.programs = {
  21569. vertex: new Map(),
  21570. fragment: new Map(),
  21571. compute: new Map()
  21572. };
  21573. }
  21574. /**
  21575. * Returns a compute pipeline for the given compute node.
  21576. *
  21577. * @param {Node} computeNode - The compute node.
  21578. * @param {Array<BindGroup>} bindings - The bindings.
  21579. * @return {ComputePipeline} The compute pipeline.
  21580. */
  21581. getForCompute( computeNode, bindings ) {
  21582. const { backend } = this;
  21583. const data = this.get( computeNode );
  21584. if ( this._needsComputeUpdate( computeNode ) ) {
  21585. const previousPipeline = data.pipeline;
  21586. if ( previousPipeline ) {
  21587. previousPipeline.usedTimes --;
  21588. previousPipeline.computeProgram.usedTimes --;
  21589. }
  21590. // get shader
  21591. const nodeBuilderState = this.nodes.getForCompute( computeNode );
  21592. // programmable stage
  21593. let stageCompute = this.programs.compute.get( nodeBuilderState.computeShader );
  21594. if ( stageCompute === undefined ) {
  21595. if ( previousPipeline && previousPipeline.computeProgram.usedTimes === 0 ) this._releaseProgram( previousPipeline.computeProgram );
  21596. stageCompute = new ProgrammableStage( nodeBuilderState.computeShader, 'compute', computeNode.name, nodeBuilderState.transforms, nodeBuilderState.nodeAttributes );
  21597. this.programs.compute.set( nodeBuilderState.computeShader, stageCompute );
  21598. backend.createProgram( stageCompute );
  21599. }
  21600. // determine compute pipeline
  21601. const cacheKey = this._getComputeCacheKey( computeNode, stageCompute );
  21602. let pipeline = this.caches.get( cacheKey );
  21603. if ( pipeline === undefined ) {
  21604. if ( previousPipeline && previousPipeline.usedTimes === 0 ) this._releasePipeline( previousPipeline );
  21605. pipeline = this._getComputePipeline( computeNode, stageCompute, cacheKey, bindings );
  21606. }
  21607. // keep track of all used times
  21608. pipeline.usedTimes ++;
  21609. stageCompute.usedTimes ++;
  21610. //
  21611. data.version = computeNode.version;
  21612. data.pipeline = pipeline;
  21613. }
  21614. return data.pipeline;
  21615. }
  21616. /**
  21617. * Returns a render pipeline for the given render object.
  21618. *
  21619. * @param {RenderObject} renderObject - The render object.
  21620. * @param {?Array<Promise>} [promises=null] - An array of compilation promises which is only relevant in context of `Renderer.compileAsync()`.
  21621. * @return {RenderPipeline} The render pipeline.
  21622. */
  21623. getForRender( renderObject, promises = null ) {
  21624. const { backend } = this;
  21625. const data = this.get( renderObject );
  21626. if ( this._needsRenderUpdate( renderObject ) ) {
  21627. const previousPipeline = data.pipeline;
  21628. if ( previousPipeline ) {
  21629. previousPipeline.usedTimes --;
  21630. previousPipeline.vertexProgram.usedTimes --;
  21631. previousPipeline.fragmentProgram.usedTimes --;
  21632. }
  21633. // get shader
  21634. const nodeBuilderState = renderObject.getNodeBuilderState();
  21635. const name = renderObject.material ? renderObject.material.name : '';
  21636. // programmable stages
  21637. let stageVertex = this.programs.vertex.get( nodeBuilderState.vertexShader );
  21638. if ( stageVertex === undefined ) {
  21639. if ( previousPipeline && previousPipeline.vertexProgram.usedTimes === 0 ) this._releaseProgram( previousPipeline.vertexProgram );
  21640. stageVertex = new ProgrammableStage( nodeBuilderState.vertexShader, 'vertex', name );
  21641. this.programs.vertex.set( nodeBuilderState.vertexShader, stageVertex );
  21642. backend.createProgram( stageVertex );
  21643. }
  21644. let stageFragment = this.programs.fragment.get( nodeBuilderState.fragmentShader );
  21645. if ( stageFragment === undefined ) {
  21646. if ( previousPipeline && previousPipeline.fragmentProgram.usedTimes === 0 ) this._releaseProgram( previousPipeline.fragmentProgram );
  21647. stageFragment = new ProgrammableStage( nodeBuilderState.fragmentShader, 'fragment', name );
  21648. this.programs.fragment.set( nodeBuilderState.fragmentShader, stageFragment );
  21649. backend.createProgram( stageFragment );
  21650. }
  21651. // determine render pipeline
  21652. const cacheKey = this._getRenderCacheKey( renderObject, stageVertex, stageFragment );
  21653. let pipeline = this.caches.get( cacheKey );
  21654. if ( pipeline === undefined ) {
  21655. if ( previousPipeline && previousPipeline.usedTimes === 0 ) this._releasePipeline( previousPipeline );
  21656. pipeline = this._getRenderPipeline( renderObject, stageVertex, stageFragment, cacheKey, promises );
  21657. } else {
  21658. renderObject.pipeline = pipeline;
  21659. }
  21660. // keep track of all used times
  21661. pipeline.usedTimes ++;
  21662. stageVertex.usedTimes ++;
  21663. stageFragment.usedTimes ++;
  21664. //
  21665. data.pipeline = pipeline;
  21666. }
  21667. return data.pipeline;
  21668. }
  21669. /**
  21670. * Deletes the pipeline for the given render object.
  21671. *
  21672. * @param {RenderObject} object - The render object.
  21673. * @return {?Object} The deleted dictionary.
  21674. */
  21675. delete( object ) {
  21676. const pipeline = this.get( object ).pipeline;
  21677. if ( pipeline ) {
  21678. // pipeline
  21679. pipeline.usedTimes --;
  21680. if ( pipeline.usedTimes === 0 ) this._releasePipeline( pipeline );
  21681. // programs
  21682. if ( pipeline.isComputePipeline ) {
  21683. pipeline.computeProgram.usedTimes --;
  21684. if ( pipeline.computeProgram.usedTimes === 0 ) this._releaseProgram( pipeline.computeProgram );
  21685. } else {
  21686. pipeline.fragmentProgram.usedTimes --;
  21687. pipeline.vertexProgram.usedTimes --;
  21688. if ( pipeline.vertexProgram.usedTimes === 0 ) this._releaseProgram( pipeline.vertexProgram );
  21689. if ( pipeline.fragmentProgram.usedTimes === 0 ) this._releaseProgram( pipeline.fragmentProgram );
  21690. }
  21691. }
  21692. return super.delete( object );
  21693. }
  21694. /**
  21695. * Frees internal resources.
  21696. */
  21697. dispose() {
  21698. super.dispose();
  21699. this.caches = new Map();
  21700. this.programs = {
  21701. vertex: new Map(),
  21702. fragment: new Map(),
  21703. compute: new Map()
  21704. };
  21705. }
  21706. /**
  21707. * Updates the pipeline for the given render object.
  21708. *
  21709. * @param {RenderObject} renderObject - The render object.
  21710. */
  21711. updateForRender( renderObject ) {
  21712. this.getForRender( renderObject );
  21713. }
  21714. /**
  21715. * Returns a compute pipeline for the given parameters.
  21716. *
  21717. * @private
  21718. * @param {Node} computeNode - The compute node.
  21719. * @param {ProgrammableStage} stageCompute - The programmable stage representing the compute shader.
  21720. * @param {string} cacheKey - The cache key.
  21721. * @param {Array<BindGroup>} bindings - The bindings.
  21722. * @return {ComputePipeline} The compute pipeline.
  21723. */
  21724. _getComputePipeline( computeNode, stageCompute, cacheKey, bindings ) {
  21725. // check for existing pipeline
  21726. cacheKey = cacheKey || this._getComputeCacheKey( computeNode, stageCompute );
  21727. let pipeline = this.caches.get( cacheKey );
  21728. if ( pipeline === undefined ) {
  21729. pipeline = new ComputePipeline( cacheKey, stageCompute );
  21730. this.caches.set( cacheKey, pipeline );
  21731. this.backend.createComputePipeline( pipeline, bindings );
  21732. }
  21733. return pipeline;
  21734. }
  21735. /**
  21736. * Returns a render pipeline for the given parameters.
  21737. *
  21738. * @private
  21739. * @param {RenderObject} renderObject - The render object.
  21740. * @param {ProgrammableStage} stageVertex - The programmable stage representing the vertex shader.
  21741. * @param {ProgrammableStage} stageFragment - The programmable stage representing the fragment shader.
  21742. * @param {string} cacheKey - The cache key.
  21743. * @param {?Array<Promise>} promises - An array of compilation promises which is only relevant in context of `Renderer.compileAsync()`.
  21744. * @return {ComputePipeline} The compute pipeline.
  21745. */
  21746. _getRenderPipeline( renderObject, stageVertex, stageFragment, cacheKey, promises ) {
  21747. // check for existing pipeline
  21748. cacheKey = cacheKey || this._getRenderCacheKey( renderObject, stageVertex, stageFragment );
  21749. let pipeline = this.caches.get( cacheKey );
  21750. if ( pipeline === undefined ) {
  21751. pipeline = new RenderPipeline( cacheKey, stageVertex, stageFragment );
  21752. this.caches.set( cacheKey, pipeline );
  21753. renderObject.pipeline = pipeline;
  21754. // The `promises` array is `null` by default and only set to an empty array when
  21755. // `Renderer.compileAsync()` is used. The next call actually fills the array with
  21756. // pending promises that resolve when the render pipelines are ready for rendering.
  21757. this.backend.createRenderPipeline( renderObject, promises );
  21758. }
  21759. return pipeline;
  21760. }
  21761. /**
  21762. * Computes a cache key representing a compute pipeline.
  21763. *
  21764. * @private
  21765. * @param {Node} computeNode - The compute node.
  21766. * @param {ProgrammableStage} stageCompute - The programmable stage representing the compute shader.
  21767. * @return {string} The cache key.
  21768. */
  21769. _getComputeCacheKey( computeNode, stageCompute ) {
  21770. return computeNode.id + ',' + stageCompute.id;
  21771. }
  21772. /**
  21773. * Computes a cache key representing a render pipeline.
  21774. *
  21775. * @private
  21776. * @param {RenderObject} renderObject - The render object.
  21777. * @param {ProgrammableStage} stageVertex - The programmable stage representing the vertex shader.
  21778. * @param {ProgrammableStage} stageFragment - The programmable stage representing the fragment shader.
  21779. * @return {string} The cache key.
  21780. */
  21781. _getRenderCacheKey( renderObject, stageVertex, stageFragment ) {
  21782. return stageVertex.id + ',' + stageFragment.id + ',' + this.backend.getRenderCacheKey( renderObject );
  21783. }
  21784. /**
  21785. * Releases the given pipeline.
  21786. *
  21787. * @private
  21788. * @param {Pipeline} pipeline - The pipeline to release.
  21789. */
  21790. _releasePipeline( pipeline ) {
  21791. this.caches.delete( pipeline.cacheKey );
  21792. }
  21793. /**
  21794. * Releases the shader program.
  21795. *
  21796. * @private
  21797. * @param {Object} program - The shader program to release.
  21798. */
  21799. _releaseProgram( program ) {
  21800. const code = program.code;
  21801. const stage = program.stage;
  21802. this.programs[ stage ].delete( code );
  21803. }
  21804. /**
  21805. * Returns `true` if the compute pipeline for the given compute node requires an update.
  21806. *
  21807. * @private
  21808. * @param {Node} computeNode - The compute node.
  21809. * @return {boolean} Whether the compute pipeline for the given compute node requires an update or not.
  21810. */
  21811. _needsComputeUpdate( computeNode ) {
  21812. const data = this.get( computeNode );
  21813. return data.pipeline === undefined || data.version !== computeNode.version;
  21814. }
  21815. /**
  21816. * Returns `true` if the render pipeline for the given render object requires an update.
  21817. *
  21818. * @private
  21819. * @param {RenderObject} renderObject - The render object.
  21820. * @return {boolean} Whether the render object for the given render object requires an update or not.
  21821. */
  21822. _needsRenderUpdate( renderObject ) {
  21823. const data = this.get( renderObject );
  21824. return data.pipeline === undefined || this.backend.needsRenderUpdate( renderObject );
  21825. }
  21826. }
  21827. /**
  21828. * This renderer module manages the bindings of the renderer.
  21829. *
  21830. * @private
  21831. * @augments DataMap
  21832. */
  21833. class Bindings extends DataMap {
  21834. /**
  21835. * Constructs a new bindings management component.
  21836. *
  21837. * @param {Backend} backend - The renderer's backend.
  21838. * @param {Nodes} nodes - Renderer component for managing nodes related logic.
  21839. * @param {Textures} textures - Renderer component for managing textures.
  21840. * @param {Attributes} attributes - Renderer component for managing attributes.
  21841. * @param {Pipelines} pipelines - Renderer component for managing pipelines.
  21842. * @param {Info} info - Renderer component for managing metrics and monitoring data.
  21843. */
  21844. constructor( backend, nodes, textures, attributes, pipelines, info ) {
  21845. super();
  21846. /**
  21847. * The renderer's backend.
  21848. *
  21849. * @type {Backend}
  21850. */
  21851. this.backend = backend;
  21852. /**
  21853. * Renderer component for managing textures.
  21854. *
  21855. * @type {Textures}
  21856. */
  21857. this.textures = textures;
  21858. /**
  21859. * Renderer component for managing pipelines.
  21860. *
  21861. * @type {Pipelines}
  21862. */
  21863. this.pipelines = pipelines;
  21864. /**
  21865. * Renderer component for managing attributes.
  21866. *
  21867. * @type {Attributes}
  21868. */
  21869. this.attributes = attributes;
  21870. /**
  21871. * Renderer component for managing nodes related logic.
  21872. *
  21873. * @type {Nodes}
  21874. */
  21875. this.nodes = nodes;
  21876. /**
  21877. * Renderer component for managing metrics and monitoring data.
  21878. *
  21879. * @type {Info}
  21880. */
  21881. this.info = info;
  21882. this.pipelines.bindings = this; // assign bindings to pipelines
  21883. }
  21884. /**
  21885. * Returns the bind groups for the given render object.
  21886. *
  21887. * @param {RenderObject} renderObject - The render object.
  21888. * @return {Array<BindGroup>} The bind groups.
  21889. */
  21890. getForRender( renderObject ) {
  21891. const bindings = renderObject.getBindings();
  21892. for ( const bindGroup of bindings ) {
  21893. const groupData = this.get( bindGroup );
  21894. if ( groupData.bindGroup === undefined ) {
  21895. // each object defines an array of bindings (ubos, textures, samplers etc.)
  21896. this._init( bindGroup );
  21897. this.backend.createBindings( bindGroup, bindings, 0 );
  21898. groupData.bindGroup = bindGroup;
  21899. }
  21900. }
  21901. return bindings;
  21902. }
  21903. /**
  21904. * Returns the bind groups for the given compute node.
  21905. *
  21906. * @param {Node} computeNode - The compute node.
  21907. * @return {Array<BindGroup>} The bind groups.
  21908. */
  21909. getForCompute( computeNode ) {
  21910. const bindings = this.nodes.getForCompute( computeNode ).bindings;
  21911. for ( const bindGroup of bindings ) {
  21912. const groupData = this.get( bindGroup );
  21913. if ( groupData.bindGroup === undefined ) {
  21914. this._init( bindGroup );
  21915. this.backend.createBindings( bindGroup, bindings, 0 );
  21916. groupData.bindGroup = bindGroup;
  21917. }
  21918. }
  21919. return bindings;
  21920. }
  21921. /**
  21922. * Updates the bindings for the given compute node.
  21923. *
  21924. * @param {Node} computeNode - The compute node.
  21925. */
  21926. updateForCompute( computeNode ) {
  21927. this._updateBindings( this.getForCompute( computeNode ) );
  21928. }
  21929. /**
  21930. * Updates the bindings for the given render object.
  21931. *
  21932. * @param {RenderObject} renderObject - The render object.
  21933. */
  21934. updateForRender( renderObject ) {
  21935. this._updateBindings( this.getForRender( renderObject ) );
  21936. }
  21937. /**
  21938. * Deletes the bindings for the given compute node.
  21939. *
  21940. * @param {Node} computeNode - The compute node.
  21941. */
  21942. deleteForCompute( computeNode ) {
  21943. const bindings = this.nodes.getForCompute( computeNode ).bindings;
  21944. for ( const bindGroup of bindings ) {
  21945. this.delete( bindGroup );
  21946. }
  21947. }
  21948. /**
  21949. * Deletes the bindings for the given renderObject node.
  21950. *
  21951. * @param {RenderObject} renderObject - The renderObject.
  21952. */
  21953. deleteForRender( renderObject ) {
  21954. const bindings = renderObject.getBindings();
  21955. for ( const bindGroup of bindings ) {
  21956. this.delete( bindGroup );
  21957. }
  21958. }
  21959. /**
  21960. * Updates the given array of bindings.
  21961. *
  21962. * @param {Array<BindGroup>} bindings - The bind groups.
  21963. */
  21964. _updateBindings( bindings ) {
  21965. for ( const bindGroup of bindings ) {
  21966. this._update( bindGroup, bindings );
  21967. }
  21968. }
  21969. /**
  21970. * Initializes the given bind group.
  21971. *
  21972. * @param {BindGroup} bindGroup - The bind group to initialize.
  21973. */
  21974. _init( bindGroup ) {
  21975. for ( const binding of bindGroup.bindings ) {
  21976. if ( binding.isSampledTexture ) {
  21977. this.textures.updateTexture( binding.texture );
  21978. } else if ( binding.isSampler ) {
  21979. this.textures.updateSampler( binding.texture );
  21980. } else if ( binding.isStorageBuffer ) {
  21981. const attribute = binding.attribute;
  21982. const attributeType = attribute.isIndirectStorageBufferAttribute ? AttributeType.INDIRECT : AttributeType.STORAGE;
  21983. this.attributes.update( attribute, attributeType );
  21984. }
  21985. }
  21986. }
  21987. /**
  21988. * Updates the given bind group.
  21989. *
  21990. * @param {BindGroup} bindGroup - The bind group to update.
  21991. * @param {Array<BindGroup>} bindings - The bind groups.
  21992. */
  21993. _update( bindGroup, bindings ) {
  21994. const { backend } = this;
  21995. let needsBindingsUpdate = false;
  21996. let cacheBindings = true;
  21997. let cacheIndex = 0;
  21998. let version = 0;
  21999. // iterate over all bindings and check if buffer updates or a new binding group is required
  22000. for ( const binding of bindGroup.bindings ) {
  22001. if ( binding.isNodeUniformsGroup ) {
  22002. const updated = this.nodes.updateGroup( binding );
  22003. // every uniforms group is a uniform buffer. So if no update is required,
  22004. // we move one with the next binding. Otherwise the next if block will update the group.
  22005. if ( updated === false ) continue;
  22006. }
  22007. if ( binding.isStorageBuffer ) {
  22008. const attribute = binding.attribute;
  22009. const attributeType = attribute.isIndirectStorageBufferAttribute ? AttributeType.INDIRECT : AttributeType.STORAGE;
  22010. this.attributes.update( attribute, attributeType );
  22011. }
  22012. if ( binding.isUniformBuffer ) {
  22013. const updated = binding.update();
  22014. if ( updated ) {
  22015. backend.updateBinding( binding );
  22016. }
  22017. } else if ( binding.isSampledTexture ) {
  22018. const updated = binding.update();
  22019. // get the texture data after the update, to sync the texture reference from node
  22020. const texture = binding.texture;
  22021. const texturesTextureData = this.textures.get( texture );
  22022. if ( updated ) {
  22023. // version: update the texture data or create a new one
  22024. this.textures.updateTexture( texture );
  22025. // generation: update the bindings if a new texture has been created
  22026. if ( binding.generation !== texturesTextureData.generation ) {
  22027. binding.generation = texturesTextureData.generation;
  22028. needsBindingsUpdate = true;
  22029. cacheBindings = false;
  22030. }
  22031. }
  22032. const textureData = backend.get( texture );
  22033. if ( textureData.externalTexture !== undefined || texturesTextureData.isDefaultTexture ) {
  22034. cacheBindings = false;
  22035. } else {
  22036. cacheIndex = cacheIndex * 10 + texture.id;
  22037. version += texture.version;
  22038. }
  22039. if ( texture.isStorageTexture === true && texture.mipmapsAutoUpdate === true ) {
  22040. const textureData = this.get( texture );
  22041. if ( binding.store === true ) {
  22042. textureData.needsMipmap = true;
  22043. } else if ( this.textures.needsMipmaps( texture ) && textureData.needsMipmap === true ) {
  22044. this.backend.generateMipmaps( texture );
  22045. textureData.needsMipmap = false;
  22046. }
  22047. }
  22048. } else if ( binding.isSampler ) {
  22049. const updated = binding.update();
  22050. if ( updated ) {
  22051. const samplerKey = this.textures.updateSampler( binding.texture );
  22052. if ( binding.samplerKey !== samplerKey ) {
  22053. binding.samplerKey = samplerKey;
  22054. needsBindingsUpdate = true;
  22055. cacheBindings = false;
  22056. }
  22057. }
  22058. }
  22059. }
  22060. if ( needsBindingsUpdate === true ) {
  22061. this.backend.updateBindings( bindGroup, bindings, cacheBindings ? cacheIndex : 0, version );
  22062. }
  22063. }
  22064. }
  22065. /**
  22066. * Default sorting function for opaque render items.
  22067. *
  22068. * @private
  22069. * @function
  22070. * @param {Object} a - The first render item.
  22071. * @param {Object} b - The second render item.
  22072. * @return {number} A numeric value which defines the sort order.
  22073. */
  22074. function painterSortStable( a, b ) {
  22075. if ( a.groupOrder !== b.groupOrder ) {
  22076. return a.groupOrder - b.groupOrder;
  22077. } else if ( a.renderOrder !== b.renderOrder ) {
  22078. return a.renderOrder - b.renderOrder;
  22079. } else if ( a.z !== b.z ) {
  22080. return a.z - b.z;
  22081. } else {
  22082. return a.id - b.id;
  22083. }
  22084. }
  22085. /**
  22086. * Default sorting function for transparent render items.
  22087. *
  22088. * @private
  22089. * @function
  22090. * @param {Object} a - The first render item.
  22091. * @param {Object} b - The second render item.
  22092. * @return {number} A numeric value which defines the sort order.
  22093. */
  22094. function reversePainterSortStable( a, b ) {
  22095. if ( a.groupOrder !== b.groupOrder ) {
  22096. return a.groupOrder - b.groupOrder;
  22097. } else if ( a.renderOrder !== b.renderOrder ) {
  22098. return a.renderOrder - b.renderOrder;
  22099. } else if ( a.z !== b.z ) {
  22100. return b.z - a.z;
  22101. } else {
  22102. return a.id - b.id;
  22103. }
  22104. }
  22105. /**
  22106. * Returns `true` if the given transparent material requires a double pass.
  22107. *
  22108. * @private
  22109. * @function
  22110. * @param {Material} material - The transparent material.
  22111. * @return {boolean} Whether the given material requires a double pass or not.
  22112. */
  22113. function needsDoublePass( material ) {
  22114. const hasTransmission = material.transmission > 0 || ( material.transmissionNode && material.transmissionNode.isNode );
  22115. return hasTransmission && material.side === DoubleSide && material.forceSinglePass === false;
  22116. }
  22117. /**
  22118. * When the renderer analyzes the scene at the beginning of a render call,
  22119. * it stores 3D object for further processing in render lists. Depending on the
  22120. * properties of a 3D objects (like their transformation or material state), the
  22121. * objects are maintained in ordered lists for the actual rendering.
  22122. *
  22123. * Render lists are unique per scene and camera combination.
  22124. *
  22125. * @private
  22126. * @augments Pipeline
  22127. */
  22128. class RenderList {
  22129. /**
  22130. * Constructs a render list.
  22131. *
  22132. * @param {Lighting} lighting - The lighting management component.
  22133. * @param {Scene} scene - The scene.
  22134. * @param {Camera} camera - The camera the scene is rendered with.
  22135. */
  22136. constructor( lighting, scene, camera ) {
  22137. /**
  22138. * 3D objects are transformed into render items and stored in this array.
  22139. *
  22140. * @type {Array<Object>}
  22141. */
  22142. this.renderItems = [];
  22143. /**
  22144. * The current render items index.
  22145. *
  22146. * @type {number}
  22147. * @default 0
  22148. */
  22149. this.renderItemsIndex = 0;
  22150. /**
  22151. * A list with opaque render items.
  22152. *
  22153. * @type {Array<Object>}
  22154. */
  22155. this.opaque = [];
  22156. /**
  22157. * A list with transparent render items which require
  22158. * double pass rendering (e.g. transmissive objects).
  22159. *
  22160. * @type {Array<Object>}
  22161. */
  22162. this.transparentDoublePass = [];
  22163. /**
  22164. * A list with transparent render items.
  22165. *
  22166. * @type {Array<Object>}
  22167. */
  22168. this.transparent = [];
  22169. /**
  22170. * A list with transparent render bundle data.
  22171. *
  22172. * @type {Array<Object>}
  22173. */
  22174. this.bundles = [];
  22175. /**
  22176. * The render list's lights node. This node is later
  22177. * relevant for the actual analytical light nodes which
  22178. * compute the scene's lighting in the shader.
  22179. *
  22180. * @type {LightsNode}
  22181. */
  22182. this.lightsNode = lighting.getNode( scene, camera );
  22183. /**
  22184. * The scene's lights stored in an array. This array
  22185. * is used to setup the lights node.
  22186. *
  22187. * @type {Array<Light>}
  22188. */
  22189. this.lightsArray = [];
  22190. /**
  22191. * The scene.
  22192. *
  22193. * @type {Scene}
  22194. */
  22195. this.scene = scene;
  22196. /**
  22197. * The camera the scene is rendered with.
  22198. *
  22199. * @type {Camera}
  22200. */
  22201. this.camera = camera;
  22202. /**
  22203. * How many objects perform occlusion query tests.
  22204. *
  22205. * @type {number}
  22206. * @default 0
  22207. */
  22208. this.occlusionQueryCount = 0;
  22209. }
  22210. /**
  22211. * This method is called right at the beginning of a render call
  22212. * before the scene is analyzed. It prepares the internal data
  22213. * structures for the upcoming render lists generation.
  22214. *
  22215. * @return {RenderList} A reference to this render list.
  22216. */
  22217. begin() {
  22218. this.renderItemsIndex = 0;
  22219. this.opaque.length = 0;
  22220. this.transparentDoublePass.length = 0;
  22221. this.transparent.length = 0;
  22222. this.bundles.length = 0;
  22223. this.lightsArray.length = 0;
  22224. this.occlusionQueryCount = 0;
  22225. return this;
  22226. }
  22227. /**
  22228. * Returns a render item for the giving render item state. The state is defined
  22229. * by a series of object-related parameters.
  22230. *
  22231. * The method avoids object creation by holding render items and reusing them in
  22232. * subsequent render calls (just with different property values).
  22233. *
  22234. * @param {Object3D} object - The 3D object.
  22235. * @param {BufferGeometry} geometry - The 3D object's geometry.
  22236. * @param {Material} material - The 3D object's material.
  22237. * @param {number} groupOrder - The current group order.
  22238. * @param {number} z - Th 3D object's depth value (z value in clip space).
  22239. * @param {?number} group - {?Object} group - Only relevant for objects using multiple materials. This represents a group entry from the respective `BufferGeometry`.
  22240. * @param {ClippingContext} clippingContext - The current clipping context.
  22241. * @return {Object} The render item.
  22242. */
  22243. getNextRenderItem( object, geometry, material, groupOrder, z, group, clippingContext ) {
  22244. let renderItem = this.renderItems[ this.renderItemsIndex ];
  22245. if ( renderItem === undefined ) {
  22246. renderItem = {
  22247. id: object.id,
  22248. object: object,
  22249. geometry: geometry,
  22250. material: material,
  22251. groupOrder: groupOrder,
  22252. renderOrder: object.renderOrder,
  22253. z: z,
  22254. group: group,
  22255. clippingContext: clippingContext
  22256. };
  22257. this.renderItems[ this.renderItemsIndex ] = renderItem;
  22258. } else {
  22259. renderItem.id = object.id;
  22260. renderItem.object = object;
  22261. renderItem.geometry = geometry;
  22262. renderItem.material = material;
  22263. renderItem.groupOrder = groupOrder;
  22264. renderItem.renderOrder = object.renderOrder;
  22265. renderItem.z = z;
  22266. renderItem.group = group;
  22267. renderItem.clippingContext = clippingContext;
  22268. }
  22269. this.renderItemsIndex ++;
  22270. return renderItem;
  22271. }
  22272. /**
  22273. * Pushes the given object as a render item to the internal render lists.
  22274. * The selected lists depend on the object properties.
  22275. *
  22276. * @param {Object3D} object - The 3D object.
  22277. * @param {BufferGeometry} geometry - The 3D object's geometry.
  22278. * @param {Material} material - The 3D object's material.
  22279. * @param {number} groupOrder - The current group order.
  22280. * @param {number} z - Th 3D object's depth value (z value in clip space).
  22281. * @param {?number} group - {?Object} group - Only relevant for objects using multiple materials. This represents a group entry from the respective `BufferGeometry`.
  22282. * @param {ClippingContext} clippingContext - The current clipping context.
  22283. */
  22284. push( object, geometry, material, groupOrder, z, group, clippingContext ) {
  22285. const renderItem = this.getNextRenderItem( object, geometry, material, groupOrder, z, group, clippingContext );
  22286. if ( object.occlusionTest === true ) this.occlusionQueryCount ++;
  22287. if ( material.transparent === true || material.transmission > 0 ||
  22288. ( material.transmissionNode && material.transmissionNode.isNode ) ||
  22289. ( material.backdropNode && material.backdropNode.isNode ) ) {
  22290. if ( needsDoublePass( material ) ) this.transparentDoublePass.push( renderItem );
  22291. this.transparent.push( renderItem );
  22292. } else {
  22293. this.opaque.push( renderItem );
  22294. }
  22295. }
  22296. /**
  22297. * Inserts the given object as a render item at the start of the internal render lists.
  22298. * The selected lists depend on the object properties.
  22299. *
  22300. * @param {Object3D} object - The 3D object.
  22301. * @param {BufferGeometry} geometry - The 3D object's geometry.
  22302. * @param {Material} material - The 3D object's material.
  22303. * @param {number} groupOrder - The current group order.
  22304. * @param {number} z - Th 3D object's depth value (z value in clip space).
  22305. * @param {?number} group - {?Object} group - Only relevant for objects using multiple materials. This represents a group entry from the respective `BufferGeometry`.
  22306. * @param {ClippingContext} clippingContext - The current clipping context.
  22307. */
  22308. unshift( object, geometry, material, groupOrder, z, group, clippingContext ) {
  22309. const renderItem = this.getNextRenderItem( object, geometry, material, groupOrder, z, group, clippingContext );
  22310. if ( material.transparent === true || material.transmission > 0 ||
  22311. ( material.transmissionNode && material.transmissionNode.isNode ) ||
  22312. ( material.backdropNode && material.backdropNode.isNode ) ) {
  22313. if ( needsDoublePass( material ) ) this.transparentDoublePass.unshift( renderItem );
  22314. this.transparent.unshift( renderItem );
  22315. } else {
  22316. this.opaque.unshift( renderItem );
  22317. }
  22318. }
  22319. /**
  22320. * Pushes render bundle group data into the render list.
  22321. *
  22322. * @param {Object} group - Bundle group data.
  22323. */
  22324. pushBundle( group ) {
  22325. this.bundles.push( group );
  22326. }
  22327. /**
  22328. * Pushes a light into the render list.
  22329. *
  22330. * @param {Light} light - The light.
  22331. */
  22332. pushLight( light ) {
  22333. this.lightsArray.push( light );
  22334. }
  22335. /**
  22336. * Sorts the internal render lists.
  22337. *
  22338. * @param {?function(any, any): number} customOpaqueSort - A custom sort function for opaque objects.
  22339. * @param {?function(any, any): number} customTransparentSort - A custom sort function for transparent objects.
  22340. */
  22341. sort( customOpaqueSort, customTransparentSort ) {
  22342. if ( this.opaque.length > 1 ) this.opaque.sort( customOpaqueSort || painterSortStable );
  22343. if ( this.transparentDoublePass.length > 1 ) this.transparentDoublePass.sort( customTransparentSort || reversePainterSortStable );
  22344. if ( this.transparent.length > 1 ) this.transparent.sort( customTransparentSort || reversePainterSortStable );
  22345. }
  22346. /**
  22347. * This method performs finalizing tasks right after the render lists
  22348. * have been generated.
  22349. */
  22350. finish() {
  22351. // update lights
  22352. this.lightsNode.setLights( this.lightsArray );
  22353. // Clear references from inactive renderItems in the list
  22354. for ( let i = this.renderItemsIndex, il = this.renderItems.length; i < il; i ++ ) {
  22355. const renderItem = this.renderItems[ i ];
  22356. if ( renderItem.id === null ) break;
  22357. renderItem.id = null;
  22358. renderItem.object = null;
  22359. renderItem.geometry = null;
  22360. renderItem.material = null;
  22361. renderItem.groupOrder = null;
  22362. renderItem.renderOrder = null;
  22363. renderItem.z = null;
  22364. renderItem.group = null;
  22365. renderItem.clippingContext = null;
  22366. }
  22367. }
  22368. }
  22369. const _chainKeys$4 = [];
  22370. /**
  22371. * This renderer module manages the render lists which are unique
  22372. * per scene and camera combination.
  22373. *
  22374. * @private
  22375. */
  22376. class RenderLists {
  22377. /**
  22378. * Constructs a render lists management component.
  22379. *
  22380. * @param {Lighting} lighting - The lighting management component.
  22381. */
  22382. constructor( lighting ) {
  22383. /**
  22384. * The lighting management component.
  22385. *
  22386. * @type {Lighting}
  22387. */
  22388. this.lighting = lighting;
  22389. /**
  22390. * The internal chain map which holds the render lists.
  22391. *
  22392. * @type {ChainMap}
  22393. */
  22394. this.lists = new ChainMap();
  22395. }
  22396. /**
  22397. * Returns a render list for the given scene and camera.
  22398. *
  22399. * @param {Scene} scene - The scene.
  22400. * @param {Camera} camera - The camera.
  22401. * @return {RenderList} The render list.
  22402. */
  22403. get( scene, camera ) {
  22404. const lists = this.lists;
  22405. _chainKeys$4[ 0 ] = scene;
  22406. _chainKeys$4[ 1 ] = camera;
  22407. let list = lists.get( _chainKeys$4 );
  22408. if ( list === undefined ) {
  22409. list = new RenderList( this.lighting, scene, camera );
  22410. lists.set( _chainKeys$4, list );
  22411. }
  22412. _chainKeys$4.length = 0;
  22413. return list;
  22414. }
  22415. /**
  22416. * Frees all internal resources.
  22417. */
  22418. dispose() {
  22419. this.lists = new ChainMap();
  22420. }
  22421. }
  22422. let _id$8 = 0;
  22423. /**
  22424. * Any render or compute command is executed in a specific context that defines
  22425. * the state of the renderer and its backend. Typical examples for such context
  22426. * data are the current clear values or data from the active framebuffer. This
  22427. * module is used to represent these contexts as objects.
  22428. *
  22429. * @private
  22430. */
  22431. class RenderContext {
  22432. /**
  22433. * Constructs a new render context.
  22434. */
  22435. constructor() {
  22436. /**
  22437. * The context's ID.
  22438. *
  22439. * @type {number}
  22440. */
  22441. this.id = _id$8 ++;
  22442. /**
  22443. * Whether the current active framebuffer has a color attachment.
  22444. *
  22445. * @type {boolean}
  22446. * @default true
  22447. */
  22448. this.color = true;
  22449. /**
  22450. * Whether the color attachment should be cleared or not.
  22451. *
  22452. * @type {boolean}
  22453. * @default true
  22454. */
  22455. this.clearColor = true;
  22456. /**
  22457. * The clear color value.
  22458. *
  22459. * @type {Object}
  22460. * @default true
  22461. */
  22462. this.clearColorValue = { r: 0, g: 0, b: 0, a: 1 };
  22463. /**
  22464. * Whether the current active framebuffer has a depth attachment.
  22465. *
  22466. * @type {boolean}
  22467. * @default true
  22468. */
  22469. this.depth = true;
  22470. /**
  22471. * Whether the depth attachment should be cleared or not.
  22472. *
  22473. * @type {boolean}
  22474. * @default true
  22475. */
  22476. this.clearDepth = true;
  22477. /**
  22478. * The clear depth value.
  22479. *
  22480. * @type {number}
  22481. * @default 1
  22482. */
  22483. this.clearDepthValue = 1;
  22484. /**
  22485. * Whether the current active framebuffer has a stencil attachment.
  22486. *
  22487. * @type {boolean}
  22488. * @default false
  22489. */
  22490. this.stencil = false;
  22491. /**
  22492. * Whether the stencil attachment should be cleared or not.
  22493. *
  22494. * @type {boolean}
  22495. * @default true
  22496. */
  22497. this.clearStencil = true;
  22498. /**
  22499. * The clear stencil value.
  22500. *
  22501. * @type {number}
  22502. * @default 1
  22503. */
  22504. this.clearStencilValue = 1;
  22505. /**
  22506. * By default the viewport encloses the entire framebuffer If a smaller
  22507. * viewport is manually defined, this property is to `true` by the renderer.
  22508. *
  22509. * @type {boolean}
  22510. * @default false
  22511. */
  22512. this.viewport = false;
  22513. /**
  22514. * The viewport value. This value is in physical pixels meaning it incorporates
  22515. * the renderer's pixel ratio. The viewport property of render targets or
  22516. * the renderer is in logical pixels.
  22517. *
  22518. * @type {Vector4}
  22519. */
  22520. this.viewportValue = new Vector4();
  22521. /**
  22522. * When the scissor test is active and scissor rectangle smaller than the
  22523. * framebuffers dimensions, this property is to `true` by the renderer.
  22524. *
  22525. * @type {boolean}
  22526. * @default false
  22527. */
  22528. this.scissor = false;
  22529. /**
  22530. * The scissor rectangle.
  22531. *
  22532. * @type {Vector4}
  22533. */
  22534. this.scissorValue = new Vector4();
  22535. /**
  22536. * The active render target.
  22537. *
  22538. * @type {?RenderTarget}
  22539. * @default null
  22540. */
  22541. this.renderTarget = null;
  22542. /**
  22543. * The textures of the active render target.
  22544. * `null` when no render target is set.
  22545. *
  22546. * @type {?Array<Texture>}
  22547. * @default null
  22548. */
  22549. this.textures = null;
  22550. /**
  22551. * The depth texture of the active render target.
  22552. * `null` when no render target is set.
  22553. *
  22554. * @type {?DepthTexture}
  22555. * @default null
  22556. */
  22557. this.depthTexture = null;
  22558. /**
  22559. * The active cube face.
  22560. *
  22561. * @type {number}
  22562. * @default 0
  22563. */
  22564. this.activeCubeFace = 0;
  22565. /**
  22566. * The active mipmap level.
  22567. *
  22568. * @type {number}
  22569. * @default 0
  22570. */
  22571. this.activeMipmapLevel = 0;
  22572. /**
  22573. * The number of MSAA samples. This value is always `1` when
  22574. * MSAA isn't used.
  22575. *
  22576. * @type {number}
  22577. * @default 1
  22578. */
  22579. this.sampleCount = 1;
  22580. /**
  22581. * The active render target's width in physical pixels.
  22582. *
  22583. * @type {number}
  22584. * @default 0
  22585. */
  22586. this.width = 0;
  22587. /**
  22588. * The active render target's height in physical pixels.
  22589. *
  22590. * @type {number}
  22591. * @default 0
  22592. */
  22593. this.height = 0;
  22594. /**
  22595. * The occlusion query count.
  22596. *
  22597. * @type {number}
  22598. * @default 0
  22599. */
  22600. this.occlusionQueryCount = 0;
  22601. /**
  22602. * The current clipping context.
  22603. *
  22604. * @type {?ClippingContext}
  22605. * @default null
  22606. */
  22607. this.clippingContext = null;
  22608. /**
  22609. * This flag can be used for type testing.
  22610. *
  22611. * @type {boolean}
  22612. * @readonly
  22613. * @default true
  22614. */
  22615. this.isRenderContext = true;
  22616. }
  22617. /**
  22618. * Returns the cache key of this render context.
  22619. *
  22620. * @return {number} The cache key.
  22621. */
  22622. getCacheKey() {
  22623. return getCacheKey( this );
  22624. }
  22625. }
  22626. /**
  22627. * Computes a cache key for the given render context. This key
  22628. * should identify the render target state so it is possible to
  22629. * configure the correct attachments in the respective backend.
  22630. *
  22631. * @param {RenderContext} renderContext - The render context.
  22632. * @return {number} The cache key.
  22633. */
  22634. function getCacheKey( renderContext ) {
  22635. const { textures, activeCubeFace, activeMipmapLevel } = renderContext;
  22636. const values = [ activeCubeFace, activeMipmapLevel ];
  22637. for ( const texture of textures ) {
  22638. values.push( texture.id );
  22639. }
  22640. return hashArray( values );
  22641. }
  22642. const _chainKeys$3 = [];
  22643. const _defaultScene = /*@__PURE__*/ new Scene();
  22644. const _defaultCamera = /*@__PURE__*/ new Camera();
  22645. /**
  22646. * This module manages the render contexts of the renderer.
  22647. *
  22648. * @private
  22649. */
  22650. class RenderContexts {
  22651. /**
  22652. * Constructs a new render context management component.
  22653. */
  22654. constructor() {
  22655. /**
  22656. * A dictionary that manages render contexts in chain maps
  22657. * for each attachment state.
  22658. *
  22659. * @type {Object<string,ChainMap>}
  22660. */
  22661. this.chainMaps = {};
  22662. }
  22663. /**
  22664. * Returns a render context for the given scene, camera and render target.
  22665. *
  22666. * @param {Scene} scene - The scene.
  22667. * @param {Camera} camera - The camera that is used to render the scene.
  22668. * @param {?RenderTarget} [renderTarget=null] - The active render target.
  22669. * @return {RenderContext} The render context.
  22670. */
  22671. get( scene, camera, renderTarget = null ) {
  22672. _chainKeys$3[ 0 ] = scene;
  22673. _chainKeys$3[ 1 ] = camera;
  22674. let attachmentState;
  22675. if ( renderTarget === null ) {
  22676. attachmentState = 'default';
  22677. } else {
  22678. const format = renderTarget.texture.format;
  22679. const count = renderTarget.textures.length;
  22680. attachmentState = `${ count }:${ format }:${ renderTarget.samples }:${ renderTarget.depthBuffer }:${ renderTarget.stencilBuffer }`;
  22681. }
  22682. const chainMap = this._getChainMap( attachmentState );
  22683. let renderState = chainMap.get( _chainKeys$3 );
  22684. if ( renderState === undefined ) {
  22685. renderState = new RenderContext();
  22686. chainMap.set( _chainKeys$3, renderState );
  22687. }
  22688. _chainKeys$3.length = 0;
  22689. if ( renderTarget !== null ) renderState.sampleCount = renderTarget.samples === 0 ? 1 : renderTarget.samples;
  22690. return renderState;
  22691. }
  22692. /**
  22693. * Returns a render context intended for clear operations.
  22694. *
  22695. * @param {?RenderTarget} [renderTarget=null] - The active render target.
  22696. * @return {RenderContext} The render context.
  22697. */
  22698. getForClear( renderTarget = null ) {
  22699. return this.get( _defaultScene, _defaultCamera, renderTarget );
  22700. }
  22701. /**
  22702. * Returns a chain map for the given attachment state.
  22703. *
  22704. * @private
  22705. * @param {string} attachmentState - The attachment state.
  22706. * @return {ChainMap} The chain map.
  22707. */
  22708. _getChainMap( attachmentState ) {
  22709. return this.chainMaps[ attachmentState ] || ( this.chainMaps[ attachmentState ] = new ChainMap() );
  22710. }
  22711. /**
  22712. * Frees internal resources.
  22713. */
  22714. dispose() {
  22715. this.chainMaps = {};
  22716. }
  22717. }
  22718. const _size$3 = /*@__PURE__*/ new Vector3();
  22719. /**
  22720. * This module manages the textures of the renderer.
  22721. *
  22722. * @private
  22723. * @augments DataMap
  22724. */
  22725. class Textures extends DataMap {
  22726. /**
  22727. * Constructs a new texture management component.
  22728. *
  22729. * @param {Renderer} renderer - The renderer.
  22730. * @param {Backend} backend - The renderer's backend.
  22731. * @param {Info} info - Renderer component for managing metrics and monitoring data.
  22732. */
  22733. constructor( renderer, backend, info ) {
  22734. super();
  22735. /**
  22736. * The renderer.
  22737. *
  22738. * @type {Renderer}
  22739. */
  22740. this.renderer = renderer;
  22741. /**
  22742. * The backend.
  22743. *
  22744. * @type {Backend}
  22745. */
  22746. this.backend = backend;
  22747. /**
  22748. * Renderer component for managing metrics and monitoring data.
  22749. *
  22750. * @type {Info}
  22751. */
  22752. this.info = info;
  22753. }
  22754. /**
  22755. * Updates the given render target. Based on the given render target configuration,
  22756. * it updates the texture states representing the attachments of the framebuffer.
  22757. *
  22758. * @param {RenderTarget} renderTarget - The render target to update.
  22759. * @param {number} [activeMipmapLevel=0] - The active mipmap level.
  22760. */
  22761. updateRenderTarget( renderTarget, activeMipmapLevel = 0 ) {
  22762. const renderTargetData = this.get( renderTarget );
  22763. const sampleCount = renderTarget.samples === 0 ? 1 : renderTarget.samples;
  22764. const depthTextureMips = renderTargetData.depthTextureMips || ( renderTargetData.depthTextureMips = {} );
  22765. const textures = renderTarget.textures;
  22766. const size = this.getSize( textures[ 0 ] );
  22767. const mipWidth = size.width >> activeMipmapLevel;
  22768. const mipHeight = size.height >> activeMipmapLevel;
  22769. let depthTexture = renderTarget.depthTexture || depthTextureMips[ activeMipmapLevel ];
  22770. const useDepthTexture = renderTarget.depthBuffer === true || renderTarget.stencilBuffer === true;
  22771. let textureNeedsUpdate = false;
  22772. if ( depthTexture === undefined && useDepthTexture ) {
  22773. depthTexture = new DepthTexture();
  22774. depthTexture.format = renderTarget.stencilBuffer ? DepthStencilFormat : DepthFormat;
  22775. depthTexture.type = renderTarget.stencilBuffer ? UnsignedInt248Type : UnsignedIntType; // FloatType
  22776. depthTexture.image.width = mipWidth;
  22777. depthTexture.image.height = mipHeight;
  22778. depthTexture.image.depth = size.depth;
  22779. depthTexture.renderTarget = renderTarget;
  22780. depthTexture.isArrayTexture = renderTarget.multiview === true && size.depth > 1;
  22781. depthTextureMips[ activeMipmapLevel ] = depthTexture;
  22782. }
  22783. if ( renderTargetData.width !== size.width || size.height !== renderTargetData.height ) {
  22784. textureNeedsUpdate = true;
  22785. if ( depthTexture ) {
  22786. depthTexture.needsUpdate = true;
  22787. depthTexture.image.width = mipWidth;
  22788. depthTexture.image.height = mipHeight;
  22789. depthTexture.image.depth = depthTexture.isArrayTexture ? depthTexture.image.depth : 1;
  22790. }
  22791. }
  22792. renderTargetData.width = size.width;
  22793. renderTargetData.height = size.height;
  22794. renderTargetData.textures = textures;
  22795. renderTargetData.depthTexture = depthTexture || null;
  22796. renderTargetData.depth = renderTarget.depthBuffer;
  22797. renderTargetData.stencil = renderTarget.stencilBuffer;
  22798. renderTargetData.renderTarget = renderTarget;
  22799. if ( renderTargetData.sampleCount !== sampleCount ) {
  22800. textureNeedsUpdate = true;
  22801. if ( depthTexture ) {
  22802. depthTexture.needsUpdate = true;
  22803. }
  22804. renderTargetData.sampleCount = sampleCount;
  22805. }
  22806. //
  22807. const options = { sampleCount };
  22808. // XR render targets require no texture updates
  22809. if ( renderTarget.isXRRenderTarget !== true ) {
  22810. for ( let i = 0; i < textures.length; i ++ ) {
  22811. const texture = textures[ i ];
  22812. if ( textureNeedsUpdate ) texture.needsUpdate = true;
  22813. this.updateTexture( texture, options );
  22814. }
  22815. if ( depthTexture ) {
  22816. this.updateTexture( depthTexture, options );
  22817. }
  22818. }
  22819. // dispose handler
  22820. if ( renderTargetData.initialized !== true ) {
  22821. renderTargetData.initialized = true;
  22822. // dispose
  22823. renderTargetData.onDispose = () => {
  22824. this._destroyRenderTarget( renderTarget );
  22825. };
  22826. renderTarget.addEventListener( 'dispose', renderTargetData.onDispose );
  22827. }
  22828. }
  22829. /**
  22830. * Updates the given texture. Depending on the texture state, this method
  22831. * triggers the upload of texture data to the GPU memory. If the texture data are
  22832. * not yet ready for the upload, it uses default texture data for as a placeholder.
  22833. *
  22834. * @param {Texture} texture - The texture to update.
  22835. * @param {Object} [options={}] - The options.
  22836. */
  22837. updateTexture( texture, options = {} ) {
  22838. const textureData = this.get( texture );
  22839. if ( textureData.initialized === true && textureData.version === texture.version ) return;
  22840. const isRenderTarget = texture.isRenderTargetTexture || texture.isDepthTexture || texture.isFramebufferTexture;
  22841. const backend = this.backend;
  22842. if ( isRenderTarget && textureData.initialized === true ) {
  22843. // it's an update
  22844. backend.destroyTexture( texture );
  22845. }
  22846. //
  22847. if ( texture.isFramebufferTexture ) {
  22848. const renderTarget = this.renderer.getRenderTarget();
  22849. if ( renderTarget ) {
  22850. texture.type = renderTarget.texture.type;
  22851. } else {
  22852. texture.type = UnsignedByteType;
  22853. }
  22854. }
  22855. //
  22856. const { width, height, depth } = this.getSize( texture );
  22857. options.width = width;
  22858. options.height = height;
  22859. options.depth = depth;
  22860. options.needsMipmaps = this.needsMipmaps( texture );
  22861. options.levels = options.needsMipmaps ? this.getMipLevels( texture, width, height ) : 1;
  22862. // TODO: Uniformly handle mipmap definitions
  22863. // Normal textures and compressed cube textures define base level + mips with their mipmap array
  22864. // Uncompressed cube textures use their mipmap array only for mips (no base level)
  22865. if ( texture.isCubeTexture && texture.mipmaps.length > 0 ) options.levels ++;
  22866. //
  22867. if ( isRenderTarget || texture.isStorageTexture === true || texture.isExternalTexture === true ) {
  22868. backend.createTexture( texture, options );
  22869. textureData.generation = texture.version;
  22870. } else {
  22871. if ( texture.version > 0 ) {
  22872. const image = texture.image;
  22873. if ( image === undefined ) {
  22874. warn( 'Renderer: Texture marked for update but image is undefined.' );
  22875. } else if ( image.complete === false ) {
  22876. warn( 'Renderer: Texture marked for update but image is incomplete.' );
  22877. } else {
  22878. if ( texture.images ) {
  22879. const images = [];
  22880. for ( const image of texture.images ) {
  22881. images.push( image );
  22882. }
  22883. options.images = images;
  22884. } else {
  22885. options.image = image;
  22886. }
  22887. if ( textureData.isDefaultTexture === undefined || textureData.isDefaultTexture === true ) {
  22888. backend.createTexture( texture, options );
  22889. textureData.isDefaultTexture = false;
  22890. textureData.generation = texture.version;
  22891. }
  22892. if ( texture.source.dataReady === true ) backend.updateTexture( texture, options );
  22893. const skipAutoGeneration = texture.isStorageTexture === true && texture.mipmapsAutoUpdate === false;
  22894. if ( options.needsMipmaps && texture.mipmaps.length === 0 && ! skipAutoGeneration ) {
  22895. backend.generateMipmaps( texture );
  22896. }
  22897. if ( texture.onUpdate ) texture.onUpdate( texture );
  22898. }
  22899. } else {
  22900. // async update
  22901. backend.createDefaultTexture( texture );
  22902. textureData.isDefaultTexture = true;
  22903. textureData.generation = texture.version;
  22904. }
  22905. }
  22906. // dispose handler
  22907. if ( textureData.initialized !== true ) {
  22908. textureData.initialized = true;
  22909. textureData.generation = texture.version;
  22910. //
  22911. this.info.memory.textures ++;
  22912. //
  22913. if ( texture.isVideoTexture && ColorManagement.getTransfer( texture.colorSpace ) !== SRGBTransfer ) {
  22914. warn( 'WebGPURenderer: Video textures must use a color space with a sRGB transfer function, e.g. SRGBColorSpace.' );
  22915. }
  22916. // dispose
  22917. textureData.onDispose = () => {
  22918. this._destroyTexture( texture );
  22919. };
  22920. texture.addEventListener( 'dispose', textureData.onDispose );
  22921. }
  22922. //
  22923. textureData.version = texture.version;
  22924. }
  22925. /**
  22926. * Updates the sampler for the given texture. This method has no effect
  22927. * for the WebGL backend since it has no concept of samplers. Texture
  22928. * parameters are configured with the `texParameter()` command for each
  22929. * texture.
  22930. *
  22931. * In WebGPU, samplers are objects like textures and it's possible to share
  22932. * them when the texture parameters match.
  22933. *
  22934. * @param {Texture} texture - The texture to update the sampler for.
  22935. * @return {string} The current sampler key.
  22936. */
  22937. updateSampler( texture ) {
  22938. return this.backend.updateSampler( texture );
  22939. }
  22940. /**
  22941. * Computes the size of the given texture and writes the result
  22942. * into the target vector. This vector is also returned by the
  22943. * method.
  22944. *
  22945. * If no texture data are available for the compute yet, the method
  22946. * returns default size values.
  22947. *
  22948. * @param {Texture} texture - The texture to compute the size for.
  22949. * @param {Vector3} target - The target vector.
  22950. * @return {Vector3} The target vector.
  22951. */
  22952. getSize( texture, target = _size$3 ) {
  22953. let image = texture.images ? texture.images[ 0 ] : texture.image;
  22954. if ( image ) {
  22955. if ( image.image !== undefined ) image = image.image;
  22956. if ( ( typeof HTMLVideoElement !== 'undefined' ) && ( image instanceof HTMLVideoElement ) ) {
  22957. target.width = image.videoWidth || 1;
  22958. target.height = image.videoHeight || 1;
  22959. target.depth = 1;
  22960. } else if ( ( typeof VideoFrame !== 'undefined' ) && ( image instanceof VideoFrame ) ) {
  22961. target.width = image.displayWidth || 1;
  22962. target.height = image.displayHeight || 1;
  22963. target.depth = 1;
  22964. } else {
  22965. target.width = image.width || 1;
  22966. target.height = image.height || 1;
  22967. target.depth = texture.isCubeTexture ? 6 : ( image.depth || 1 );
  22968. }
  22969. } else {
  22970. target.width = target.height = target.depth = 1;
  22971. }
  22972. return target;
  22973. }
  22974. /**
  22975. * Computes the number of mipmap levels for the given texture.
  22976. *
  22977. * @param {Texture} texture - The texture.
  22978. * @param {number} width - The texture's width.
  22979. * @param {number} height - The texture's height.
  22980. * @return {number} The number of mipmap levels.
  22981. */
  22982. getMipLevels( texture, width, height ) {
  22983. let mipLevelCount;
  22984. if ( texture.mipmaps.length > 0 ) {
  22985. mipLevelCount = texture.mipmaps.length;
  22986. } else {
  22987. if ( texture.isCompressedTexture === true ) {
  22988. // it is not possible to compute mipmaps for compressed textures. So
  22989. // when no mipmaps are defined in "texture.mipmaps", force a texture
  22990. // level of 1
  22991. mipLevelCount = 1;
  22992. } else {
  22993. mipLevelCount = Math.floor( Math.log2( Math.max( width, height ) ) ) + 1;
  22994. }
  22995. }
  22996. return mipLevelCount;
  22997. }
  22998. /**
  22999. * Returns `true` if the given texture makes use of mipmapping.
  23000. *
  23001. * @param {Texture} texture - The texture.
  23002. * @return {boolean} Whether mipmaps are required or not.
  23003. */
  23004. needsMipmaps( texture ) {
  23005. return texture.generateMipmaps === true || texture.mipmaps.length > 0;
  23006. }
  23007. /**
  23008. * Frees internal resources when the given render target isn't
  23009. * required anymore.
  23010. *
  23011. * @param {RenderTarget} renderTarget - The render target to destroy.
  23012. */
  23013. _destroyRenderTarget( renderTarget ) {
  23014. if ( this.has( renderTarget ) === true ) {
  23015. const renderTargetData = this.get( renderTarget );
  23016. const textures = renderTargetData.textures;
  23017. const depthTexture = renderTargetData.depthTexture;
  23018. //
  23019. renderTarget.removeEventListener( 'dispose', renderTargetData.onDispose );
  23020. //
  23021. for ( let i = 0; i < textures.length; i ++ ) {
  23022. this._destroyTexture( textures[ i ] );
  23023. }
  23024. if ( depthTexture ) {
  23025. this._destroyTexture( depthTexture );
  23026. }
  23027. this.delete( renderTarget );
  23028. this.backend.delete( renderTarget );
  23029. }
  23030. }
  23031. /**
  23032. * Frees internal resource when the given texture isn't
  23033. * required anymore.
  23034. *
  23035. * @param {Texture} texture - The texture to destroy.
  23036. */
  23037. _destroyTexture( texture ) {
  23038. if ( this.has( texture ) === true ) {
  23039. const textureData = this.get( texture );
  23040. //
  23041. texture.removeEventListener( 'dispose', textureData.onDispose );
  23042. // if a texture is not ready for use, it falls back to a default texture so it's possible
  23043. // to use it for rendering. If a texture in this state is disposed, it's important to
  23044. // not destroy/delete the underlying GPU texture object since it is cached and shared with
  23045. // other textures.
  23046. const isDefaultTexture = textureData.isDefaultTexture;
  23047. this.backend.destroyTexture( texture, isDefaultTexture );
  23048. this.delete( texture );
  23049. this.info.memory.textures --;
  23050. }
  23051. }
  23052. }
  23053. /**
  23054. * A four-component version of {@link Color} which is internally
  23055. * used by the renderer to represents clear color with alpha as
  23056. * one object.
  23057. *
  23058. * @private
  23059. * @augments Color
  23060. */
  23061. class Color4 extends Color {
  23062. /**
  23063. * Constructs a new four-component color.
  23064. * You can also pass a single THREE.Color, hex or
  23065. * string argument to this constructor.
  23066. *
  23067. * @param {number|string} [r=1] - The red value.
  23068. * @param {number} [g=1] - The green value.
  23069. * @param {number} [b=1] - The blue value.
  23070. * @param {number} [a=1] - The alpha value.
  23071. */
  23072. constructor( r, g, b, a = 1 ) {
  23073. super( r, g, b );
  23074. this.a = a;
  23075. }
  23076. /**
  23077. * Overwrites the default to honor alpha.
  23078. * You can also pass a single THREE.Color, hex or
  23079. * string argument to this method.
  23080. *
  23081. * @param {number|string|Color} r - The red value.
  23082. * @param {number} [g] - The green value.
  23083. * @param {number} [b] - The blue value.
  23084. * @param {number} [a=1] - The alpha value.
  23085. * @return {Color4} A reference to this object.
  23086. */
  23087. set( r, g, b, a = 1 ) {
  23088. this.a = a;
  23089. return super.set( r, g, b );
  23090. }
  23091. /**
  23092. * Overwrites the default to honor alpha.
  23093. *
  23094. * @param {Color4} color - The color to copy.
  23095. * @return {Color4} A reference to this object.
  23096. */
  23097. copy( color ) {
  23098. if ( color.a !== undefined ) this.a = color.a;
  23099. return super.copy( color );
  23100. }
  23101. /**
  23102. * Overwrites the default to honor alpha.
  23103. *
  23104. * @return {Color4} The cloned color.
  23105. */
  23106. clone() {
  23107. return new this.constructor( this.r, this.g, this.b, this.a );
  23108. }
  23109. }
  23110. /**
  23111. * Special version of {@link PropertyNode} which is used for parameters.
  23112. *
  23113. * @augments PropertyNode
  23114. */
  23115. class ParameterNode extends PropertyNode {
  23116. static get type() {
  23117. return 'ParameterNode';
  23118. }
  23119. /**
  23120. * Constructs a new parameter node.
  23121. *
  23122. * @param {string} nodeType - The type of the node.
  23123. * @param {?string} [name=null] - The name of the parameter in the shader.
  23124. */
  23125. constructor( nodeType, name = null ) {
  23126. super( nodeType, name );
  23127. /**
  23128. * This flag can be used for type testing.
  23129. *
  23130. * @type {boolean}
  23131. * @readonly
  23132. * @default true
  23133. */
  23134. this.isParameterNode = true;
  23135. }
  23136. /**
  23137. * Gets the type of a member variable in the parameter node.
  23138. *
  23139. * @param {NodeBuilder} builder - The node builder.
  23140. * @param {string} name - The name of the member variable.
  23141. * @returns {string}
  23142. */
  23143. getMemberType( builder, name ) {
  23144. const type = this.getNodeType( builder );
  23145. const struct = builder.getStructTypeNode( type );
  23146. let memberType;
  23147. if ( struct !== null ) {
  23148. memberType = struct.getMemberType( builder, name );
  23149. } else {
  23150. error( `TSL: Member "${ name }" not found in struct "${ type }".` );
  23151. memberType = 'float';
  23152. }
  23153. return memberType;
  23154. }
  23155. getHash() {
  23156. return this.uuid;
  23157. }
  23158. generate() {
  23159. return this.name;
  23160. }
  23161. }
  23162. /**
  23163. * TSL function for creating a parameter node.
  23164. *
  23165. * @tsl
  23166. * @function
  23167. * @param {string} type - The type of the node.
  23168. * @param {?string} name - The name of the parameter in the shader.
  23169. * @returns {ParameterNode}
  23170. */
  23171. const parameter = ( type, name ) => nodeObject( new ParameterNode( type, name ) );
  23172. /**
  23173. * Stack is a helper for Nodes that need to produce stack-based code instead of continuous flow.
  23174. * They are usually needed in cases like `If`, `Else`.
  23175. *
  23176. * @augments Node
  23177. */
  23178. class StackNode extends Node {
  23179. static get type() {
  23180. return 'StackNode';
  23181. }
  23182. /**
  23183. * Constructs a new stack node.
  23184. *
  23185. * @param {?StackNode} [parent=null] - The parent stack node.
  23186. */
  23187. constructor( parent = null ) {
  23188. super();
  23189. /**
  23190. * List of nodes.
  23191. *
  23192. * @type {Array<Node>}
  23193. */
  23194. this.nodes = [];
  23195. /**
  23196. * The output node.
  23197. *
  23198. * @type {?Node}
  23199. * @default null
  23200. */
  23201. this.outputNode = null;
  23202. /**
  23203. * The parent stack node.
  23204. *
  23205. * @type {?StackNode}
  23206. * @default null
  23207. */
  23208. this.parent = parent;
  23209. /**
  23210. * The current conditional node.
  23211. *
  23212. * @private
  23213. * @type {ConditionalNode}
  23214. * @default null
  23215. */
  23216. this._currentCond = null;
  23217. /**
  23218. * The expression node. Only
  23219. * relevant for Switch/Case.
  23220. *
  23221. * @private
  23222. * @type {Node}
  23223. * @default null
  23224. */
  23225. this._expressionNode = null;
  23226. /**
  23227. * This flag can be used for type testing.
  23228. *
  23229. * @type {boolean}
  23230. * @readonly
  23231. * @default true
  23232. */
  23233. this.isStackNode = true;
  23234. }
  23235. getElementType( builder ) {
  23236. return this.hasOutput ? this.outputNode.getElementType( builder ) : 'void';
  23237. }
  23238. getNodeType( builder ) {
  23239. return this.hasOutput ? this.outputNode.getNodeType( builder ) : 'void';
  23240. }
  23241. getMemberType( builder, name ) {
  23242. return this.hasOutput ? this.outputNode.getMemberType( builder, name ) : 'void';
  23243. }
  23244. /**
  23245. * Adds a node to this stack.
  23246. *
  23247. * @param {Node} node - The node to add.
  23248. * @return {StackNode} A reference to this stack node.
  23249. */
  23250. addToStack( node ) {
  23251. if ( node.isNode !== true ) {
  23252. error( 'TSL: Invalid node added to stack.' );
  23253. return this;
  23254. }
  23255. this.nodes.push( node );
  23256. return this;
  23257. }
  23258. /**
  23259. * Represent an `if` statement in TSL.
  23260. *
  23261. * @param {Node} boolNode - Represents the condition.
  23262. * @param {Function} method - TSL code which is executed if the condition evaluates to `true`.
  23263. * @return {StackNode} A reference to this stack node.
  23264. */
  23265. If( boolNode, method ) {
  23266. const methodNode = new ShaderNode( method );
  23267. this._currentCond = select( boolNode, methodNode );
  23268. return this.addToStack( this._currentCond );
  23269. }
  23270. /**
  23271. * Represent an `elseif` statement in TSL.
  23272. *
  23273. * @param {Node} boolNode - Represents the condition.
  23274. * @param {Function} method - TSL code which is executed if the condition evaluates to `true`.
  23275. * @return {StackNode} A reference to this stack node.
  23276. */
  23277. ElseIf( boolNode, method ) {
  23278. const methodNode = new ShaderNode( method );
  23279. const ifNode = select( boolNode, methodNode );
  23280. this._currentCond.elseNode = ifNode;
  23281. this._currentCond = ifNode;
  23282. return this;
  23283. }
  23284. /**
  23285. * Represent an `else` statement in TSL.
  23286. *
  23287. * @param {Function} method - TSL code which is executed in the `else` case.
  23288. * @return {StackNode} A reference to this stack node.
  23289. */
  23290. Else( method ) {
  23291. this._currentCond.elseNode = new ShaderNode( method );
  23292. return this;
  23293. }
  23294. /**
  23295. * Represents a `switch` statement in TSL.
  23296. *
  23297. * @param {any} expression - Represents the expression.
  23298. * @param {Function} method - TSL code which is executed if the condition evaluates to `true`.
  23299. * @return {StackNode} A reference to this stack node.
  23300. */
  23301. Switch( expression ) {
  23302. this._expressionNode = nodeObject( expression );
  23303. return this;
  23304. }
  23305. /**
  23306. * Represents a `case` statement in TSL. The TSL version accepts an arbitrary numbers of values.
  23307. * The last parameter must be the callback method that should be executed in the `true` case.
  23308. *
  23309. * @param {...any} params - The values of the `Case()` statement as well as the callback method.
  23310. * @return {StackNode} A reference to this stack node.
  23311. */
  23312. Case( ...params ) {
  23313. const caseNodes = [];
  23314. // extract case nodes from the parameter list
  23315. if ( params.length >= 2 ) {
  23316. for ( let i = 0; i < params.length - 1; i ++ ) {
  23317. caseNodes.push( this._expressionNode.equal( nodeObject( params[ i ] ) ) );
  23318. }
  23319. } else {
  23320. error( 'TSL: Invalid parameter length. Case() requires at least two parameters.' );
  23321. }
  23322. // extract method
  23323. const method = params[ params.length - 1 ];
  23324. const methodNode = new ShaderNode( method );
  23325. // chain multiple cases when using Case( 1, 2, 3, () => {} )
  23326. let caseNode = caseNodes[ 0 ];
  23327. for ( let i = 1; i < caseNodes.length; i ++ ) {
  23328. caseNode = caseNode.or( caseNodes[ i ] );
  23329. }
  23330. // build condition
  23331. const condNode = select( caseNode, methodNode );
  23332. if ( this._currentCond === null ) {
  23333. this._currentCond = condNode;
  23334. return this.addToStack( this._currentCond );
  23335. } else {
  23336. this._currentCond.elseNode = condNode;
  23337. this._currentCond = condNode;
  23338. return this;
  23339. }
  23340. }
  23341. /**
  23342. * Represents the default code block of a Switch/Case statement.
  23343. *
  23344. * @param {Function} method - TSL code which is executed in the `else` case.
  23345. * @return {StackNode} A reference to this stack node.
  23346. */
  23347. Default( method ) {
  23348. this.Else( method );
  23349. return this;
  23350. }
  23351. setup( builder ) {
  23352. const nodeProperties = builder.getNodeProperties( this );
  23353. let index = 0;
  23354. for ( const childNode of this.getChildren() ) {
  23355. if ( childNode.isVarNode && childNode.intent === true ) {
  23356. if ( childNode.isAssign( builder ) !== true ) {
  23357. continue;
  23358. }
  23359. }
  23360. nodeProperties[ 'node' + index ++ ] = childNode;
  23361. }
  23362. // return a outputNode if exists or null
  23363. return nodeProperties.outputNode || null;
  23364. }
  23365. get hasOutput() {
  23366. return this.outputNode && this.outputNode.isNode;
  23367. }
  23368. build( builder, ...params ) {
  23369. const previousStack = getCurrentStack();
  23370. setCurrentStack( this );
  23371. builder.setActiveStack( this );
  23372. const buildStage = builder.buildStage;
  23373. for ( const node of this.nodes ) {
  23374. if ( node.isVarNode && node.intent === true ) {
  23375. if ( node.isAssign( builder ) !== true ) {
  23376. continue;
  23377. }
  23378. }
  23379. if ( buildStage === 'setup' ) {
  23380. node.build( builder );
  23381. } else if ( buildStage === 'analyze' ) {
  23382. node.build( builder, this );
  23383. } else if ( buildStage === 'generate' ) {
  23384. const stages = builder.getDataFromNode( node, 'any' ).stages;
  23385. const parents = stages && stages[ builder.shaderStage ];
  23386. if ( node.isVarNode && parents && parents.length === 1 && parents[ 0 ] && parents[ 0 ].isStackNode ) {
  23387. continue; // skip var nodes that are only used in .toVarying()
  23388. }
  23389. node.build( builder, 'void' );
  23390. }
  23391. }
  23392. //
  23393. let result;
  23394. if ( this.hasOutput ) {
  23395. result = this.outputNode.build( builder, ...params );
  23396. } else {
  23397. result = super.build( builder, ...params );
  23398. }
  23399. setCurrentStack( previousStack );
  23400. builder.removeActiveStack( this );
  23401. return result;
  23402. }
  23403. }
  23404. /**
  23405. * TSL function for creating a stack node.
  23406. *
  23407. * @tsl
  23408. * @function
  23409. * @param {?StackNode} [parent=null] - The parent stack node.
  23410. * @returns {StackNode}
  23411. */
  23412. const stack = /*@__PURE__*/ nodeProxy( StackNode ).setParameterLength( 0, 1 );
  23413. /**
  23414. * Generates a layout for struct members.
  23415. * This function takes an object representing struct members and returns an array of member layouts.
  23416. * Each member layout includes the member's name, type, and whether it is atomic.
  23417. *
  23418. * @param {Object.<string, string|Object>} members - An object where keys are member names and values are either types (as strings) or objects with type and atomic properties.
  23419. * @returns {Array.<{name: string, type: string, atomic: boolean}>} An array of member layouts.
  23420. */
  23421. function getMembersLayout( members ) {
  23422. return Object.entries( members ).map( ( [ name, value ] ) => {
  23423. if ( typeof value === 'string' ) {
  23424. return { name, type: value, atomic: false };
  23425. }
  23426. return { name, type: value.type, atomic: value.atomic || false };
  23427. } );
  23428. }
  23429. /**
  23430. * Represents a struct type node in the node-based system.
  23431. * This class is used to define and manage the layout and types of struct members.
  23432. * It extends the base Node class and provides methods to get the length of the struct,
  23433. * retrieve member types, and generate the struct type for a builder.
  23434. *
  23435. * @augments Node
  23436. */
  23437. class StructTypeNode extends Node {
  23438. static get type() {
  23439. return 'StructTypeNode';
  23440. }
  23441. /**
  23442. * Creates an instance of StructTypeNode.
  23443. *
  23444. * @param {Object} membersLayout - The layout of the members for the struct.
  23445. * @param {?string} [name=null] - The optional name of the struct.
  23446. */
  23447. constructor( membersLayout, name = null ) {
  23448. super( 'struct' );
  23449. /**
  23450. * The layout of the members for the struct
  23451. *
  23452. * @type {Array.<{name: string, type: string, atomic: boolean}>}
  23453. */
  23454. this.membersLayout = getMembersLayout( membersLayout );
  23455. /**
  23456. * The name of the struct.
  23457. *
  23458. * @type {?string}
  23459. * @default null
  23460. */
  23461. this.name = name;
  23462. /**
  23463. * This flag can be used for type testing.
  23464. *
  23465. * @type {boolean}
  23466. * @readonly
  23467. * @default true
  23468. */
  23469. this.isStructLayoutNode = true;
  23470. }
  23471. /**
  23472. * Returns the length of the struct.
  23473. * The length is calculated by summing the lengths of the struct's members.
  23474. *
  23475. * @returns {number} The length of the struct.
  23476. */
  23477. getLength() {
  23478. const GPU_CHUNK_BYTES = 8;
  23479. const BYTES_PER_ELEMENT = Float32Array.BYTES_PER_ELEMENT;
  23480. let offset = 0; // global buffer offset in bytes
  23481. for ( const member of this.membersLayout ) {
  23482. const type = member.type;
  23483. const itemSize = getMemoryLengthFromType( type ) * BYTES_PER_ELEMENT;
  23484. const boundary = getByteBoundaryFromType( type );
  23485. const chunkOffset = offset % GPU_CHUNK_BYTES; // offset in the current chunk
  23486. const chunkPadding = chunkOffset % boundary; // required padding to match boundary
  23487. const chunkStart = chunkOffset + chunkPadding; // start position in the current chunk for the data
  23488. offset += chunkPadding;
  23489. // Check for chunk overflow
  23490. if ( chunkStart !== 0 && ( GPU_CHUNK_BYTES - chunkStart ) < itemSize ) {
  23491. // Add padding to the end of the chunk
  23492. offset += ( GPU_CHUNK_BYTES - chunkStart );
  23493. }
  23494. offset += itemSize;
  23495. }
  23496. return ( Math.ceil( offset / GPU_CHUNK_BYTES ) * GPU_CHUNK_BYTES ) / BYTES_PER_ELEMENT;
  23497. }
  23498. getMemberType( builder, name ) {
  23499. const member = this.membersLayout.find( m => m.name === name );
  23500. return member ? member.type : 'void';
  23501. }
  23502. getNodeType( builder ) {
  23503. const structType = builder.getStructTypeFromNode( this, this.membersLayout, this.name );
  23504. return structType.name;
  23505. }
  23506. setup( builder ) {
  23507. builder.getStructTypeFromNode( this, this.membersLayout, this.name );
  23508. builder.addInclude( this );
  23509. }
  23510. generate( builder ) {
  23511. return this.getNodeType( builder );
  23512. }
  23513. }
  23514. /**
  23515. * StructNode allows to create custom structures with multiple members.
  23516. * This can also be used to define structures in attribute and uniform data.
  23517. *
  23518. * ```js
  23519. * // Define a custom struct
  23520. * const BoundingBox = struct( { min: 'vec3', max: 'vec3' } );
  23521. *
  23522. * // Create a new instance of the struct
  23523. * const bb = BoundingBox( vec3( 0 ), vec3( 1 ) ); // style 1
  23524. * const bb = BoundingBox( { min: vec3( 0 ), max: vec3( 1 ) } ); // style 2
  23525. *
  23526. * // Access the struct members
  23527. * const min = bb.get( 'min' );
  23528. *
  23529. * // Assign a new value to a member
  23530. * min.assign( vec3() );
  23531. * ```
  23532. * @augments Node
  23533. */
  23534. class StructNode extends Node {
  23535. static get type() {
  23536. return 'StructNode';
  23537. }
  23538. constructor( structTypeNode, values ) {
  23539. super( 'vec3' );
  23540. this.structTypeNode = structTypeNode;
  23541. this.values = values;
  23542. this.isStructNode = true;
  23543. }
  23544. getNodeType( builder ) {
  23545. return this.structTypeNode.getNodeType( builder );
  23546. }
  23547. getMemberType( builder, name ) {
  23548. return this.structTypeNode.getMemberType( builder, name );
  23549. }
  23550. generate( builder ) {
  23551. const nodeVar = builder.getVarFromNode( this );
  23552. const structType = nodeVar.type;
  23553. const propertyName = builder.getPropertyName( nodeVar );
  23554. builder.addLineFlowCode( `${ propertyName } = ${ builder.generateStruct( structType, this.structTypeNode.membersLayout, this.values ) }`, this );
  23555. return nodeVar.name;
  23556. }
  23557. }
  23558. /**
  23559. * TSL function for creating a struct node.
  23560. *
  23561. * @tsl
  23562. * @function
  23563. * @param {Object} membersLayout - The layout of the struct members.
  23564. * @param {?string} [name=null] - The name of the struct.
  23565. * @returns {Function} The struct function.
  23566. */
  23567. const struct = ( membersLayout, name = null ) => {
  23568. const structLayout = new StructTypeNode( membersLayout, name );
  23569. const struct = ( ...params ) => {
  23570. let values = null;
  23571. if ( params.length > 0 ) {
  23572. if ( params[ 0 ].isNode ) {
  23573. values = {};
  23574. const names = Object.keys( membersLayout );
  23575. for ( let i = 0; i < params.length; i ++ ) {
  23576. values[ names[ i ] ] = params[ i ];
  23577. }
  23578. } else {
  23579. values = params[ 0 ];
  23580. }
  23581. }
  23582. return nodeObject( new StructNode( structLayout, values ) );
  23583. };
  23584. struct.layout = structLayout;
  23585. struct.isStruct = true;
  23586. return struct;
  23587. };
  23588. /**
  23589. * This node can be used to define multiple outputs in a shader programs.
  23590. *
  23591. * @augments Node
  23592. */
  23593. class OutputStructNode extends Node {
  23594. static get type() {
  23595. return 'OutputStructNode';
  23596. }
  23597. /**
  23598. * Constructs a new output struct node. The constructor can be invoked with an
  23599. * arbitrary number of nodes representing the members.
  23600. *
  23601. * @param {...Node} members - A parameter list of nodes.
  23602. */
  23603. constructor( ...members ) {
  23604. super();
  23605. /**
  23606. * An array of nodes which defines the output.
  23607. *
  23608. * @type {Array<Node>}
  23609. */
  23610. this.members = members;
  23611. /**
  23612. * This flag can be used for type testing.
  23613. *
  23614. * @type {boolean}
  23615. * @readonly
  23616. * @default true
  23617. */
  23618. this.isOutputStructNode = true;
  23619. }
  23620. getNodeType( builder ) {
  23621. const properties = builder.getNodeProperties( this );
  23622. if ( properties.membersLayout === undefined ) {
  23623. const members = this.members;
  23624. const membersLayout = [];
  23625. for ( let i = 0; i < members.length; i ++ ) {
  23626. const name = 'm' + i;
  23627. const type = members[ i ].getNodeType( builder );
  23628. membersLayout.push( { name, type, index: i } );
  23629. }
  23630. properties.membersLayout = membersLayout;
  23631. properties.structType = builder.getOutputStructTypeFromNode( this, properties.membersLayout );
  23632. }
  23633. return properties.structType.name;
  23634. }
  23635. generate( builder ) {
  23636. const propertyName = builder.getOutputStructName();
  23637. const members = this.members;
  23638. const structPrefix = propertyName !== '' ? propertyName + '.' : '';
  23639. for ( let i = 0; i < members.length; i ++ ) {
  23640. const snippet = members[ i ].build( builder );
  23641. builder.addLineFlowCode( `${ structPrefix }m${ i } = ${ snippet }`, this );
  23642. }
  23643. return propertyName;
  23644. }
  23645. }
  23646. /**
  23647. * TSL function for creating an output struct node.
  23648. *
  23649. * @tsl
  23650. * @function
  23651. * @param {...Node} members - A parameter list of nodes.
  23652. * @returns {OutputStructNode}
  23653. */
  23654. const outputStruct = /*@__PURE__*/ nodeProxy( OutputStructNode );
  23655. /**
  23656. * Returns the MRT texture index for the given name.
  23657. *
  23658. * @param {Array<Texture>} textures - The textures of a MRT-configured render target.
  23659. * @param {string} name - The name of the MRT texture which index is requested.
  23660. * @return {number} The texture index.
  23661. */
  23662. function getTextureIndex( textures, name ) {
  23663. for ( let i = 0; i < textures.length; i ++ ) {
  23664. if ( textures[ i ].name === name ) {
  23665. return i;
  23666. }
  23667. }
  23668. return -1;
  23669. }
  23670. /**
  23671. * This node can be used setup a MRT context for rendering. A typical MRT setup for
  23672. * post-processing is shown below:
  23673. * ```js
  23674. * const mrtNode = mrt( {
  23675. * output: output,
  23676. * normal: normalView
  23677. * } ) );
  23678. * ```
  23679. * The MRT output is defined as a dictionary.
  23680. *
  23681. * @augments OutputStructNode
  23682. */
  23683. class MRTNode extends OutputStructNode {
  23684. static get type() {
  23685. return 'MRTNode';
  23686. }
  23687. /**
  23688. * Constructs a new output struct node.
  23689. *
  23690. * @param {Object<string, Node>} outputNodes - The MRT outputs.
  23691. */
  23692. constructor( outputNodes ) {
  23693. super();
  23694. /**
  23695. * A dictionary representing the MRT outputs. The key
  23696. * is the name of the output, the value the node which produces
  23697. * the output result.
  23698. *
  23699. * @type {Object<string, Node>}
  23700. */
  23701. this.outputNodes = outputNodes;
  23702. /**
  23703. * This flag can be used for type testing.
  23704. *
  23705. * @type {boolean}
  23706. * @readonly
  23707. * @default true
  23708. */
  23709. this.isMRTNode = true;
  23710. }
  23711. /**
  23712. * Returns `true` if the MRT node has an output with the given name.
  23713. *
  23714. * @param {string} name - The name of the output.
  23715. * @return {NodeBuilder} Whether the MRT node has an output for the given name or not.
  23716. */
  23717. has( name ) {
  23718. return this.outputNodes[ name ] !== undefined;
  23719. }
  23720. /**
  23721. * Returns the output node for the given name.
  23722. *
  23723. * @param {string} name - The name of the output.
  23724. * @return {Node} The output node.
  23725. */
  23726. get( name ) {
  23727. return this.outputNodes[ name ];
  23728. }
  23729. /**
  23730. * Merges the outputs of the given MRT node with the outputs of this node.
  23731. *
  23732. * @param {MRTNode} mrtNode - The MRT to merge.
  23733. * @return {MRTNode} A new MRT node with merged outputs..
  23734. */
  23735. merge( mrtNode ) {
  23736. const outputs = { ...this.outputNodes, ...mrtNode.outputNodes };
  23737. return mrt( outputs );
  23738. }
  23739. setup( builder ) {
  23740. const outputNodes = this.outputNodes;
  23741. const mrt = builder.renderer.getRenderTarget();
  23742. const members = [];
  23743. const textures = mrt.textures;
  23744. for ( const name in outputNodes ) {
  23745. const index = getTextureIndex( textures, name );
  23746. members[ index ] = vec4( outputNodes[ name ] );
  23747. }
  23748. this.members = members;
  23749. return super.setup( builder );
  23750. }
  23751. }
  23752. /**
  23753. * TSL function for creating a MRT node.
  23754. *
  23755. * @tsl
  23756. * @function
  23757. * @param {Object<string, Node>} outputNodes - The MRT outputs.
  23758. * @returns {MRTNode}
  23759. */
  23760. const mrt = /*@__PURE__*/ nodeProxy( MRTNode );
  23761. /**
  23762. * This node represents an operation that reinterprets the bit representation of a value
  23763. * in one type as a value in another type.
  23764. *
  23765. * @augments TempNode
  23766. */
  23767. class BitcastNode extends TempNode {
  23768. static get type() {
  23769. return 'BitcastNode';
  23770. }
  23771. /**
  23772. * Constructs a new bitcast node.
  23773. *
  23774. * @param {Node} valueNode - The value to convert.
  23775. * @param {string} conversionType - The type to convert to.
  23776. * @param {?string} [inputType = null] - The expected input data type of the bitcast operation.
  23777. */
  23778. constructor( valueNode, conversionType, inputType = null ) {
  23779. super();
  23780. /**
  23781. * The data to bitcast to a new type.
  23782. *
  23783. * @type {Node}
  23784. */
  23785. this.valueNode = valueNode;
  23786. /**
  23787. * The type the value will be converted to.
  23788. *
  23789. * @type {string}
  23790. */
  23791. this.conversionType = conversionType;
  23792. /**
  23793. * The expected input data type of the bitcast operation.
  23794. *
  23795. *
  23796. * @type {string}
  23797. * @default null
  23798. */
  23799. this.inputType = inputType;
  23800. /**
  23801. * This flag can be used for type testing.
  23802. *
  23803. * @type {boolean}
  23804. * @readonly
  23805. * @default true
  23806. */
  23807. this.isBitcastNode = true;
  23808. }
  23809. getNodeType( builder ) {
  23810. // GLSL aliasing
  23811. if ( this.inputType !== null ) {
  23812. const valueType = this.valueNode.getNodeType( builder );
  23813. const valueLength = builder.getTypeLength( valueType );
  23814. return builder.getTypeFromLength( valueLength, this.conversionType );
  23815. }
  23816. return this.conversionType;
  23817. }
  23818. generate( builder ) {
  23819. const type = this.getNodeType( builder );
  23820. let inputType = '';
  23821. if ( this.inputType !== null ) {
  23822. const valueType = this.valueNode.getNodeType( builder );
  23823. const valueTypeLength = builder.getTypeLength( valueType );
  23824. inputType = valueTypeLength === 1 ? this.inputType : builder.changeComponentType( valueType, this.inputType );
  23825. } else {
  23826. inputType = this.valueNode.getNodeType( builder );
  23827. }
  23828. return `${ builder.getBitcastMethod( type, inputType ) }( ${ this.valueNode.build( builder, inputType ) } )`;
  23829. }
  23830. }
  23831. /**
  23832. * Reinterpret the bit representation of a value in one type as a value in another type.
  23833. *
  23834. * @tsl
  23835. * @function
  23836. * @param {Node | number} x - The parameter.
  23837. * @param {string} y - The new type.
  23838. * @returns {Node}
  23839. */
  23840. const bitcast = /*@__PURE__*/ nodeProxyIntent( BitcastNode ).setParameterLength( 2 );
  23841. /**
  23842. * Bitcasts a float or a vector of floats to a corresponding integer type with the same element size.
  23843. *
  23844. * @tsl
  23845. * @function
  23846. * @param {Node<float>} value - The float or vector of floats to bitcast.
  23847. * @returns {BitcastNode}
  23848. */
  23849. const floatBitsToInt = ( value ) => new BitcastNode( value, 'int', 'float' );
  23850. /**
  23851. * Bitcasts a float or a vector of floats to a corresponding unsigned integer type with the same element size.
  23852. *
  23853. * @tsl
  23854. * @function
  23855. * @param {Node<float>} value - The float or vector of floats to bitcast.
  23856. * @returns {BitcastNode}
  23857. */
  23858. const floatBitsToUint = ( value ) => new BitcastNode( value, 'uint', 'float' );
  23859. /**
  23860. * Bitcasts an integer or a vector of integers to a corresponding float type with the same element size.
  23861. *
  23862. * @tsl
  23863. * @function
  23864. * @param {Node<int>} value - The integer or vector of integers to bitcast.
  23865. * @returns {BitcastNode}
  23866. */
  23867. const intBitsToFloat = ( value ) => new BitcastNode( value, 'float', 'int' );
  23868. /**
  23869. * Bitcast an unsigned integer or a vector of unsigned integers to a corresponding float type with the same element size.
  23870. *
  23871. * @tsl
  23872. * @function
  23873. * @param {Node<uint>} value - The unsigned integer or vector of unsigned integers to bitcast.
  23874. * @returns {BitcastNode}
  23875. */
  23876. const uintBitsToFloat = ( value ) => new BitcastNode( value, 'float', 'uint' );
  23877. /**
  23878. * Generates a hash value in the range `[0, 1]` from the given seed.
  23879. *
  23880. * @tsl
  23881. * @function
  23882. * @param {Node<float>} seed - The seed.
  23883. * @return {Node<float>} The hash value.
  23884. */
  23885. const hash = /*@__PURE__*/ Fn( ( [ seed ] ) => {
  23886. // Taken from https://www.shadertoy.com/view/XlGcRh, originally from pcg-random.org
  23887. const state = seed.toUint().mul( 747796405 ).add( 2891336453 );
  23888. const word = state.shiftRight( state.shiftRight( 28 ).add( 4 ) ).bitXor( state ).mul( 277803737 );
  23889. const result = word.shiftRight( 22 ).bitXor( word );
  23890. return result.toFloat().mul( 1 / 2 ** 32 ); // Convert to range [0, 1)
  23891. } );
  23892. /**
  23893. * A function that remaps the `[0,1]` interval into the `[0,1]` interval.
  23894. * The corners are mapped to `0` and the center to `1`.
  23895. * Reference: {@link https://iquilezles.org/articles/functions/}.
  23896. *
  23897. * @tsl
  23898. * @function
  23899. * @param {Node<float>} x - The value to remap.
  23900. * @param {Node<float>} k - Allows to control the remapping functions shape by rising the parabola to a power `k`.
  23901. * @return {Node<float>} The remapped value.
  23902. */
  23903. const parabola = ( x, k ) => pow( mul( 4.0, x.mul( sub( 1.0, x ) ) ), k );
  23904. /**
  23905. * A function that remaps the `[0,1]` interval into the `[0,1]` interval.
  23906. * Expands the sides and compresses the center, and keeps `0.5` mapped to `0.5`.
  23907. * Reference: {@link https://iquilezles.org/articles/functions/}.
  23908. *
  23909. * @tsl
  23910. * @function
  23911. * @param {Node<float>} x - The value to remap.
  23912. * @param {Node<float>} k - `k=1` is the identity curve,`k<1` produces the classic `gain()` shape, and `k>1` produces "s" shaped curves.
  23913. * @return {Node<float>} The remapped value.
  23914. */
  23915. 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 ) );
  23916. /**
  23917. * A function that remaps the `[0,1]` interval into the `[0,1]` interval.
  23918. * A generalization of the `parabola()`. Keeps the corners mapped to 0 but allows the control of the shape one either side of the curve.
  23919. * Reference: {@link https://iquilezles.org/articles/functions/}.
  23920. *
  23921. * @tsl
  23922. * @function
  23923. * @param {Node<float>} x - The value to remap.
  23924. * @param {Node<float>} a - First control parameter.
  23925. * @param {Node<float>} b - Second control parameter.
  23926. * @return {Node<float>} The remapped value.
  23927. */
  23928. const pcurve = ( x, a, b ) => pow( div( pow( x, a ), add( pow( x, a ), pow( sub( 1.0, x ), b ) ) ), 1.0 / a );
  23929. /**
  23930. * A phase shifted sinus curve that starts at zero and ends at zero, with bouncing behavior.
  23931. * Reference: {@link https://iquilezles.org/articles/functions/}.
  23932. *
  23933. * @tsl
  23934. * @function
  23935. * @param {Node<float>} x - The value to compute the sin for.
  23936. * @param {Node<float>} k - Controls the amount of bounces.
  23937. * @return {Node<float>} The result value.
  23938. */
  23939. const sinc = ( x, k ) => sin( PI.mul( k.mul( x ).sub( 1.0 ) ) ).div( PI.mul( k.mul( x ).sub( 1.0 ) ) );
  23940. // https://github.com/cabbibo/glsl-tri-noise-3d
  23941. const tri = /*@__PURE__*/ Fn( ( [ x ] ) => {
  23942. return x.fract().sub( .5 ).abs();
  23943. } ).setLayout( {
  23944. name: 'tri',
  23945. type: 'float',
  23946. inputs: [
  23947. { name: 'x', type: 'float' }
  23948. ]
  23949. } );
  23950. const tri3 = /*@__PURE__*/ Fn( ( [ p ] ) => {
  23951. 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. ) ) ) ) );
  23952. } ).setLayout( {
  23953. name: 'tri3',
  23954. type: 'vec3',
  23955. inputs: [
  23956. { name: 'p', type: 'vec3' }
  23957. ]
  23958. } );
  23959. /**
  23960. * Generates a noise value from the given position, speed and time parameters.
  23961. *
  23962. * @tsl
  23963. * @function
  23964. * @param {Node<vec3>} position - The position.
  23965. * @param {Node<float>} speed - The speed.
  23966. * @param {Node<float>} time - The time.
  23967. * @return {Node<float>} The generated noise.
  23968. */
  23969. const triNoise3D = /*@__PURE__*/ Fn( ( [ position, speed, time ] ) => {
  23970. const p = vec3( position ).toVar();
  23971. const z = float( 1.4 ).toVar();
  23972. const rz = float( 0.0 ).toVar();
  23973. const bp = vec3( p ).toVar();
  23974. Loop( { start: float( 0.0 ), end: float( 3.0 ), type: 'float', condition: '<=' }, () => {
  23975. const dg = vec3( tri3( bp.mul( 2.0 ) ) ).toVar();
  23976. p.addAssign( dg.add( time.mul( float( 0.1 ).mul( speed ) ) ) );
  23977. bp.mulAssign( 1.8 );
  23978. z.mulAssign( 1.5 );
  23979. p.mulAssign( 1.2 );
  23980. const t = float( tri( p.z.add( tri( p.x.add( tri( p.y ) ) ) ) ) ).toVar();
  23981. rz.addAssign( t.div( z ) );
  23982. bp.addAssign( 0.14 );
  23983. } );
  23984. return rz;
  23985. } ).setLayout( {
  23986. name: 'triNoise3D',
  23987. type: 'float',
  23988. inputs: [
  23989. { name: 'position', type: 'vec3' },
  23990. { name: 'speed', type: 'float' },
  23991. { name: 'time', type: 'float' }
  23992. ]
  23993. } );
  23994. /**
  23995. * This class allows to define multiple overloaded versions
  23996. * of the same function. Depending on the parameters of the function
  23997. * call, the node picks the best-fit overloaded version.
  23998. *
  23999. * @augments Node
  24000. */
  24001. class FunctionOverloadingNode extends Node {
  24002. static get type() {
  24003. return 'FunctionOverloadingNode';
  24004. }
  24005. /**
  24006. * Constructs a new function overloading node.
  24007. *
  24008. * @param {Array<Function>} functionNodes - Array of `Fn` function definitions.
  24009. * @param {...Node} parametersNodes - A list of parameter nodes.
  24010. */
  24011. constructor( functionNodes = [], ...parametersNodes ) {
  24012. super();
  24013. /**
  24014. * Array of `Fn` function definitions.
  24015. *
  24016. * @type {Array<Function>}
  24017. */
  24018. this.functionNodes = functionNodes;
  24019. /**
  24020. * A list of parameter nodes.
  24021. *
  24022. * @type {Array<Node>}
  24023. */
  24024. this.parametersNodes = parametersNodes;
  24025. /**
  24026. * The selected overloaded function call.
  24027. *
  24028. * @private
  24029. * @type {ShaderCallNodeInternal}
  24030. */
  24031. this._candidateFn = null;
  24032. /**
  24033. * This node is marked as global.
  24034. *
  24035. * @type {boolean}
  24036. * @default true
  24037. */
  24038. this.global = true;
  24039. }
  24040. /**
  24041. * This method is overwritten since the node type is inferred from
  24042. * the function's return type.
  24043. *
  24044. * @param {NodeBuilder} builder - The current node builder.
  24045. * @return {string} The node type.
  24046. */
  24047. getNodeType( builder ) {
  24048. const candidateFn = this.getCandidateFn( builder );
  24049. return candidateFn.shaderNode.layout.type;
  24050. }
  24051. /**
  24052. * Returns the candidate function for the current parameters.
  24053. *
  24054. * @param {NodeBuilder} builder - The current node builder.
  24055. * @return {FunctionNode} The candidate function.
  24056. */
  24057. getCandidateFn( builder ) {
  24058. const params = this.parametersNodes;
  24059. let candidateFn = this._candidateFn;
  24060. if ( candidateFn === null ) {
  24061. let bestCandidateFn = null;
  24062. let bestScore = -1;
  24063. for ( const functionNode of this.functionNodes ) {
  24064. const shaderNode = functionNode.shaderNode;
  24065. const layout = shaderNode.layout;
  24066. if ( layout === null ) {
  24067. throw new Error( 'FunctionOverloadingNode: FunctionNode must be a layout.' );
  24068. }
  24069. const inputs = layout.inputs;
  24070. if ( params.length === inputs.length ) {
  24071. let currentScore = 0;
  24072. for ( let i = 0; i < params.length; i ++ ) {
  24073. const param = params[ i ];
  24074. const input = inputs[ i ];
  24075. if ( param.getNodeType( builder ) === input.type ) {
  24076. currentScore ++;
  24077. }
  24078. }
  24079. if ( currentScore > bestScore ) {
  24080. bestCandidateFn = functionNode;
  24081. bestScore = currentScore;
  24082. }
  24083. }
  24084. }
  24085. this._candidateFn = candidateFn = bestCandidateFn;
  24086. }
  24087. return candidateFn;
  24088. }
  24089. /**
  24090. * Sets up the node for the current parameters.
  24091. *
  24092. * @param {NodeBuilder} builder - The current node builder.
  24093. * @return {Node} The setup node.
  24094. */
  24095. setup( builder ) {
  24096. const candidateFn = this.getCandidateFn( builder );
  24097. return candidateFn( ...this.parametersNodes );
  24098. }
  24099. }
  24100. const overloadingBaseFn = /*@__PURE__*/ nodeProxy( FunctionOverloadingNode );
  24101. /**
  24102. * TSL function for creating a function overloading node.
  24103. *
  24104. * @tsl
  24105. * @function
  24106. * @param {Array<Function>} functionNodes - Array of `Fn` function definitions.
  24107. * @returns {FunctionOverloadingNode}
  24108. */
  24109. const overloadingFn = ( functionNodes ) => ( ...params ) => overloadingBaseFn( functionNodes, ...params );
  24110. /**
  24111. * Represents the elapsed time in seconds.
  24112. *
  24113. * @tsl
  24114. * @type {UniformNode<float>}
  24115. */
  24116. const time = /*@__PURE__*/ uniform( 0 ).setGroup( renderGroup ).onRenderUpdate( ( frame ) => frame.time );
  24117. /**
  24118. * Represents the delta time in seconds.
  24119. *
  24120. * @tsl
  24121. * @type {UniformNode<float>}
  24122. */
  24123. const deltaTime = /*@__PURE__*/ uniform( 0 ).setGroup( renderGroup ).onRenderUpdate( ( frame ) => frame.deltaTime );
  24124. /**
  24125. * Represents the current frame ID.
  24126. *
  24127. * @tsl
  24128. * @type {UniformNode<uint>}
  24129. */
  24130. const frameId = /*@__PURE__*/ uniform( 0, 'uint' ).setGroup( renderGroup ).onRenderUpdate( ( frame ) => frame.frameId );
  24131. /**
  24132. * Generates a sine wave oscillation based on a timer.
  24133. *
  24134. * @tsl
  24135. * @function
  24136. * @param {Node<float>} t - The timer to generate the oscillation with.
  24137. * @return {Node<float>} The oscillation node.
  24138. */
  24139. const oscSine = ( t = time ) => t.add( 0.75 ).mul( Math.PI * 2 ).sin().mul( 0.5 ).add( 0.5 );
  24140. /**
  24141. * Generates a square wave oscillation based on a timer.
  24142. *
  24143. * @tsl
  24144. * @function
  24145. * @param {Node<float>} t - The timer to generate the oscillation with.
  24146. * @return {Node<float>} The oscillation node.
  24147. */
  24148. const oscSquare = ( t = time ) => t.fract().round();
  24149. /**
  24150. * Generates a triangle wave oscillation based on a timer.
  24151. *
  24152. * @tsl
  24153. * @function
  24154. * @param {Node<float>} t - The timer to generate the oscillation with.
  24155. * @return {Node<float>} The oscillation node.
  24156. */
  24157. const oscTriangle = ( t = time ) => t.add( 0.5 ).fract().mul( 2 ).sub( 1 ).abs();
  24158. /**
  24159. * Generates a sawtooth wave oscillation based on a timer.
  24160. *
  24161. * @tsl
  24162. * @function
  24163. * @param {Node<float>} t - The timer to generate the oscillation with.
  24164. * @return {Node<float>} The oscillation node.
  24165. */
  24166. const oscSawtooth = ( t = time ) => t.fract();
  24167. /**
  24168. * Rotates the given uv coordinates around a center point
  24169. *
  24170. * @tsl
  24171. * @function
  24172. * @param {Node<vec2>} uv - The uv coordinates.
  24173. * @param {Node<float>} rotation - The rotation defined in radians.
  24174. * @param {Node<vec2>} center - The center of rotation
  24175. * @return {Node<vec2>} The rotated uv coordinates.
  24176. */
  24177. const rotateUV = /*@__PURE__*/ Fn( ( [ uv, rotation, center = vec2( 0.5 ) ] ) => {
  24178. return rotate( uv.sub( center ), rotation ).add( center );
  24179. } );
  24180. /**
  24181. * Applies a spherical warping effect to the given uv coordinates.
  24182. *
  24183. * @tsl
  24184. * @function
  24185. * @param {Node<vec2>} uv - The uv coordinates.
  24186. * @param {Node<float>} strength - The strength of the effect.
  24187. * @param {Node<vec2>} center - The center point
  24188. * @return {Node<vec2>} The updated uv coordinates.
  24189. */
  24190. const spherizeUV = /*@__PURE__*/ Fn( ( [ uv, strength, center = vec2( 0.5 ) ] ) => {
  24191. const delta = uv.sub( center );
  24192. const delta2 = delta.dot( delta );
  24193. const delta4 = delta2.mul( delta2 );
  24194. const deltaOffset = delta4.mul( strength );
  24195. return uv.add( delta.mul( deltaOffset ) );
  24196. } );
  24197. /**
  24198. * This can be used to achieve a billboarding behavior for flat meshes. That means they are
  24199. * oriented always towards the camera.
  24200. *
  24201. * ```js
  24202. * material.vertexNode = billboarding();
  24203. * ```
  24204. *
  24205. * @tsl
  24206. * @function
  24207. * @param {Object} config - The configuration object.
  24208. * @param {?Node<vec3>} [config.position=null] - Can be used to define the vertex positions in world space.
  24209. * @param {boolean} [config.horizontal=true] - Whether to follow the camera rotation horizontally or not.
  24210. * @param {boolean} [config.vertical=false] - Whether to follow the camera rotation vertically or not.
  24211. * @return {Node<vec3>} The updated vertex position in clip space.
  24212. */
  24213. const billboarding = /*@__PURE__*/ Fn( ( { position = null, horizontal = true, vertical = false } ) => {
  24214. let worldMatrix;
  24215. if ( position !== null ) {
  24216. worldMatrix = modelWorldMatrix.toVar();
  24217. worldMatrix[ 3 ][ 0 ] = position.x;
  24218. worldMatrix[ 3 ][ 1 ] = position.y;
  24219. worldMatrix[ 3 ][ 2 ] = position.z;
  24220. } else {
  24221. worldMatrix = modelWorldMatrix;
  24222. }
  24223. const modelViewMatrix = cameraViewMatrix.mul( worldMatrix );
  24224. if ( defined( horizontal ) ) {
  24225. modelViewMatrix[ 0 ][ 0 ] = modelWorldMatrix[ 0 ].length();
  24226. modelViewMatrix[ 0 ][ 1 ] = 0;
  24227. modelViewMatrix[ 0 ][ 2 ] = 0;
  24228. }
  24229. if ( defined( vertical ) ) {
  24230. modelViewMatrix[ 1 ][ 0 ] = 0;
  24231. modelViewMatrix[ 1 ][ 1 ] = modelWorldMatrix[ 1 ].length();
  24232. modelViewMatrix[ 1 ][ 2 ] = 0;
  24233. }
  24234. modelViewMatrix[ 2 ][ 0 ] = 0;
  24235. modelViewMatrix[ 2 ][ 1 ] = 0;
  24236. modelViewMatrix[ 2 ][ 2 ] = 1;
  24237. return cameraProjectionMatrix.mul( modelViewMatrix ).mul( positionLocal );
  24238. } );
  24239. /**
  24240. * A special version of a screen uv function that involves a depth comparison
  24241. * when computing the final uvs. The function mitigates visual errors when
  24242. * using viewport texture nodes for refraction purposes. Without this function
  24243. * objects in front of a refractive surface might appear on the refractive surface
  24244. * which is incorrect.
  24245. *
  24246. * @tsl
  24247. * @function
  24248. * @param {?Node<vec2>} uv - Optional uv coordinates. By default `screenUV` is used.
  24249. * @return {Node<vec2>} The update uv coordinates.
  24250. */
  24251. const viewportSafeUV = /*@__PURE__*/ Fn( ( [ uv = null ] ) => {
  24252. const depth = linearDepth();
  24253. const depthDiff = linearDepth( viewportDepthTexture( uv ) ).sub( depth );
  24254. const finalUV = depthDiff.lessThan( 0 ).select( screenUV, uv );
  24255. return finalUV;
  24256. } );
  24257. /**
  24258. * Can be used to compute texture coordinates for animated sprite sheets.
  24259. *
  24260. * ```js
  24261. * const uvNode = spritesheetUV( vec2( 6, 6 ), uv(), time.mul( animationSpeed ) );
  24262. *
  24263. * material.colorNode = texture( spriteSheet, uvNode );
  24264. * ```
  24265. *
  24266. * @augments Node
  24267. */
  24268. class SpriteSheetUVNode extends Node {
  24269. static get type() {
  24270. return 'SpriteSheetUVNode';
  24271. }
  24272. /**
  24273. * Constructs a new sprite sheet uv node.
  24274. *
  24275. * @param {Node<vec2>} countNode - The node that defines the number of sprites in the x and y direction (e.g 6x6).
  24276. * @param {Node<vec2>} [uvNode=uv()] - The uv node.
  24277. * @param {Node<float>} [frameNode=float()] - The node that defines the current frame/sprite.
  24278. */
  24279. constructor( countNode, uvNode = uv$1(), frameNode = float( 0 ) ) {
  24280. super( 'vec2' );
  24281. /**
  24282. * The node that defines the number of sprites in the x and y direction (e.g 6x6).
  24283. *
  24284. * @type {Node<vec2>}
  24285. */
  24286. this.countNode = countNode;
  24287. /**
  24288. * The uv node.
  24289. *
  24290. * @type {Node<vec2>}
  24291. */
  24292. this.uvNode = uvNode;
  24293. /**
  24294. * The node that defines the current frame/sprite.
  24295. *
  24296. * @type {Node<float>}
  24297. */
  24298. this.frameNode = frameNode;
  24299. }
  24300. setup() {
  24301. const { frameNode, uvNode, countNode } = this;
  24302. const { width, height } = countNode;
  24303. const frameNum = frameNode.mod( width.mul( height ) ).floor();
  24304. const column = frameNum.mod( width );
  24305. const row = height.sub( frameNum.add( 1 ).div( width ).ceil() );
  24306. const scale = countNode.reciprocal();
  24307. const uvFrameOffset = vec2( column, row );
  24308. return uvNode.add( uvFrameOffset ).mul( scale );
  24309. }
  24310. }
  24311. /**
  24312. * TSL function for creating a sprite sheet uv node.
  24313. *
  24314. * @tsl
  24315. * @function
  24316. * @param {Node<vec2>} countNode - The node that defines the number of sprites in the x and y direction (e.g 6x6).
  24317. * @param {?Node<vec2>} [uvNode=uv()] - The uv node.
  24318. * @param {?Node<float>} [frameNode=float()] - The node that defines the current frame/sprite.
  24319. * @returns {SpriteSheetUVNode}
  24320. */
  24321. const spritesheetUV = /*@__PURE__*/ nodeProxy( SpriteSheetUVNode ).setParameterLength( 3 );
  24322. /**
  24323. * TSL function for creating a triplanar textures node.
  24324. *
  24325. * Can be used for triplanar texture mapping.
  24326. *
  24327. * ```js
  24328. * material.colorNode = triplanarTexture( texture( diffuseMap ) );
  24329. * ```
  24330. *
  24331. * @tsl
  24332. * @function
  24333. * @param {Node} textureXNode - First texture node.
  24334. * @param {?Node} [textureYNode=null] - Second texture node. When not set, the shader will sample from `textureXNode` instead.
  24335. * @param {?Node} [textureZNode=null] - Third texture node. When not set, the shader will sample from `textureXNode` instead.
  24336. * @param {?Node<float>} [scaleNode=float(1)] - The scale node.
  24337. * @param {?Node<vec3>} [positionNode=positionLocal] - Vertex positions in local space.
  24338. * @param {?Node<vec3>} [normalNode=normalLocal] - Normals in local space.
  24339. * @returns {Node<vec4>}
  24340. */
  24341. const triplanarTextures = /*@__PURE__*/ Fn( ( [ textureXNode, textureYNode = null, textureZNode = null, scaleNode = float( 1 ), positionNode = positionLocal, normalNode = normalLocal ] ) => {
  24342. // Reference: https://github.com/keijiro/StandardTriplanar
  24343. // Blending factor of triplanar mapping
  24344. let bf = normalNode.abs().normalize();
  24345. bf = bf.div( bf.dot( vec3( 1.0 ) ) );
  24346. // Triplanar mapping
  24347. const tx = positionNode.yz.mul( scaleNode );
  24348. const ty = positionNode.zx.mul( scaleNode );
  24349. const tz = positionNode.xy.mul( scaleNode );
  24350. // Base color
  24351. const textureX = textureXNode.value;
  24352. const textureY = textureYNode !== null ? textureYNode.value : textureX;
  24353. const textureZ = textureZNode !== null ? textureZNode.value : textureX;
  24354. const cx = texture( textureX, tx ).mul( bf.x );
  24355. const cy = texture( textureY, ty ).mul( bf.y );
  24356. const cz = texture( textureZ, tz ).mul( bf.z );
  24357. return add( cx, cy, cz );
  24358. } );
  24359. /**
  24360. * TSL function for creating a triplanar textures node.
  24361. *
  24362. * @tsl
  24363. * @function
  24364. * @param {Node} textureXNode - First texture node.
  24365. * @param {?Node} [textureYNode=null] - Second texture node. When not set, the shader will sample from `textureXNode` instead.
  24366. * @param {?Node} [textureZNode=null] - Third texture node. When not set, the shader will sample from `textureXNode` instead.
  24367. * @param {?Node<float>} [scaleNode=float(1)] - The scale node.
  24368. * @param {?Node<vec3>} [positionNode=positionLocal] - Vertex positions in local space.
  24369. * @param {?Node<vec3>} [normalNode=normalLocal] - Normals in local space.
  24370. * @returns {Node<vec4>}
  24371. */
  24372. const triplanarTexture = ( ...params ) => triplanarTextures( ...params );
  24373. const _reflectorPlane = new Plane();
  24374. const _normal = new Vector3();
  24375. const _reflectorWorldPosition = new Vector3();
  24376. const _cameraWorldPosition = new Vector3();
  24377. const _rotationMatrix = new Matrix4();
  24378. const _lookAtPosition = new Vector3( 0, 0, -1 );
  24379. const clipPlane = new Vector4();
  24380. const _view = new Vector3();
  24381. const _target = new Vector3();
  24382. const _q = new Vector4();
  24383. const _size$2 = new Vector2();
  24384. const _defaultRT = new RenderTarget();
  24385. const _defaultUV = screenUV.flipX();
  24386. _defaultRT.depthTexture = new DepthTexture( 1, 1 );
  24387. let _inReflector = false;
  24388. /**
  24389. * This node can be used to implement mirror-like flat reflective surfaces.
  24390. *
  24391. * ```js
  24392. * const groundReflector = reflector();
  24393. * material.colorNode = groundReflector;
  24394. *
  24395. * const plane = new Mesh( geometry, material );
  24396. * plane.add( groundReflector.target );
  24397. * ```
  24398. *
  24399. * @augments TextureNode
  24400. */
  24401. class ReflectorNode extends TextureNode {
  24402. static get type() {
  24403. return 'ReflectorNode';
  24404. }
  24405. /**
  24406. * Constructs a new reflector node.
  24407. *
  24408. * @param {Object} [parameters={}] - An object holding configuration parameters.
  24409. * @param {Object3D} [parameters.target=new Object3D()] - The 3D object the reflector is linked to.
  24410. * @param {number} [parameters.resolutionScale=1] - The resolution scale.
  24411. * @param {boolean} [parameters.generateMipmaps=false] - Whether mipmaps should be generated or not.
  24412. * @param {boolean} [parameters.bounces=true] - Whether reflectors can render other reflector nodes or not.
  24413. * @param {boolean} [parameters.depth=false] - Whether depth data should be generated or not.
  24414. * @param {number} [parameters.samples] - Anti-Aliasing samples of the internal render-target.
  24415. * @param {TextureNode} [parameters.defaultTexture] - The default texture node.
  24416. * @param {ReflectorBaseNode} [parameters.reflector] - The reflector base node.
  24417. */
  24418. constructor( parameters = {} ) {
  24419. super( parameters.defaultTexture || _defaultRT.texture, _defaultUV );
  24420. /**
  24421. * A reference to the internal reflector base node which holds the actual implementation.
  24422. *
  24423. * @private
  24424. * @type {ReflectorBaseNode}
  24425. * @default ReflectorBaseNode
  24426. */
  24427. this._reflectorBaseNode = parameters.reflector || new ReflectorBaseNode( this, parameters );
  24428. /**
  24429. * A reference to the internal depth node.
  24430. *
  24431. * @private
  24432. * @type {?Node}
  24433. * @default null
  24434. */
  24435. this._depthNode = null;
  24436. this.setUpdateMatrix( false );
  24437. }
  24438. /**
  24439. * A reference to the internal reflector node.
  24440. *
  24441. * @type {ReflectorBaseNode}
  24442. */
  24443. get reflector() {
  24444. return this._reflectorBaseNode;
  24445. }
  24446. /**
  24447. * A reference to 3D object the reflector is linked to.
  24448. *
  24449. * @type {Object3D}
  24450. */
  24451. get target() {
  24452. return this._reflectorBaseNode.target;
  24453. }
  24454. /**
  24455. * Returns a node representing the mirror's depth. That can be used
  24456. * to implement more advanced reflection effects like distance attenuation.
  24457. *
  24458. * @return {Node} The depth node.
  24459. */
  24460. getDepthNode() {
  24461. if ( this._depthNode === null ) {
  24462. if ( this._reflectorBaseNode.depth !== true ) {
  24463. throw new Error( 'THREE.ReflectorNode: Depth node can only be requested when the reflector is created with { depth: true }. ' );
  24464. }
  24465. this._depthNode = nodeObject( new ReflectorNode( {
  24466. defaultTexture: _defaultRT.depthTexture,
  24467. reflector: this._reflectorBaseNode
  24468. } ) );
  24469. }
  24470. return this._depthNode;
  24471. }
  24472. setup( builder ) {
  24473. // ignore if used in post-processing
  24474. if ( ! builder.object.isQuadMesh ) this._reflectorBaseNode.build( builder );
  24475. return super.setup( builder );
  24476. }
  24477. clone() {
  24478. const newNode = new this.constructor( this.reflectorNode );
  24479. newNode.uvNode = this.uvNode;
  24480. newNode.levelNode = this.levelNode;
  24481. newNode.biasNode = this.biasNode;
  24482. newNode.sampler = this.sampler;
  24483. newNode.depthNode = this.depthNode;
  24484. newNode.compareNode = this.compareNode;
  24485. newNode.gradNode = this.gradNode;
  24486. newNode.offsetNode = this.offsetNode;
  24487. newNode._reflectorBaseNode = this._reflectorBaseNode;
  24488. return newNode;
  24489. }
  24490. /**
  24491. * Frees internal resources. Should be called when the node is no longer in use.
  24492. */
  24493. dispose() {
  24494. super.dispose();
  24495. this._reflectorBaseNode.dispose();
  24496. }
  24497. }
  24498. /**
  24499. * Holds the actual implementation of the reflector.
  24500. *
  24501. * TODO: Explain why `ReflectorBaseNode`. Originally the entire logic was implemented
  24502. * in `ReflectorNode`, see #29619.
  24503. *
  24504. * @private
  24505. * @augments Node
  24506. */
  24507. class ReflectorBaseNode extends Node {
  24508. static get type() {
  24509. return 'ReflectorBaseNode';
  24510. }
  24511. /**
  24512. * Constructs a new reflector base node.
  24513. *
  24514. * @param {TextureNode} textureNode - Represents the rendered reflections as a texture node.
  24515. * @param {Object} [parameters={}] - An object holding configuration parameters.
  24516. * @param {Object3D} [parameters.target=new Object3D()] - The 3D object the reflector is linked to.
  24517. * @param {number} [parameters.resolutionScale=1] - The resolution scale.
  24518. * @param {boolean} [parameters.generateMipmaps=false] - Whether mipmaps should be generated or not.
  24519. * @param {boolean} [parameters.bounces=true] - Whether reflectors can render other reflector nodes or not.
  24520. * @param {boolean} [parameters.depth=false] - Whether depth data should be generated or not.
  24521. * @param {number} [parameters.samples] - Anti-Aliasing samples of the internal render-target.
  24522. */
  24523. constructor( textureNode, parameters = {} ) {
  24524. super();
  24525. const {
  24526. target = new Object3D(),
  24527. resolutionScale = 1,
  24528. generateMipmaps = false,
  24529. bounces = true,
  24530. depth = false,
  24531. samples = 0
  24532. } = parameters;
  24533. /**
  24534. * Represents the rendered reflections as a texture node.
  24535. *
  24536. * @type {TextureNode}
  24537. */
  24538. this.textureNode = textureNode;
  24539. /**
  24540. * The 3D object the reflector is linked to.
  24541. *
  24542. * @type {Object3D}
  24543. * @default {new Object3D()}
  24544. */
  24545. this.target = target;
  24546. /**
  24547. * The resolution scale.
  24548. *
  24549. * @type {number}
  24550. * @default {1}
  24551. */
  24552. this.resolutionScale = resolutionScale;
  24553. if ( parameters.resolution !== undefined ) {
  24554. warnOnce( 'ReflectorNode: The "resolution" parameter has been renamed to "resolutionScale".' ); // @deprecated r180
  24555. this.resolutionScale = parameters.resolution;
  24556. }
  24557. /**
  24558. * Whether mipmaps should be generated or not.
  24559. *
  24560. * @type {boolean}
  24561. * @default {false}
  24562. */
  24563. this.generateMipmaps = generateMipmaps;
  24564. /**
  24565. * Whether reflectors can render other reflector nodes or not.
  24566. *
  24567. * @type {boolean}
  24568. * @default {true}
  24569. */
  24570. this.bounces = bounces;
  24571. /**
  24572. * Whether depth data should be generated or not.
  24573. *
  24574. * @type {boolean}
  24575. * @default {false}
  24576. */
  24577. this.depth = depth;
  24578. /**
  24579. * The number of anti-aliasing samples for the render-target
  24580. *
  24581. * @type {number}
  24582. * @default {0}
  24583. */
  24584. this.samples = samples;
  24585. /**
  24586. * The `updateBeforeType` is set to `NodeUpdateType.RENDER` when {@link ReflectorBaseNode#bounces}
  24587. * is `true`. Otherwise it's `NodeUpdateType.FRAME`.
  24588. *
  24589. * @type {string}
  24590. * @default 'render'
  24591. */
  24592. this.updateBeforeType = bounces ? NodeUpdateType.RENDER : NodeUpdateType.FRAME;
  24593. /**
  24594. * Weak map for managing virtual cameras.
  24595. *
  24596. * @type {WeakMap<Camera, Camera>}
  24597. */
  24598. this.virtualCameras = new WeakMap();
  24599. /**
  24600. * Weak map for managing render targets.
  24601. *
  24602. * @type {Map<Camera, RenderTarget>}
  24603. */
  24604. this.renderTargets = new Map();
  24605. /**
  24606. * Force render even if reflector is facing away from camera.
  24607. *
  24608. * @type {boolean}
  24609. * @default {false}
  24610. */
  24611. this.forceUpdate = false;
  24612. /**
  24613. * Whether the reflector has been rendered or not.
  24614. *
  24615. * When the reflector is facing away from the camera,
  24616. * this flag is set to `false` and the texture will be empty(black).
  24617. *
  24618. * @type {boolean}
  24619. * @default {false}
  24620. */
  24621. this.hasOutput = false;
  24622. }
  24623. /**
  24624. * Updates the resolution of the internal render target.
  24625. *
  24626. * @private
  24627. * @param {RenderTarget} renderTarget - The render target to resize.
  24628. * @param {Renderer} renderer - The renderer that is used to determine the new size.
  24629. */
  24630. _updateResolution( renderTarget, renderer ) {
  24631. const resolution = this.resolutionScale;
  24632. renderer.getDrawingBufferSize( _size$2 );
  24633. renderTarget.setSize( Math.round( _size$2.width * resolution ), Math.round( _size$2.height * resolution ) );
  24634. }
  24635. setup( builder ) {
  24636. this._updateResolution( _defaultRT, builder.renderer );
  24637. return super.setup( builder );
  24638. }
  24639. /**
  24640. * Frees internal resources. Should be called when the node is no longer in use.
  24641. */
  24642. dispose() {
  24643. super.dispose();
  24644. for ( const renderTarget of this.renderTargets.values() ) {
  24645. renderTarget.dispose();
  24646. }
  24647. }
  24648. /**
  24649. * Returns a virtual camera for the given camera. The virtual camera is used to
  24650. * render the scene from the reflector's view so correct reflections can be produced.
  24651. *
  24652. * @param {Camera} camera - The scene's camera.
  24653. * @return {Camera} The corresponding virtual camera.
  24654. */
  24655. getVirtualCamera( camera ) {
  24656. let virtualCamera = this.virtualCameras.get( camera );
  24657. if ( virtualCamera === undefined ) {
  24658. virtualCamera = camera.clone();
  24659. this.virtualCameras.set( camera, virtualCamera );
  24660. }
  24661. return virtualCamera;
  24662. }
  24663. /**
  24664. * Returns a render target for the given camera. The reflections are rendered
  24665. * into this render target.
  24666. *
  24667. * @param {Camera} camera - The scene's camera.
  24668. * @return {RenderTarget} The render target.
  24669. */
  24670. getRenderTarget( camera ) {
  24671. let renderTarget = this.renderTargets.get( camera );
  24672. if ( renderTarget === undefined ) {
  24673. renderTarget = new RenderTarget( 0, 0, { type: HalfFloatType, samples: this.samples } );
  24674. if ( this.generateMipmaps === true ) {
  24675. renderTarget.texture.minFilter = LinearMipMapLinearFilter;
  24676. renderTarget.texture.generateMipmaps = true;
  24677. }
  24678. if ( this.depth === true ) {
  24679. renderTarget.depthTexture = new DepthTexture();
  24680. }
  24681. this.renderTargets.set( camera, renderTarget );
  24682. }
  24683. return renderTarget;
  24684. }
  24685. updateBefore( frame ) {
  24686. if ( this.bounces === false && _inReflector ) return false;
  24687. _inReflector = true;
  24688. const { scene, camera, renderer, material } = frame;
  24689. const { target } = this;
  24690. const virtualCamera = this.getVirtualCamera( camera );
  24691. const renderTarget = this.getRenderTarget( virtualCamera );
  24692. renderer.getDrawingBufferSize( _size$2 );
  24693. this._updateResolution( renderTarget, renderer );
  24694. //
  24695. _reflectorWorldPosition.setFromMatrixPosition( target.matrixWorld );
  24696. _cameraWorldPosition.setFromMatrixPosition( camera.matrixWorld );
  24697. _rotationMatrix.extractRotation( target.matrixWorld );
  24698. _normal.set( 0, 0, 1 );
  24699. _normal.applyMatrix4( _rotationMatrix );
  24700. _view.subVectors( _reflectorWorldPosition, _cameraWorldPosition );
  24701. // Avoid rendering when reflector is facing away unless forcing an update
  24702. const isFacingAway = _view.dot( _normal ) > 0;
  24703. let needsClear = false;
  24704. if ( isFacingAway === true && this.forceUpdate === false ) {
  24705. if ( this.hasOutput === false ) {
  24706. _inReflector = false;
  24707. return;
  24708. }
  24709. needsClear = true;
  24710. }
  24711. _view.reflect( _normal ).negate();
  24712. _view.add( _reflectorWorldPosition );
  24713. _rotationMatrix.extractRotation( camera.matrixWorld );
  24714. _lookAtPosition.set( 0, 0, -1 );
  24715. _lookAtPosition.applyMatrix4( _rotationMatrix );
  24716. _lookAtPosition.add( _cameraWorldPosition );
  24717. _target.subVectors( _reflectorWorldPosition, _lookAtPosition );
  24718. _target.reflect( _normal ).negate();
  24719. _target.add( _reflectorWorldPosition );
  24720. //
  24721. virtualCamera.coordinateSystem = camera.coordinateSystem;
  24722. virtualCamera.position.copy( _view );
  24723. virtualCamera.up.set( 0, 1, 0 );
  24724. virtualCamera.up.applyMatrix4( _rotationMatrix );
  24725. virtualCamera.up.reflect( _normal );
  24726. virtualCamera.lookAt( _target );
  24727. virtualCamera.near = camera.near;
  24728. virtualCamera.far = camera.far;
  24729. virtualCamera.updateMatrixWorld();
  24730. virtualCamera.projectionMatrix.copy( camera.projectionMatrix );
  24731. // Now update projection matrix with new clip plane, implementing code from: http://www.terathon.com/code/oblique.html
  24732. // Paper explaining this technique: http://www.terathon.com/lengyel/Lengyel-Oblique.pdf
  24733. _reflectorPlane.setFromNormalAndCoplanarPoint( _normal, _reflectorWorldPosition );
  24734. _reflectorPlane.applyMatrix4( virtualCamera.matrixWorldInverse );
  24735. clipPlane.set( _reflectorPlane.normal.x, _reflectorPlane.normal.y, _reflectorPlane.normal.z, _reflectorPlane.constant );
  24736. const projectionMatrix = virtualCamera.projectionMatrix;
  24737. _q.x = ( Math.sign( clipPlane.x ) + projectionMatrix.elements[ 8 ] ) / projectionMatrix.elements[ 0 ];
  24738. _q.y = ( Math.sign( clipPlane.y ) + projectionMatrix.elements[ 9 ] ) / projectionMatrix.elements[ 5 ];
  24739. _q.z = -1;
  24740. _q.w = ( 1.0 + projectionMatrix.elements[ 10 ] ) / projectionMatrix.elements[ 14 ];
  24741. // Calculate the scaled plane vector
  24742. clipPlane.multiplyScalar( 1.0 / clipPlane.dot( _q ) );
  24743. const clipBias = 0;
  24744. // Replacing the third row of the projection matrix
  24745. projectionMatrix.elements[ 2 ] = clipPlane.x;
  24746. projectionMatrix.elements[ 6 ] = clipPlane.y;
  24747. projectionMatrix.elements[ 10 ] = ( renderer.coordinateSystem === WebGPUCoordinateSystem ) ? ( clipPlane.z - clipBias ) : ( clipPlane.z + 1.0 - clipBias );
  24748. projectionMatrix.elements[ 14 ] = clipPlane.w;
  24749. //
  24750. this.textureNode.value = renderTarget.texture;
  24751. if ( this.depth === true ) {
  24752. this.textureNode.getDepthNode().value = renderTarget.depthTexture;
  24753. }
  24754. material.visible = false;
  24755. const currentRenderTarget = renderer.getRenderTarget();
  24756. const currentMRT = renderer.getMRT();
  24757. const currentAutoClear = renderer.autoClear;
  24758. renderer.setMRT( null );
  24759. renderer.setRenderTarget( renderTarget );
  24760. renderer.autoClear = true;
  24761. const previousName = scene.name;
  24762. scene.name = ( scene.name || 'Scene' ) + ' [ Reflector ]'; // TODO: Add bounce index
  24763. if ( needsClear ) {
  24764. renderer.clear();
  24765. this.hasOutput = false;
  24766. } else {
  24767. renderer.render( scene, virtualCamera );
  24768. this.hasOutput = true;
  24769. }
  24770. scene.name = previousName;
  24771. renderer.setMRT( currentMRT );
  24772. renderer.setRenderTarget( currentRenderTarget );
  24773. renderer.autoClear = currentAutoClear;
  24774. material.visible = true;
  24775. _inReflector = false;
  24776. this.forceUpdate = false;
  24777. }
  24778. /**
  24779. * The resolution scale.
  24780. *
  24781. * @deprecated
  24782. * @type {number}
  24783. * @default {1}
  24784. */
  24785. get resolution() {
  24786. warnOnce( 'ReflectorNode: The "resolution" property has been renamed to "resolutionScale".' ); // @deprecated r180
  24787. return this.resolutionScale;
  24788. }
  24789. set resolution( value ) {
  24790. warnOnce( 'ReflectorNode: The "resolution" property has been renamed to "resolutionScale".' ); // @deprecated r180
  24791. this.resolutionScale = value;
  24792. }
  24793. }
  24794. /**
  24795. * TSL function for creating a reflector node.
  24796. *
  24797. * @tsl
  24798. * @function
  24799. * @param {Object} [parameters={}] - An object holding configuration parameters.
  24800. * @param {Object3D} [parameters.target=new Object3D()] - The 3D object the reflector is linked to.
  24801. * @param {number} [parameters.resolution=1] - The resolution scale.
  24802. * @param {boolean} [parameters.generateMipmaps=false] - Whether mipmaps should be generated or not.
  24803. * @param {boolean} [parameters.bounces=true] - Whether reflectors can render other reflector nodes or not.
  24804. * @param {boolean} [parameters.depth=false] - Whether depth data should be generated or not.
  24805. * @param {number} [parameters.samples] - Anti-Aliasing samples of the internal render-target.
  24806. * @param {TextureNode} [parameters.defaultTexture] - The default texture node.
  24807. * @param {ReflectorBaseNode} [parameters.reflector] - The reflector base node.
  24808. * @returns {ReflectorNode}
  24809. */
  24810. const reflector = ( parameters ) => nodeObject( new ReflectorNode( parameters ) );
  24811. const _camera = /*@__PURE__*/ new OrthographicCamera( -1, 1, 1, -1, 0, 1 );
  24812. /**
  24813. * The purpose of this special geometry is to fill the entire viewport with a single triangle.
  24814. *
  24815. * Reference: {@link https://github.com/mrdoob/three.js/pull/21358}
  24816. *
  24817. * @private
  24818. * @augments BufferGeometry
  24819. */
  24820. class QuadGeometry extends BufferGeometry {
  24821. /**
  24822. * Constructs a new quad geometry.
  24823. *
  24824. * @param {boolean} [flipY=false] - Whether the uv coordinates should be flipped along the vertical axis or not.
  24825. */
  24826. constructor( flipY = false ) {
  24827. super();
  24828. const uv = flipY === false ? [ 0, -1, 0, 1, 2, 1 ] : [ 0, 2, 0, 0, 2, 0 ];
  24829. this.setAttribute( 'position', new Float32BufferAttribute( [ -1, 3, 0, -1, -1, 0, 3, -1, 0 ], 3 ) );
  24830. this.setAttribute( 'uv', new Float32BufferAttribute( uv, 2 ) );
  24831. }
  24832. }
  24833. const _geometry = /*@__PURE__*/ new QuadGeometry();
  24834. /**
  24835. * This module is a helper for passes which need to render a full
  24836. * screen effect which is quite common in context of post processing.
  24837. *
  24838. * The intended usage is to reuse a single quad mesh for rendering
  24839. * subsequent passes by just reassigning the `material` reference.
  24840. *
  24841. * Note: This module can only be used with `WebGPURenderer`.
  24842. *
  24843. * @augments Mesh
  24844. */
  24845. class QuadMesh extends Mesh {
  24846. /**
  24847. * Constructs a new quad mesh.
  24848. *
  24849. * @param {?Material} [material=null] - The material to render the quad mesh with.
  24850. */
  24851. constructor( material = null ) {
  24852. super( _geometry, material );
  24853. /**
  24854. * The camera to render the quad mesh with.
  24855. *
  24856. * @type {OrthographicCamera}
  24857. * @readonly
  24858. */
  24859. this.camera = _camera;
  24860. /**
  24861. * This flag can be used for type testing.
  24862. *
  24863. * @type {boolean}
  24864. * @readonly
  24865. * @default true
  24866. */
  24867. this.isQuadMesh = true;
  24868. }
  24869. /**
  24870. * Async version of `render()`.
  24871. *
  24872. * @async
  24873. * @deprecated
  24874. * @param {Renderer} renderer - The renderer.
  24875. * @return {Promise} A Promise that resolves when the render has been finished.
  24876. */
  24877. async renderAsync( renderer ) {
  24878. warnOnce( 'QuadMesh: "renderAsync()" has been deprecated. Use "render()" and "await renderer.init();" when creating the renderer.' ); // @deprecated r181
  24879. await renderer.init();
  24880. renderer.render( this, _camera );
  24881. }
  24882. /**
  24883. * Renders the quad mesh
  24884. *
  24885. * @param {Renderer} renderer - The renderer.
  24886. */
  24887. render( renderer ) {
  24888. renderer.render( this, _camera );
  24889. }
  24890. }
  24891. const _size$1 = /*@__PURE__*/ new Vector2();
  24892. /**
  24893. * `RTTNode` takes another node and uses it with a `QuadMesh` to render into a texture (RTT).
  24894. * This module is especially relevant in context of post processing where certain nodes require
  24895. * texture input for their effects. With the helper function `convertToTexture()` which is based
  24896. * on this module, the node system can automatically ensure texture input if required.
  24897. *
  24898. * @augments TextureNode
  24899. */
  24900. class RTTNode extends TextureNode {
  24901. static get type() {
  24902. return 'RTTNode';
  24903. }
  24904. /**
  24905. * Constructs a new RTT node.
  24906. *
  24907. * @param {Node} node - The node to render a texture with.
  24908. * @param {?number} [width=null] - The width of the internal render target. If not width is applied, the render target is automatically resized.
  24909. * @param {?number} [height=null] - The height of the internal render target.
  24910. * @param {Object} [options={type:HalfFloatType}] - The options for the internal render target.
  24911. */
  24912. constructor( node, width = null, height = null, options = { type: HalfFloatType } ) {
  24913. const renderTarget = new RenderTarget( width, height, options );
  24914. super( renderTarget.texture, uv$1() );
  24915. /**
  24916. * This flag can be used for type testing.
  24917. *
  24918. * @type {boolean}
  24919. * @readonly
  24920. * @default true
  24921. */
  24922. this.isRTTNode = true;
  24923. /**
  24924. * The node to render a texture with.
  24925. *
  24926. * @type {Node}
  24927. */
  24928. this.node = node;
  24929. /**
  24930. * The width of the internal render target.
  24931. * If not width is applied, the render target is automatically resized.
  24932. *
  24933. * @type {?number}
  24934. * @default null
  24935. */
  24936. this.width = width;
  24937. /**
  24938. * The height of the internal render target.
  24939. *
  24940. * @type {?number}
  24941. * @default null
  24942. */
  24943. this.height = height;
  24944. /**
  24945. * The pixel ratio
  24946. *
  24947. * @type {number}
  24948. * @default 1
  24949. */
  24950. this.pixelRatio = 1;
  24951. /**
  24952. * The render target
  24953. *
  24954. * @type {RenderTarget}
  24955. */
  24956. this.renderTarget = renderTarget;
  24957. /**
  24958. * Whether the texture requires an update or not.
  24959. *
  24960. * @type {boolean}
  24961. * @default true
  24962. */
  24963. this.textureNeedsUpdate = true;
  24964. /**
  24965. * Whether the texture should automatically be updated or not.
  24966. *
  24967. * @type {boolean}
  24968. * @default true
  24969. */
  24970. this.autoUpdate = true;
  24971. /**
  24972. * The node which is used with the quad mesh for RTT.
  24973. *
  24974. * @private
  24975. * @type {Node}
  24976. * @default null
  24977. */
  24978. this._rttNode = null;
  24979. /**
  24980. * The internal quad mesh for RTT.
  24981. *
  24982. * @private
  24983. * @type {QuadMesh}
  24984. */
  24985. this._quadMesh = new QuadMesh( new NodeMaterial() );
  24986. /**
  24987. * The `updateBeforeType` is set to `NodeUpdateType.RENDER` since the node updates
  24988. * the texture once per render in its {@link RTTNode#updateBefore} method.
  24989. *
  24990. * @type {string}
  24991. * @default 'render'
  24992. */
  24993. this.updateBeforeType = NodeUpdateType.RENDER;
  24994. }
  24995. /**
  24996. * Whether the internal render target should automatically be resized or not.
  24997. *
  24998. * @type {boolean}
  24999. * @readonly
  25000. * @default true
  25001. */
  25002. get autoResize() {
  25003. return this.width === null;
  25004. }
  25005. setup( builder ) {
  25006. this._rttNode = this.node.context( builder.getSharedContext() );
  25007. this._quadMesh.material.name = 'RTT';
  25008. this._quadMesh.material.needsUpdate = true;
  25009. return super.setup( builder );
  25010. }
  25011. /**
  25012. * Sets the size of the internal render target
  25013. *
  25014. * @param {number} width - The width to set.
  25015. * @param {number} height - The width to set.
  25016. */
  25017. setSize( width, height ) {
  25018. this.width = width;
  25019. this.height = height;
  25020. const effectiveWidth = width * this.pixelRatio;
  25021. const effectiveHeight = height * this.pixelRatio;
  25022. this.renderTarget.setSize( effectiveWidth, effectiveHeight );
  25023. this.textureNeedsUpdate = true;
  25024. }
  25025. /**
  25026. * Sets the pixel ratio. This will also resize the render target.
  25027. *
  25028. * @param {number} pixelRatio - The pixel ratio to set.
  25029. */
  25030. setPixelRatio( pixelRatio ) {
  25031. this.pixelRatio = pixelRatio;
  25032. this.setSize( this.width, this.height );
  25033. }
  25034. updateBefore( { renderer } ) {
  25035. if ( this.textureNeedsUpdate === false && this.autoUpdate === false ) return;
  25036. this.textureNeedsUpdate = false;
  25037. //
  25038. if ( this.autoResize === true ) {
  25039. const pixelRatio = renderer.getPixelRatio();
  25040. const size = renderer.getSize( _size$1 );
  25041. const effectiveWidth = Math.floor( size.width * pixelRatio );
  25042. const effectiveHeight = Math.floor( size.height * pixelRatio );
  25043. if ( effectiveWidth !== this.renderTarget.width || effectiveHeight !== this.renderTarget.height ) {
  25044. this.renderTarget.setSize( effectiveWidth, effectiveHeight );
  25045. this.textureNeedsUpdate = true;
  25046. }
  25047. }
  25048. //
  25049. let name = 'RTT';
  25050. if ( this.node.name ) {
  25051. name = this.node.name + ' [ ' + name + ' ]';
  25052. }
  25053. this._quadMesh.material.fragmentNode = this._rttNode;
  25054. this._quadMesh.name = name;
  25055. //
  25056. const currentRenderTarget = renderer.getRenderTarget();
  25057. renderer.setRenderTarget( this.renderTarget );
  25058. this._quadMesh.render( renderer );
  25059. renderer.setRenderTarget( currentRenderTarget );
  25060. }
  25061. clone() {
  25062. const newNode = new TextureNode( this.value, this.uvNode, this.levelNode );
  25063. newNode.sampler = this.sampler;
  25064. newNode.referenceNode = this;
  25065. return newNode;
  25066. }
  25067. }
  25068. /**
  25069. * TSL function for creating a RTT node.
  25070. *
  25071. * @tsl
  25072. * @function
  25073. * @param {Node} node - The node to render a texture with.
  25074. * @param {?number} [width=null] - The width of the internal render target. If not width is applied, the render target is automatically resized.
  25075. * @param {?number} [height=null] - The height of the internal render target.
  25076. * @param {Object} [options={type:HalfFloatType}] - The options for the internal render target.
  25077. * @returns {RTTNode}
  25078. */
  25079. const rtt = ( node, ...params ) => nodeObject( new RTTNode( nodeObject( node ), ...params ) );
  25080. /**
  25081. * TSL function for converting nodes to textures nodes.
  25082. *
  25083. * @tsl
  25084. * @function
  25085. * @param {Node} node - The node to render a texture with.
  25086. * @param {?number} [width=null] - The width of the internal render target. If not width is applied, the render target is automatically resized.
  25087. * @param {?number} [height=null] - The height of the internal render target.
  25088. * @param {Object} [options={type:HalfFloatType}] - The options for the internal render target.
  25089. * @returns {RTTNode}
  25090. */
  25091. const convertToTexture = ( node, ...params ) => {
  25092. if ( node.isSampleNode || node.isTextureNode ) return node;
  25093. if ( node.isPassNode ) return node.getTextureNode();
  25094. return rtt( node, ...params );
  25095. };
  25096. /**
  25097. * Computes a position in view space based on a fragment's screen position expressed as uv coordinates, the fragments
  25098. * depth value and the camera's inverse projection matrix.
  25099. *
  25100. * @tsl
  25101. * @function
  25102. * @param {Node<vec2>} screenPosition - The fragment's screen position expressed as uv coordinates.
  25103. * @param {Node<float>} depth - The fragment's depth value.
  25104. * @param {Node<mat4>} projectionMatrixInverse - The camera's inverse projection matrix.
  25105. * @return {Node<vec3>} The fragments position in view space.
  25106. */
  25107. const getViewPosition = /*@__PURE__*/ Fn( ( [ screenPosition, depth, projectionMatrixInverse ], builder ) => {
  25108. let clipSpacePosition;
  25109. if ( builder.renderer.coordinateSystem === WebGPUCoordinateSystem ) {
  25110. screenPosition = vec2( screenPosition.x, screenPosition.y.oneMinus() ).mul( 2.0 ).sub( 1.0 );
  25111. clipSpacePosition = vec4( vec3( screenPosition, depth ), 1.0 );
  25112. } else {
  25113. clipSpacePosition = vec4( vec3( screenPosition.x, screenPosition.y.oneMinus(), depth ).mul( 2.0 ).sub( 1.0 ), 1.0 );
  25114. }
  25115. const viewSpacePosition = vec4( projectionMatrixInverse.mul( clipSpacePosition ) );
  25116. return viewSpacePosition.xyz.div( viewSpacePosition.w );
  25117. } );
  25118. /**
  25119. * Computes a screen position expressed as uv coordinates based on a fragment's position in view space
  25120. * and the camera's projection matrix
  25121. *
  25122. * @tsl
  25123. * @function
  25124. * @param {Node<vec3>} viewPosition - The fragments position in view space.
  25125. * @param {Node<mat4>} projectionMatrix - The camera's projection matrix.
  25126. * @return {Node<vec2>} The fragment's screen position expressed as uv coordinates.
  25127. */
  25128. const getScreenPosition = /*@__PURE__*/ Fn( ( [ viewPosition, projectionMatrix ] ) => {
  25129. const sampleClipPos = projectionMatrix.mul( vec4( viewPosition, 1.0 ) );
  25130. const sampleUv = sampleClipPos.xy.div( sampleClipPos.w ).mul( 0.5 ).add( 0.5 ).toVar();
  25131. return vec2( sampleUv.x, sampleUv.y.oneMinus() );
  25132. } );
  25133. /**
  25134. * Computes a normal vector based on depth data. Can be used as a fallback when no normal render
  25135. * target is available or if flat surface normals are required.
  25136. *
  25137. * @tsl
  25138. * @function
  25139. * @param {Node<vec2>} uv - The texture coordinate.
  25140. * @param {DepthTexture} depthTexture - The depth texture.
  25141. * @param {Node<mat4>} projectionMatrixInverse - The camera's inverse projection matrix.
  25142. * @return {Node<vec3>} The computed normal vector.
  25143. */
  25144. const getNormalFromDepth = /*@__PURE__*/ Fn( ( [ uv, depthTexture, projectionMatrixInverse ] ) => {
  25145. const size = textureSize( textureLoad( depthTexture ) );
  25146. const p = ivec2( uv.mul( size ) ).toVar();
  25147. const c0 = textureLoad( depthTexture, p ).toVar();
  25148. const l2 = textureLoad( depthTexture, p.sub( ivec2( 2, 0 ) ) ).toVar();
  25149. const l1 = textureLoad( depthTexture, p.sub( ivec2( 1, 0 ) ) ).toVar();
  25150. const r1 = textureLoad( depthTexture, p.add( ivec2( 1, 0 ) ) ).toVar();
  25151. const r2 = textureLoad( depthTexture, p.add( ivec2( 2, 0 ) ) ).toVar();
  25152. const b2 = textureLoad( depthTexture, p.add( ivec2( 0, 2 ) ) ).toVar();
  25153. const b1 = textureLoad( depthTexture, p.add( ivec2( 0, 1 ) ) ).toVar();
  25154. const t1 = textureLoad( depthTexture, p.sub( ivec2( 0, 1 ) ) ).toVar();
  25155. const t2 = textureLoad( depthTexture, p.sub( ivec2( 0, 2 ) ) ).toVar();
  25156. const dl = abs( sub( float( 2 ).mul( l1 ).sub( l2 ), c0 ) ).toVar();
  25157. const dr = abs( sub( float( 2 ).mul( r1 ).sub( r2 ), c0 ) ).toVar();
  25158. const db = abs( sub( float( 2 ).mul( b1 ).sub( b2 ), c0 ) ).toVar();
  25159. const dt = abs( sub( float( 2 ).mul( t1 ).sub( t2 ), c0 ) ).toVar();
  25160. const ce = getViewPosition( uv, c0, projectionMatrixInverse ).toVar();
  25161. 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 ) ) );
  25162. 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 ) ) );
  25163. return normalize( cross( dpdx, dpdy ) );
  25164. } );
  25165. /**
  25166. * Interleaved Gradient Noise (IGN) from Jimenez 2014.
  25167. *
  25168. * IGN has "low discrepancy" resulting in evenly distributed samples. It's superior compared to
  25169. * default white noise, blue noise or Bayer.
  25170. *
  25171. * References:
  25172. * - {@link https://www.iryoku.com/next-generation-post-processing-in-call-of-duty-advanced-warfare/}
  25173. * - {@link https://blog.demofox.org/2022/01/01/interleaved-gradient-noise-a-different-kind-of-low-discrepancy-sequence/}
  25174. *
  25175. * @tsl
  25176. * @function
  25177. * @param {Node<vec2>} position - The input position, usually screen coordinates.
  25178. * @return {Node<float>} The noise value.
  25179. */
  25180. const interleavedGradientNoise = Fn( ( [ position ] ) => {
  25181. return fract( float( 52.9829189 ).mul( fract( dot( position, vec2( 0.06711056, 0.00583715 ) ) ) ) );
  25182. } ).setLayout( {
  25183. name: 'interleavedGradientNoise',
  25184. type: 'float',
  25185. inputs: [
  25186. { name: 'position', type: 'vec2' }
  25187. ]
  25188. } );
  25189. /**
  25190. * Class representing a node that samples a value using a provided callback function.
  25191. *
  25192. * @extends Node
  25193. */
  25194. class SampleNode extends Node {
  25195. /**
  25196. * Returns the type of the node.
  25197. *
  25198. * @type {string}
  25199. * @readonly
  25200. * @static
  25201. */
  25202. static get type() {
  25203. return 'SampleNode';
  25204. }
  25205. /**
  25206. * Creates an instance of SampleNode.
  25207. *
  25208. * @param {Function} callback - The function to be called when sampling. Should accept a UV node and return a value.
  25209. * @param {?Node<vec2>} [uvNode=null] - The UV node to be used in the texture sampling.
  25210. */
  25211. constructor( callback, uvNode = null ) {
  25212. super();
  25213. this.callback = callback;
  25214. /**
  25215. * Represents the texture coordinates.
  25216. *
  25217. * @type {?Node<vec2|vec3>}
  25218. * @default null
  25219. */
  25220. this.uvNode = uvNode;
  25221. /**
  25222. * This flag can be used for type testing.
  25223. *
  25224. * @type {boolean}
  25225. * @readonly
  25226. * @default true
  25227. */
  25228. this.isSampleNode = true;
  25229. }
  25230. /**
  25231. * Sets up the node by sampling with the default UV accessor.
  25232. *
  25233. * @returns {Node} The result of the callback function when called with the UV node.
  25234. */
  25235. setup() {
  25236. return this.sample( uv$1() );
  25237. }
  25238. /**
  25239. * Calls the callback function with the provided UV node.
  25240. *
  25241. * @param {Node<vec2>} uv - The UV node or value to be passed to the callback.
  25242. * @returns {Node} The result of the callback function.
  25243. */
  25244. sample( uv ) {
  25245. return this.callback( uv );
  25246. }
  25247. }
  25248. /**
  25249. * Helper function to create a SampleNode wrapped as a node object.
  25250. *
  25251. * @function
  25252. * @param {Function} callback - The function to be called when sampling. Should accept a UV node and return a value.
  25253. * @param {?Node<vec2>} [uv=null] - The UV node to be used in the texture sampling.
  25254. * @returns {SampleNode} The created SampleNode instance wrapped as a node object.
  25255. */
  25256. const sample = ( callback, uv = null ) => nodeObject( new SampleNode( callback, nodeObject( uv ) ) );
  25257. /**
  25258. * EventNode is a node that executes a callback during specific update phases.
  25259. *
  25260. * @augments Node
  25261. */
  25262. class EventNode extends Node {
  25263. static get type() {
  25264. return 'EventNode';
  25265. }
  25266. /**
  25267. * Creates an EventNode.
  25268. *
  25269. * @param {string} eventType - The type of event
  25270. * @param {Function} callback - The callback to execute on update.
  25271. */
  25272. constructor( eventType, callback ) {
  25273. super( 'void' );
  25274. this.eventType = eventType;
  25275. this.callback = callback;
  25276. if ( eventType === EventNode.OBJECT ) {
  25277. this.updateType = NodeUpdateType.OBJECT;
  25278. } else if ( eventType === EventNode.MATERIAL ) {
  25279. this.updateType = NodeUpdateType.RENDER;
  25280. } else if ( eventType === EventNode.BEFORE_OBJECT ) {
  25281. this.updateBeforeType = NodeUpdateType.OBJECT;
  25282. } else if ( eventType === EventNode.BEFORE_MATERIAL ) {
  25283. this.updateBeforeType = NodeUpdateType.RENDER;
  25284. }
  25285. }
  25286. update( frame ) {
  25287. this.callback( frame );
  25288. }
  25289. updateBefore( frame ) {
  25290. this.callback( frame );
  25291. }
  25292. }
  25293. EventNode.OBJECT = 'object';
  25294. EventNode.MATERIAL = 'material';
  25295. EventNode.BEFORE_OBJECT = 'beforeObject';
  25296. EventNode.BEFORE_MATERIAL = 'beforeMaterial';
  25297. /**
  25298. * Helper to create an EventNode and add it to the stack.
  25299. *
  25300. * @param {string} type - The event type.
  25301. * @param {Function} callback - The callback function.
  25302. * @returns {EventNode}
  25303. */
  25304. const createEvent = ( type, callback ) => nodeObject( new EventNode( type, callback ) ).toStack();
  25305. /**
  25306. * Creates an event that triggers a function every time an object (Mesh|Sprite) is rendered.
  25307. *
  25308. * The event will be bound to the declared TSL function `Fn()`; it must be declared within a `Fn()` or the JS function call must be inherited from one.
  25309. *
  25310. * @param {Function} callback - The callback function.
  25311. * @returns {EventNode}
  25312. */
  25313. const OnObjectUpdate = ( callback ) => createEvent( EventNode.OBJECT, callback );
  25314. /**
  25315. * Creates an event that triggers a function when the first object that uses the material is rendered.
  25316. *
  25317. * The event will be bound to the declared TSL function `Fn()`; it must be declared within a `Fn()` or the JS function call must be inherited from one.
  25318. *
  25319. * @param {Function} callback - The callback function.
  25320. * @returns {EventNode}
  25321. */
  25322. const OnMaterialUpdate = ( callback ) => createEvent( EventNode.MATERIAL, callback );
  25323. /**
  25324. * Creates an event that triggers a function before an object (Mesh|Sprite) is updated.
  25325. *
  25326. * The event will be bound to the declared TSL function `Fn()`; it must be declared within a `Fn()` or the JS function call must be inherited from one.
  25327. *
  25328. * @param {Function} callback - The callback function.
  25329. * @returns {EventNode}
  25330. */
  25331. const OnBeforeObjectUpdate = ( callback ) => createEvent( EventNode.BEFORE_OBJECT, callback );
  25332. /**
  25333. * Creates an event that triggers a function before the material is updated.
  25334. *
  25335. * The event will be bound to the declared TSL function `Fn()`; it must be declared within a `Fn()` or the JS function call must be inherited from one.
  25336. *
  25337. * @param {Function} callback - The callback function.
  25338. * @returns {EventNode}
  25339. */
  25340. const OnBeforeMaterialUpdate = ( callback ) => createEvent( EventNode.BEFORE_MATERIAL, callback );
  25341. /**
  25342. * This special type of instanced buffer attribute is intended for compute shaders.
  25343. * In earlier three.js versions it was only possible to update attribute data
  25344. * on the CPU via JavaScript and then upload the data to the GPU. With the
  25345. * new material system and renderer it is now possible to use compute shaders
  25346. * to compute the data for an attribute more efficiently on the GPU.
  25347. *
  25348. * The idea is to create an instance of this class and provide it as an input
  25349. * to {@link StorageBufferNode}.
  25350. *
  25351. * Note: This type of buffer attribute can only be used with `WebGPURenderer`.
  25352. *
  25353. * @augments InstancedBufferAttribute
  25354. */
  25355. class StorageInstancedBufferAttribute extends InstancedBufferAttribute {
  25356. /**
  25357. * Constructs a new storage instanced buffer attribute.
  25358. *
  25359. * @param {number|TypedArray} count - The item count. It is also valid to pass a typed array as an argument.
  25360. * The subsequent parameters are then obsolete.
  25361. * @param {number} itemSize - The item size.
  25362. * @param {TypedArray.constructor} [typeClass=Float32Array] - A typed array constructor.
  25363. */
  25364. constructor( count, itemSize, typeClass = Float32Array ) {
  25365. const array = ArrayBuffer.isView( count ) ? count : new typeClass( count * itemSize );
  25366. super( array, itemSize );
  25367. /**
  25368. * This flag can be used for type testing.
  25369. *
  25370. * @type {boolean}
  25371. * @readonly
  25372. * @default true
  25373. */
  25374. this.isStorageInstancedBufferAttribute = true;
  25375. }
  25376. }
  25377. /**
  25378. * This special type of buffer attribute is intended for compute shaders.
  25379. * In earlier three.js versions it was only possible to update attribute data
  25380. * on the CPU via JavaScript and then upload the data to the GPU. With the
  25381. * new material system and renderer it is now possible to use compute shaders
  25382. * to compute the data for an attribute more efficiently on the GPU.
  25383. *
  25384. * The idea is to create an instance of this class and provide it as an input
  25385. * to {@link StorageBufferNode}.
  25386. *
  25387. * Note: This type of buffer attribute can only be used with `WebGPURenderer`.
  25388. *
  25389. * @augments BufferAttribute
  25390. */
  25391. class StorageBufferAttribute extends BufferAttribute {
  25392. /**
  25393. * Constructs a new storage buffer attribute.
  25394. *
  25395. * @param {number|TypedArray} count - The item count. It is also valid to pass a typed array as an argument.
  25396. * The subsequent parameters are then obsolete.
  25397. * @param {number} itemSize - The item size.
  25398. * @param {TypedArray.constructor} [typeClass=Float32Array] - A typed array constructor.
  25399. */
  25400. constructor( count, itemSize, typeClass = Float32Array ) {
  25401. const array = ArrayBuffer.isView( count ) ? count : new typeClass( count * itemSize );
  25402. super( array, itemSize );
  25403. /**
  25404. * This flag can be used for type testing.
  25405. *
  25406. * @type {boolean}
  25407. * @readonly
  25408. * @default true
  25409. */
  25410. this.isStorageBufferAttribute = true;
  25411. }
  25412. }
  25413. /**
  25414. * TSL function for creating a storage buffer node with a configured `StorageBufferAttribute`.
  25415. *
  25416. * @tsl
  25417. * @function
  25418. * @param {number|TypedArray} count - The data count. It is also valid to pass a typed array as an argument.
  25419. * @param {string|Struct} [type='float'] - The data type.
  25420. * @returns {StorageBufferNode}
  25421. */
  25422. const attributeArray = ( count, type = 'float' ) => {
  25423. let itemSize, typedArray;
  25424. if ( type.isStruct === true ) {
  25425. itemSize = type.layout.getLength();
  25426. typedArray = getTypedArrayFromType( 'float' );
  25427. } else {
  25428. itemSize = getLengthFromType( type );
  25429. typedArray = getTypedArrayFromType( type );
  25430. }
  25431. const buffer = new StorageBufferAttribute( count, itemSize, typedArray );
  25432. const node = storage( buffer, type, count );
  25433. return node;
  25434. };
  25435. /**
  25436. * TSL function for creating a storage buffer node with a configured `StorageInstancedBufferAttribute`.
  25437. *
  25438. * @tsl
  25439. * @function
  25440. * @param {number|TypedArray} count - The data count. It is also valid to pass a typed array as an argument.
  25441. * @param {string|Struct} [type='float'] - The data type.
  25442. * @returns {StorageBufferNode}
  25443. */
  25444. const instancedArray = ( count, type = 'float' ) => {
  25445. let itemSize, typedArray;
  25446. if ( type.isStruct === true ) {
  25447. itemSize = type.layout.getLength();
  25448. typedArray = getTypedArrayFromType( 'float' );
  25449. } else {
  25450. itemSize = getLengthFromType( type );
  25451. typedArray = getTypedArrayFromType( type );
  25452. }
  25453. const buffer = new StorageInstancedBufferAttribute( count, itemSize, typedArray );
  25454. const node = storage( buffer, type, count );
  25455. return node;
  25456. };
  25457. /**
  25458. * A node for representing the uv coordinates of points.
  25459. *
  25460. * Can only be used with a WebGL backend. In WebGPU, point
  25461. * primitives always have the size of one pixel and can thus
  25462. * can't be used as sprite-like objects that display textures.
  25463. *
  25464. * @augments Node
  25465. */
  25466. class PointUVNode extends Node {
  25467. static get type() {
  25468. return 'PointUVNode';
  25469. }
  25470. /**
  25471. * Constructs a new point uv node.
  25472. */
  25473. constructor() {
  25474. super( 'vec2' );
  25475. /**
  25476. * This flag can be used for type testing.
  25477. *
  25478. * @type {boolean}
  25479. * @readonly
  25480. * @default true
  25481. */
  25482. this.isPointUVNode = true;
  25483. }
  25484. generate( /*builder*/ ) {
  25485. return 'vec2( gl_PointCoord.x, 1.0 - gl_PointCoord.y )';
  25486. }
  25487. }
  25488. /**
  25489. * TSL object that represents the uv coordinates of points.
  25490. *
  25491. * @tsl
  25492. * @type {PointUVNode}
  25493. */
  25494. const pointUV = /*@__PURE__*/ nodeImmutable( PointUVNode );
  25495. const _e1 = /*@__PURE__*/ new Euler();
  25496. const _m1 = /*@__PURE__*/ new Matrix4();
  25497. /**
  25498. * This module allows access to a collection of scene properties. The following predefined TSL objects
  25499. * are available for easier use:
  25500. *
  25501. * - `backgroundBlurriness`: A node that represents the scene's background blurriness.
  25502. * - `backgroundIntensity`: A node that represents the scene's background intensity.
  25503. * - `backgroundRotation`: A node that represents the scene's background rotation.
  25504. *
  25505. * @augments Node
  25506. */
  25507. class SceneNode extends Node {
  25508. static get type() {
  25509. return 'SceneNode';
  25510. }
  25511. /**
  25512. * Constructs a new scene node.
  25513. *
  25514. * @param {('backgroundBlurriness'|'backgroundIntensity'|'backgroundRotation')} scope - The scope defines the type of scene property that is accessed.
  25515. * @param {?Scene} [scene=null] - A reference to the scene.
  25516. */
  25517. constructor( scope = SceneNode.BACKGROUND_BLURRINESS, scene = null ) {
  25518. super();
  25519. /**
  25520. * The scope defines the type of scene property that is accessed.
  25521. *
  25522. * @type {('backgroundBlurriness'|'backgroundIntensity'|'backgroundRotation')}
  25523. */
  25524. this.scope = scope;
  25525. /**
  25526. * A reference to the scene that is going to be accessed.
  25527. *
  25528. * @type {?Scene}
  25529. * @default null
  25530. */
  25531. this.scene = scene;
  25532. }
  25533. /**
  25534. * Depending on the scope, the method returns a different type of node that represents
  25535. * the respective scene property.
  25536. *
  25537. * @param {NodeBuilder} builder - The current node builder.
  25538. * @return {Node} The output node.
  25539. */
  25540. setup( builder ) {
  25541. const scope = this.scope;
  25542. const scene = this.scene !== null ? this.scene : builder.scene;
  25543. let output;
  25544. if ( scope === SceneNode.BACKGROUND_BLURRINESS ) {
  25545. output = reference( 'backgroundBlurriness', 'float', scene );
  25546. } else if ( scope === SceneNode.BACKGROUND_INTENSITY ) {
  25547. output = reference( 'backgroundIntensity', 'float', scene );
  25548. } else if ( scope === SceneNode.BACKGROUND_ROTATION ) {
  25549. output = uniform( 'mat4' ).setName( 'backgroundRotation' ).setGroup( renderGroup ).onRenderUpdate( () => {
  25550. const background = scene.background;
  25551. if ( background !== null && background.isTexture && background.mapping !== UVMapping ) {
  25552. _e1.copy( scene.backgroundRotation );
  25553. // accommodate left-handed frame
  25554. _e1.x *= -1; _e1.y *= -1; _e1.z *= -1;
  25555. _m1.makeRotationFromEuler( _e1 );
  25556. } else {
  25557. _m1.identity();
  25558. }
  25559. return _m1;
  25560. } );
  25561. } else {
  25562. error( 'SceneNode: Unknown scope:', scope );
  25563. }
  25564. return output;
  25565. }
  25566. }
  25567. SceneNode.BACKGROUND_BLURRINESS = 'backgroundBlurriness';
  25568. SceneNode.BACKGROUND_INTENSITY = 'backgroundIntensity';
  25569. SceneNode.BACKGROUND_ROTATION = 'backgroundRotation';
  25570. /**
  25571. * TSL object that represents the scene's background blurriness.
  25572. *
  25573. * @tsl
  25574. * @type {SceneNode}
  25575. */
  25576. const backgroundBlurriness = /*@__PURE__*/ nodeImmutable( SceneNode, SceneNode.BACKGROUND_BLURRINESS );
  25577. /**
  25578. * TSL object that represents the scene's background intensity.
  25579. *
  25580. * @tsl
  25581. * @type {SceneNode}
  25582. */
  25583. const backgroundIntensity = /*@__PURE__*/ nodeImmutable( SceneNode, SceneNode.BACKGROUND_INTENSITY );
  25584. /**
  25585. * TSL object that represents the scene's background rotation.
  25586. *
  25587. * @tsl
  25588. * @type {SceneNode}
  25589. */
  25590. const backgroundRotation = /*@__PURE__*/ nodeImmutable( SceneNode, SceneNode.BACKGROUND_ROTATION );
  25591. /**
  25592. * This special version of a texture node can be used to
  25593. * write data into a storage texture with a compute shader.
  25594. *
  25595. * ```js
  25596. * const storageTexture = new THREE.StorageTexture( width, height );
  25597. *
  25598. * const computeTexture = Fn( ( { storageTexture } ) => {
  25599. *
  25600. * const posX = instanceIndex.mod( width );
  25601. * const posY = instanceIndex.div( width );
  25602. * const indexUV = uvec2( posX, posY );
  25603. *
  25604. * // generate RGB values
  25605. *
  25606. * const r = 1;
  25607. * const g = 1;
  25608. * const b = 1;
  25609. *
  25610. * textureStore( storageTexture, indexUV, vec4( r, g, b, 1 ) ).toWriteOnly();
  25611. *
  25612. * } );
  25613. *
  25614. * const computeNode = computeTexture( { storageTexture } ).compute( width * height );
  25615. * renderer.computeAsync( computeNode );
  25616. * ```
  25617. *
  25618. * This node can only be used with a WebGPU backend.
  25619. *
  25620. * @augments TextureNode
  25621. */
  25622. class StorageTextureNode extends TextureNode {
  25623. static get type() {
  25624. return 'StorageTextureNode';
  25625. }
  25626. /**
  25627. * Constructs a new storage texture node.
  25628. *
  25629. * @param {StorageTexture} value - The storage texture.
  25630. * @param {Node<vec2|vec3>} uvNode - The uv node.
  25631. * @param {?Node} [storeNode=null] - The value node that should be stored in the texture.
  25632. */
  25633. constructor( value, uvNode, storeNode = null ) {
  25634. super( value, uvNode );
  25635. /**
  25636. * The value node that should be stored in the texture.
  25637. *
  25638. * @type {?Node}
  25639. * @default null
  25640. */
  25641. this.storeNode = storeNode;
  25642. /**
  25643. * The mip level to write to for storage textures.
  25644. *
  25645. * @type {number}
  25646. * @default 0
  25647. */
  25648. this.mipLevel = 0;
  25649. /**
  25650. * This flag can be used for type testing.
  25651. *
  25652. * @type {boolean}
  25653. * @readonly
  25654. * @default true
  25655. */
  25656. this.isStorageTextureNode = true;
  25657. /**
  25658. * The access type of the texture node.
  25659. *
  25660. * @type {string}
  25661. * @default 'writeOnly'
  25662. */
  25663. this.access = NodeAccess.WRITE_ONLY;
  25664. }
  25665. /**
  25666. * Overwrites the default implementation to return a fixed value `'storageTexture'`.
  25667. *
  25668. * @param {NodeBuilder} builder - The current node builder.
  25669. * @return {string} The input type.
  25670. */
  25671. getInputType( /*builder*/ ) {
  25672. return 'storageTexture';
  25673. }
  25674. setup( builder ) {
  25675. super.setup( builder );
  25676. const properties = builder.getNodeProperties( this );
  25677. properties.storeNode = this.storeNode;
  25678. return properties;
  25679. }
  25680. /**
  25681. * Defines the node access.
  25682. *
  25683. * @param {string} value - The node access.
  25684. * @return {StorageTextureNode} A reference to this node.
  25685. */
  25686. setAccess( value ) {
  25687. this.access = value;
  25688. return this;
  25689. }
  25690. /**
  25691. * Sets the mip level to write to.
  25692. *
  25693. * @param {number} level - The mip level.
  25694. * @return {StorageTextureNode} A reference to this node.
  25695. */
  25696. setMipLevel( level ) {
  25697. this.mipLevel = level;
  25698. return this;
  25699. }
  25700. /**
  25701. * Generates the code snippet of the storage node. If no `storeNode`
  25702. * is defined, the texture node is generated as normal texture.
  25703. *
  25704. * @param {NodeBuilder} builder - The current node builder.
  25705. * @param {string} output - The current output.
  25706. * @return {string} The generated code snippet.
  25707. */
  25708. generate( builder, output ) {
  25709. let snippet;
  25710. if ( this.storeNode !== null ) {
  25711. snippet = this.generateStore( builder );
  25712. } else {
  25713. snippet = super.generate( builder, output );
  25714. }
  25715. return snippet;
  25716. }
  25717. /**
  25718. * Convenience method for configuring a read/write node access.
  25719. *
  25720. * @return {StorageTextureNode} A reference to this node.
  25721. */
  25722. toReadWrite() {
  25723. return this.setAccess( NodeAccess.READ_WRITE );
  25724. }
  25725. /**
  25726. * Convenience method for configuring a read-only node access.
  25727. *
  25728. * @return {StorageTextureNode} A reference to this node.
  25729. */
  25730. toReadOnly() {
  25731. return this.setAccess( NodeAccess.READ_ONLY );
  25732. }
  25733. /**
  25734. * Convenience method for configuring a write-only node access.
  25735. *
  25736. * @return {StorageTextureNode} A reference to this node.
  25737. */
  25738. toWriteOnly() {
  25739. return this.setAccess( NodeAccess.WRITE_ONLY );
  25740. }
  25741. /**
  25742. * Generates the code snippet of the storage texture node.
  25743. *
  25744. * @param {NodeBuilder} builder - The current node builder.
  25745. */
  25746. generateStore( builder ) {
  25747. const properties = builder.getNodeProperties( this );
  25748. const { uvNode, storeNode, depthNode } = properties;
  25749. const textureProperty = super.generate( builder, 'property' );
  25750. const uvSnippet = uvNode.build( builder, this.value.is3DTexture === true ? 'uvec3' : 'uvec2' );
  25751. const storeSnippet = storeNode.build( builder, 'vec4' );
  25752. const depthSnippet = depthNode ? depthNode.build( builder, 'int' ) : null;
  25753. const snippet = builder.generateTextureStore( builder, textureProperty, uvSnippet, depthSnippet, storeSnippet );
  25754. builder.addLineFlowCode( snippet, this );
  25755. }
  25756. clone() {
  25757. const newNode = super.clone();
  25758. newNode.storeNode = this.storeNode;
  25759. newNode.mipLevel = this.mipLevel;
  25760. return newNode;
  25761. }
  25762. }
  25763. /**
  25764. * TSL function for creating a storage texture node.
  25765. *
  25766. * @tsl
  25767. * @function
  25768. * @param {StorageTexture} value - The storage texture.
  25769. * @param {?Node<vec2|vec3>} uvNode - The uv node.
  25770. * @param {?Node} [storeNode=null] - The value node that should be stored in the texture.
  25771. * @returns {StorageTextureNode}
  25772. */
  25773. const storageTexture = /*@__PURE__*/ nodeProxy( StorageTextureNode ).setParameterLength( 1, 3 );
  25774. /**
  25775. * TODO: Explain difference to `storageTexture()`.
  25776. *
  25777. * @tsl
  25778. * @function
  25779. * @param {StorageTexture} value - The storage texture.
  25780. * @param {Node<vec2|vec3>} uvNode - The uv node.
  25781. * @param {?Node} [storeNode=null] - The value node that should be stored in the texture.
  25782. * @returns {StorageTextureNode}
  25783. */
  25784. const textureStore = ( value, uvNode, storeNode ) => {
  25785. const node = storageTexture( value, uvNode, storeNode );
  25786. if ( storeNode !== null ) node.toStack();
  25787. return node;
  25788. };
  25789. const normal = Fn( ( { texture, uv } ) => {
  25790. const epsilon = 0.0001;
  25791. const ret = vec3().toVar();
  25792. If( uv.x.lessThan( epsilon ), () => {
  25793. ret.assign( vec3( 1, 0, 0 ) );
  25794. } ).ElseIf( uv.y.lessThan( epsilon ), () => {
  25795. ret.assign( vec3( 0, 1, 0 ) );
  25796. } ).ElseIf( uv.z.lessThan( epsilon ), () => {
  25797. ret.assign( vec3( 0, 0, 1 ) );
  25798. } ).ElseIf( uv.x.greaterThan( 1 - epsilon ), () => {
  25799. ret.assign( vec3( -1, 0, 0 ) );
  25800. } ).ElseIf( uv.y.greaterThan( 1 - epsilon ), () => {
  25801. ret.assign( vec3( 0, -1, 0 ) );
  25802. } ).ElseIf( uv.z.greaterThan( 1 - epsilon ), () => {
  25803. ret.assign( vec3( 0, 0, -1 ) );
  25804. } ).Else( () => {
  25805. const step = 0.01;
  25806. 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 );
  25807. 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 );
  25808. 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 );
  25809. ret.assign( vec3( x, y, z ) );
  25810. } );
  25811. return ret.normalize();
  25812. } );
  25813. /**
  25814. * This type of uniform node represents a 3D texture.
  25815. *
  25816. * @augments TextureNode
  25817. */
  25818. class Texture3DNode extends TextureNode {
  25819. static get type() {
  25820. return 'Texture3DNode';
  25821. }
  25822. /**
  25823. * Constructs a new 3D texture node.
  25824. *
  25825. * @param {Data3DTexture} value - The 3D texture.
  25826. * @param {?Node<vec2|vec3>} [uvNode=null] - The uv node.
  25827. * @param {?Node<int>} [levelNode=null] - The level node.
  25828. */
  25829. constructor( value, uvNode = null, levelNode = null ) {
  25830. super( value, uvNode, levelNode );
  25831. /**
  25832. * This flag can be used for type testing.
  25833. *
  25834. * @type {boolean}
  25835. * @readonly
  25836. * @default true
  25837. */
  25838. this.isTexture3DNode = true;
  25839. }
  25840. /**
  25841. * Overwrites the default implementation to return a fixed value `'texture3D'`.
  25842. *
  25843. * @param {NodeBuilder} builder - The current node builder.
  25844. * @return {string} The input type.
  25845. */
  25846. getInputType( /*builder*/ ) {
  25847. return 'texture3D';
  25848. }
  25849. /**
  25850. * Returns a default uv node which is in context of 3D textures a three-dimensional
  25851. * uv node.
  25852. *
  25853. * @return {Node<vec3>} The default uv node.
  25854. */
  25855. getDefaultUV() {
  25856. return vec3( 0.5, 0.5, 0.5 );
  25857. }
  25858. /**
  25859. * Overwritten with an empty implementation since the `updateMatrix` flag is ignored
  25860. * for 3D textures. The uv transformation matrix is not applied to 3D textures.
  25861. *
  25862. * @param {boolean} value - The update toggle.
  25863. */
  25864. setUpdateMatrix( /*value*/ ) { } // Ignore .updateMatrix for 3d TextureNode
  25865. /**
  25866. * Overwrites the default implementation to return the unmodified uv node.
  25867. *
  25868. * @param {NodeBuilder} builder - The current node builder.
  25869. * @param {Node} uvNode - The uv node to setup.
  25870. * @return {Node} The unmodified uv node.
  25871. */
  25872. setupUV( builder, uvNode ) {
  25873. const texture = this.value;
  25874. if ( builder.isFlipY() && ( texture.isRenderTargetTexture === true || texture.isFramebufferTexture === true ) ) {
  25875. if ( this.sampler ) {
  25876. uvNode = uvNode.flipY();
  25877. } else {
  25878. uvNode = uvNode.setY( int( textureSize( this, this.levelNode ).y ).sub( uvNode.y ).sub( 1 ) );
  25879. }
  25880. }
  25881. return uvNode;
  25882. }
  25883. /**
  25884. * Generates the uv code snippet.
  25885. *
  25886. * @param {NodeBuilder} builder - The current node builder.
  25887. * @param {Node} uvNode - The uv node to generate code for.
  25888. * @return {string} The generated code snippet.
  25889. */
  25890. generateUV( builder, uvNode ) {
  25891. return uvNode.build( builder, this.sampler === true ? 'vec3' : 'ivec3' );
  25892. }
  25893. /**
  25894. * Generates the offset code snippet.
  25895. *
  25896. * @param {NodeBuilder} builder - The current node builder.
  25897. * @param {Node} offsetNode - The offset node to generate code for.
  25898. * @return {string} The generated code snippet.
  25899. */
  25900. generateOffset( builder, offsetNode ) {
  25901. return offsetNode.build( builder, 'ivec3' );
  25902. }
  25903. /**
  25904. * TODO.
  25905. *
  25906. * @param {Node<vec3>} uvNode - The uv node .
  25907. * @return {Node<vec3>} TODO.
  25908. */
  25909. normal( uvNode ) {
  25910. return normal( { texture: this, uv: uvNode } );
  25911. }
  25912. }
  25913. /**
  25914. * TSL function for creating a 3D texture node.
  25915. *
  25916. * @tsl
  25917. * @function
  25918. * @param {Data3DTexture} value - The 3D texture.
  25919. * @param {?Node<vec3>} [uvNode=null] - The uv node.
  25920. * @param {?Node<int>} [levelNode=null] - The level node.
  25921. * @returns {Texture3DNode}
  25922. */
  25923. const texture3D = /*@__PURE__*/ nodeProxy( Texture3DNode ).setParameterLength( 1, 3 );
  25924. /**
  25925. * TSL function for creating a texture node that fetches/loads texels without interpolation.
  25926. *
  25927. * @tsl
  25928. * @function
  25929. * @param {?(Texture|TextureNode)} [value=EmptyTexture] - The texture.
  25930. * @param {?Node<vec3>} [uvNode=null] - The uv node.
  25931. * @param {?Node<int>} [levelNode=null] - The level node.
  25932. * @param {?Node<float>} [biasNode=null] - The bias node.
  25933. * @returns {TextureNode}
  25934. */
  25935. const texture3DLoad = ( ...params ) => texture3D( ...params ).setSampler( false );
  25936. /**
  25937. * TSL function for creating a texture node that fetches/loads texels without interpolation.
  25938. *
  25939. * @tsl
  25940. * @function
  25941. * @param {?(Texture|TextureNode)} [value=EmptyTexture] - The texture.
  25942. * @param {?Node<vec3>} [uvNode=null] - The uv node.
  25943. * @param {?Node<int>} [levelNode=null] - The level node.
  25944. * @returns {TextureNode}
  25945. */
  25946. const texture3DLevel = ( value, uvNode, levelNode ) => texture3D( value, uvNode ).level( levelNode );
  25947. /**
  25948. * A special type of reference node that allows to link values in
  25949. * `userData` fields to node objects.
  25950. * ```js
  25951. * sprite.userData.rotation = 1; // stores individual rotation per sprite
  25952. *
  25953. * const material = new THREE.SpriteNodeMaterial();
  25954. * material.rotationNode = userData( 'rotation', 'float' );
  25955. * ```
  25956. * Since `UserDataNode` is extended from {@link ReferenceNode}, the node value
  25957. * will automatically be updated when the `rotation` user data field changes.
  25958. *
  25959. * @augments ReferenceNode
  25960. */
  25961. class UserDataNode extends ReferenceNode {
  25962. static get type() {
  25963. return 'UserDataNode';
  25964. }
  25965. /**
  25966. * Constructs a new user data node.
  25967. *
  25968. * @param {string} property - The property name that should be referenced by the node.
  25969. * @param {string} inputType - The node data type of the reference.
  25970. * @param {?Object} [userData=null] - A reference to the `userData` object. If not provided, the `userData` property of the 3D object that uses the node material is evaluated.
  25971. */
  25972. constructor( property, inputType, userData = null ) {
  25973. super( property, inputType, userData );
  25974. /**
  25975. * A reference to the `userData` object. If not provided, the `userData`
  25976. * property of the 3D object that uses the node material is evaluated.
  25977. *
  25978. * @type {?Object}
  25979. * @default null
  25980. */
  25981. this.userData = userData;
  25982. }
  25983. /**
  25984. * Overwritten to make sure {@link ReferenceNode#reference} points to the correct
  25985. * `userData` field.
  25986. *
  25987. * @param {(NodeFrame|NodeBuilder)} state - The current state to evaluate.
  25988. * @return {Object} A reference to the `userData` field.
  25989. */
  25990. updateReference( state ) {
  25991. this.reference = this.userData !== null ? this.userData : state.object.userData;
  25992. return this.reference;
  25993. }
  25994. }
  25995. /**
  25996. * TSL function for creating a user data node.
  25997. *
  25998. * @tsl
  25999. * @function
  26000. * @param {string} name - The property name that should be referenced by the node.
  26001. * @param {string} inputType - The node data type of the reference.
  26002. * @param {?Object} userData - A reference to the `userData` object. If not provided, the `userData` property of the 3D object that uses the node material is evaluated.
  26003. * @returns {UserDataNode}
  26004. */
  26005. const userData = ( name, inputType, userData ) => nodeObject( new UserDataNode( name, inputType, userData ) );
  26006. const _objectData = new WeakMap();
  26007. /**
  26008. * A node for representing motion or velocity vectors. Foundation
  26009. * for advanced post processing effects like motion blur or TRAA.
  26010. *
  26011. * The node keeps track of the model, view and projection matrices
  26012. * of the previous frame and uses them to compute offsets in NDC space.
  26013. * These offsets represent the final velocity.
  26014. *
  26015. * @augments TempNode
  26016. */
  26017. class VelocityNode extends TempNode {
  26018. static get type() {
  26019. return 'VelocityNode';
  26020. }
  26021. /**
  26022. * Constructs a new vertex color node.
  26023. */
  26024. constructor() {
  26025. super( 'vec2' );
  26026. /**
  26027. * The current projection matrix.
  26028. *
  26029. * @type {?Matrix4}
  26030. * @default null
  26031. */
  26032. this.projectionMatrix = null;
  26033. /**
  26034. * Overwritten since velocity nodes are updated per object.
  26035. *
  26036. * @type {string}
  26037. * @default 'object'
  26038. */
  26039. this.updateType = NodeUpdateType.OBJECT;
  26040. /**
  26041. * Overwritten since velocity nodes save data after the update.
  26042. *
  26043. * @type {string}
  26044. * @default 'object'
  26045. */
  26046. this.updateAfterType = NodeUpdateType.OBJECT;
  26047. /**
  26048. * Uniform node representing the previous model matrix in world space.
  26049. *
  26050. * @type {UniformNode<mat4>}
  26051. * @default null
  26052. */
  26053. this.previousModelWorldMatrix = uniform( new Matrix4() );
  26054. /**
  26055. * Uniform node representing the previous projection matrix.
  26056. *
  26057. * @type {UniformNode<mat4>}
  26058. * @default null
  26059. */
  26060. this.previousProjectionMatrix = uniform( new Matrix4() ).setGroup( renderGroup );
  26061. /**
  26062. * Uniform node representing the previous view matrix.
  26063. *
  26064. * @type {UniformNode<mat4>}
  26065. * @default null
  26066. */
  26067. this.previousCameraViewMatrix = uniform( new Matrix4() );
  26068. }
  26069. /**
  26070. * Sets the given projection matrix.
  26071. *
  26072. * @param {Matrix4} projectionMatrix - The projection matrix to set.
  26073. */
  26074. setProjectionMatrix( projectionMatrix ) {
  26075. this.projectionMatrix = projectionMatrix;
  26076. }
  26077. /**
  26078. * Updates velocity specific uniforms.
  26079. *
  26080. * @param {NodeFrame} frame - A reference to the current node frame.
  26081. */
  26082. update( { frameId, camera, object } ) {
  26083. const previousModelMatrix = getPreviousMatrix( object );
  26084. this.previousModelWorldMatrix.value.copy( previousModelMatrix );
  26085. //
  26086. const cameraData = getData( camera );
  26087. if ( cameraData.frameId !== frameId ) {
  26088. cameraData.frameId = frameId;
  26089. if ( cameraData.previousProjectionMatrix === undefined ) {
  26090. cameraData.previousProjectionMatrix = new Matrix4();
  26091. cameraData.previousCameraViewMatrix = new Matrix4();
  26092. cameraData.currentProjectionMatrix = new Matrix4();
  26093. cameraData.currentCameraViewMatrix = new Matrix4();
  26094. cameraData.previousProjectionMatrix.copy( this.projectionMatrix || camera.projectionMatrix );
  26095. cameraData.previousCameraViewMatrix.copy( camera.matrixWorldInverse );
  26096. } else {
  26097. cameraData.previousProjectionMatrix.copy( cameraData.currentProjectionMatrix );
  26098. cameraData.previousCameraViewMatrix.copy( cameraData.currentCameraViewMatrix );
  26099. }
  26100. cameraData.currentProjectionMatrix.copy( this.projectionMatrix || camera.projectionMatrix );
  26101. cameraData.currentCameraViewMatrix.copy( camera.matrixWorldInverse );
  26102. this.previousProjectionMatrix.value.copy( cameraData.previousProjectionMatrix );
  26103. this.previousCameraViewMatrix.value.copy( cameraData.previousCameraViewMatrix );
  26104. }
  26105. }
  26106. /**
  26107. * Overwritten to updated velocity specific uniforms.
  26108. *
  26109. * @param {NodeFrame} frame - A reference to the current node frame.
  26110. */
  26111. updateAfter( { object } ) {
  26112. getPreviousMatrix( object ).copy( object.matrixWorld );
  26113. }
  26114. /**
  26115. * Implements the velocity computation based on the previous and current vertex data.
  26116. *
  26117. * @param {NodeBuilder} builder - A reference to the current node builder.
  26118. * @return {Node<vec2>} The motion vector.
  26119. */
  26120. setup( /*builder*/ ) {
  26121. const projectionMatrix = ( this.projectionMatrix === null ) ? cameraProjectionMatrix : uniform( this.projectionMatrix );
  26122. const previousModelViewMatrix = this.previousCameraViewMatrix.mul( this.previousModelWorldMatrix );
  26123. const clipPositionCurrent = projectionMatrix.mul( modelViewMatrix ).mul( positionLocal );
  26124. const clipPositionPrevious = this.previousProjectionMatrix.mul( previousModelViewMatrix ).mul( positionPrevious );
  26125. const ndcPositionCurrent = clipPositionCurrent.xy.div( clipPositionCurrent.w );
  26126. const ndcPositionPrevious = clipPositionPrevious.xy.div( clipPositionPrevious.w );
  26127. const velocity = sub( ndcPositionCurrent, ndcPositionPrevious );
  26128. return velocity;
  26129. }
  26130. }
  26131. function getData( object ) {
  26132. let objectData = _objectData.get( object );
  26133. if ( objectData === undefined ) {
  26134. objectData = {};
  26135. _objectData.set( object, objectData );
  26136. }
  26137. return objectData;
  26138. }
  26139. function getPreviousMatrix( object, index = 0 ) {
  26140. const objectData = getData( object );
  26141. let matrix = objectData[ index ];
  26142. if ( matrix === undefined ) {
  26143. objectData[ index ] = matrix = new Matrix4();
  26144. objectData[ index ].copy( object.matrixWorld );
  26145. }
  26146. return matrix;
  26147. }
  26148. /**
  26149. * TSL object that represents the velocity of a render pass.
  26150. *
  26151. * @tsl
  26152. * @type {VelocityNode}
  26153. */
  26154. const velocity = /*@__PURE__*/ nodeImmutable( VelocityNode );
  26155. /**
  26156. * Computes a grayscale value for the given RGB color value.
  26157. *
  26158. * @tsl
  26159. * @function
  26160. * @param {Node<vec3>} color - The color value to compute the grayscale for.
  26161. * @return {Node<vec3>} The grayscale color.
  26162. */
  26163. const grayscale = /*@__PURE__*/ Fn( ( [ color ] ) => {
  26164. return luminance( color.rgb );
  26165. } );
  26166. /**
  26167. * Super-saturates or desaturates the given RGB color.
  26168. *
  26169. * @tsl
  26170. * @function
  26171. * @param {Node<vec3>} color - The input color.
  26172. * @param {Node<float>} [adjustment=1] - Specifies the amount of the conversion. A value under `1` desaturates the color, a value over `1` super-saturates it.
  26173. * @return {Node<vec3>} The saturated color.
  26174. */
  26175. const saturation = /*@__PURE__*/ Fn( ( [ color, adjustment = float( 1 ) ] ) => {
  26176. return adjustment.mix( luminance( color.rgb ), color.rgb );
  26177. } );
  26178. /**
  26179. * Selectively enhance the intensity of less saturated RGB colors. Can result
  26180. * in a more natural and visually appealing image with enhanced color depth
  26181. * compared to {@link ColorAdjustment#saturation}.
  26182. *
  26183. * @tsl
  26184. * @function
  26185. * @param {Node<vec3>} color - The input color.
  26186. * @param {Node<float>} [adjustment=1] - Controls the intensity of the vibrance effect.
  26187. * @return {Node<vec3>} The updated color.
  26188. */
  26189. const vibrance = /*@__PURE__*/ Fn( ( [ color, adjustment = float( 1 ) ] ) => {
  26190. const average = add( color.r, color.g, color.b ).div( 3.0 );
  26191. const mx = color.r.max( color.g.max( color.b ) );
  26192. const amt = mx.sub( average ).mul( adjustment ).mul( -3 );
  26193. return mix( color.rgb, mx, amt );
  26194. } );
  26195. /**
  26196. * Updates the hue component of the given RGB color while preserving its luminance and saturation.
  26197. *
  26198. * @tsl
  26199. * @function
  26200. * @param {Node<vec3>} color - The input color.
  26201. * @param {Node<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.
  26202. * @return {Node<vec3>} The updated color.
  26203. */
  26204. const hue = /*@__PURE__*/ Fn( ( [ color, adjustment = float( 1 ) ] ) => {
  26205. const k = vec3( 0.57735, 0.57735, 0.57735 );
  26206. const cosAngle = adjustment.cos();
  26207. return vec3( color.rgb.mul( cosAngle ).add( k.cross( color.rgb ).mul( adjustment.sin() ).add( k.mul( dot( k, color.rgb ).mul( cosAngle.oneMinus() ) ) ) ) );
  26208. } );
  26209. /**
  26210. * Computes the luminance for the given RGB color value.
  26211. *
  26212. * @tsl
  26213. * @function
  26214. * @param {Node<vec3>} color - The color value to compute the luminance for.
  26215. * @param {?Node<vec3>} luminanceCoefficients - The luminance coefficients. By default predefined values of the current working color space are used.
  26216. * @return {Node<float>} The luminance.
  26217. */
  26218. const luminance = (
  26219. color,
  26220. luminanceCoefficients = vec3( ColorManagement.getLuminanceCoefficients( new Vector3() ) )
  26221. ) => dot( color, luminanceCoefficients );
  26222. /**
  26223. * Color Decision List (CDL) v1.2
  26224. *
  26225. * Compact representation of color grading information, defined by slope, offset, power, and
  26226. * saturation. The CDL should be typically be given input in a log space (such as LogC, ACEScc,
  26227. * or AgX Log), and will return output in the same space. Output may require clamping >=0.
  26228. *
  26229. * @tsl
  26230. * @function
  26231. * @param {Node<vec4>} color Input (-Infinity < input < +Infinity)
  26232. * @param {Node<vec3>} slope Slope (0 ≤ slope < +Infinity)
  26233. * @param {Node<vec3>} offset Offset (-Infinity < offset < +Infinity; typically -1 < offset < 1)
  26234. * @param {Node<vec3>} power Power (0 < power < +Infinity)
  26235. * @param {Node<float>} saturation Saturation (0 ≤ saturation < +Infinity; typically 0 ≤ saturation < 4)
  26236. * @param {Node<vec3>} luminanceCoefficients Luminance coefficients for saturation term, typically Rec. 709
  26237. * @return {Node<vec4>} Output, -Infinity < output < +Infinity
  26238. *
  26239. * References:
  26240. * - ASC CDL v1.2
  26241. * - {@link https://blender.stackexchange.com/a/55239/43930}
  26242. * - {@link https://docs.acescentral.com/specifications/acescc/}
  26243. */
  26244. const cdl = /*@__PURE__*/ Fn( ( [
  26245. color,
  26246. slope = vec3( 1 ),
  26247. offset = vec3( 0 ),
  26248. power = vec3( 1 ),
  26249. saturation = float( 1 ),
  26250. // ASC CDL v1.2 explicitly requires Rec. 709 luminance coefficients.
  26251. luminanceCoefficients = vec3( ColorManagement.getLuminanceCoefficients( new Vector3(), LinearSRGBColorSpace ) )
  26252. ] ) => {
  26253. // NOTE: The ASC CDL v1.2 defines a [0, 1] clamp on the slope+offset term, and another on the
  26254. // saturation term. Per the ACEScc specification and Filament, limits may be omitted to support
  26255. // values outside [0, 1], requiring a workaround for negative values in the power expression.
  26256. const luma = color.rgb.dot( vec3( luminanceCoefficients ) );
  26257. const v = max$1( color.rgb.mul( slope ).add( offset ), 0.0 ).toVar();
  26258. const pv = v.pow( power ).toVar();
  26259. If( v.r.greaterThan( 0.0 ), () => { v.r.assign( pv.r ); } ); // eslint-disable-line
  26260. If( v.g.greaterThan( 0.0 ), () => { v.g.assign( pv.g ); } ); // eslint-disable-line
  26261. If( v.b.greaterThan( 0.0 ), () => { v.b.assign( pv.b ); } ); // eslint-disable-line
  26262. v.assign( luma.add( v.sub( luma ).mul( saturation ) ) );
  26263. return vec4( v.rgb, color.a );
  26264. } );
  26265. /**
  26266. * Represents a posterize effect which reduces the number of colors
  26267. * in an image, resulting in a more blocky and stylized appearance.
  26268. *
  26269. * @augments TempNode
  26270. */
  26271. class PosterizeNode extends TempNode {
  26272. static get type() {
  26273. return 'PosterizeNode';
  26274. }
  26275. /**
  26276. * Constructs a new posterize node.
  26277. *
  26278. * @param {Node} sourceNode - The input color.
  26279. * @param {Node} stepsNode - Controls the intensity of the posterization effect. A lower number results in a more blocky appearance.
  26280. */
  26281. constructor( sourceNode, stepsNode ) {
  26282. super();
  26283. /**
  26284. * The input color.
  26285. *
  26286. * @type {Node}
  26287. */
  26288. this.sourceNode = sourceNode;
  26289. /**
  26290. * Controls the intensity of the posterization effect. A lower number results in a more blocky appearance.
  26291. *
  26292. * @type {Node}
  26293. */
  26294. this.stepsNode = stepsNode;
  26295. }
  26296. setup() {
  26297. const { sourceNode, stepsNode } = this;
  26298. return sourceNode.mul( stepsNode ).floor().div( stepsNode );
  26299. }
  26300. }
  26301. /**
  26302. * TSL function for creating a posterize node.
  26303. *
  26304. * @tsl
  26305. * @function
  26306. * @param {Node} sourceNode - The input color.
  26307. * @param {Node} stepsNode - Controls the intensity of the posterization effect. A lower number results in a more blocky appearance.
  26308. * @returns {PosterizeNode}
  26309. */
  26310. const posterize = /*@__PURE__*/ nodeProxy( PosterizeNode ).setParameterLength( 2 );
  26311. const _size = /*@__PURE__*/ new Vector2();
  26312. /**
  26313. * Represents the texture of a pass node.
  26314. *
  26315. * @augments TextureNode
  26316. */
  26317. class PassTextureNode extends TextureNode {
  26318. static get type() {
  26319. return 'PassTextureNode';
  26320. }
  26321. /**
  26322. * Constructs a new pass texture node.
  26323. *
  26324. * @param {PassNode} passNode - The pass node.
  26325. * @param {Texture} texture - The output texture.
  26326. */
  26327. constructor( passNode, texture ) {
  26328. super( texture );
  26329. /**
  26330. * A reference to the pass node.
  26331. *
  26332. * @type {PassNode}
  26333. */
  26334. this.passNode = passNode;
  26335. this.setUpdateMatrix( false );
  26336. }
  26337. setup( builder ) {
  26338. this.passNode.build( builder );
  26339. return super.setup( builder );
  26340. }
  26341. clone() {
  26342. return new this.constructor( this.passNode, this.value );
  26343. }
  26344. }
  26345. /**
  26346. * An extension of `PassTextureNode` which allows to manage more than one
  26347. * internal texture. Relevant for the `getPreviousTexture()` related API.
  26348. *
  26349. * @augments PassTextureNode
  26350. */
  26351. class PassMultipleTextureNode extends PassTextureNode {
  26352. static get type() {
  26353. return 'PassMultipleTextureNode';
  26354. }
  26355. /**
  26356. * Constructs a new pass texture node.
  26357. *
  26358. * @param {PassNode} passNode - The pass node.
  26359. * @param {string} textureName - The output texture name.
  26360. * @param {boolean} [previousTexture=false] - Whether previous frame data should be used or not.
  26361. */
  26362. constructor( passNode, textureName, previousTexture = false ) {
  26363. // null is passed to the super call since this class does not
  26364. // use an external texture for rendering pass data into. Instead
  26365. // the texture is managed by the pass node itself
  26366. super( passNode, null );
  26367. /**
  26368. * The output texture name.
  26369. *
  26370. * @type {string}
  26371. */
  26372. this.textureName = textureName;
  26373. /**
  26374. * Whether previous frame data should be used or not.
  26375. *
  26376. * @type {boolean}
  26377. */
  26378. this.previousTexture = previousTexture;
  26379. }
  26380. /**
  26381. * Updates the texture reference of this node.
  26382. */
  26383. updateTexture() {
  26384. this.value = this.previousTexture ? this.passNode.getPreviousTexture( this.textureName ) : this.passNode.getTexture( this.textureName );
  26385. }
  26386. setup( builder ) {
  26387. this.updateTexture();
  26388. return super.setup( builder );
  26389. }
  26390. clone() {
  26391. const newNode = new this.constructor( this.passNode, this.textureName, this.previousTexture );
  26392. newNode.uvNode = this.uvNode;
  26393. newNode.levelNode = this.levelNode;
  26394. newNode.biasNode = this.biasNode;
  26395. newNode.sampler = this.sampler;
  26396. newNode.depthNode = this.depthNode;
  26397. newNode.compareNode = this.compareNode;
  26398. newNode.gradNode = this.gradNode;
  26399. newNode.offsetNode = this.offsetNode;
  26400. return newNode;
  26401. }
  26402. }
  26403. /**
  26404. * Represents a render pass (sometimes called beauty pass) in context of post processing.
  26405. * This pass produces a render for the given scene and camera and can provide multiple outputs
  26406. * via MRT for further processing.
  26407. *
  26408. * ```js
  26409. * const postProcessing = new PostProcessing( renderer );
  26410. *
  26411. * const scenePass = pass( scene, camera );
  26412. *
  26413. * postProcessing.outputNode = scenePass;
  26414. * ```
  26415. *
  26416. * @augments TempNode
  26417. */
  26418. class PassNode extends TempNode {
  26419. static get type() {
  26420. return 'PassNode';
  26421. }
  26422. /**
  26423. * Constructs a new pass node.
  26424. *
  26425. * @param {('color'|'depth')} scope - The scope of the pass. The scope determines whether the node outputs color or depth.
  26426. * @param {Scene} scene - A reference to the scene.
  26427. * @param {Camera} camera - A reference to the camera.
  26428. * @param {Object} options - Options for the internal render target.
  26429. */
  26430. constructor( scope, scene, camera, options = {} ) {
  26431. super( 'vec4' );
  26432. /**
  26433. * The scope of the pass. The scope determines whether the node outputs color or depth.
  26434. *
  26435. * @type {('color'|'depth')}
  26436. */
  26437. this.scope = scope;
  26438. /**
  26439. * A reference to the scene.
  26440. *
  26441. * @type {Scene}
  26442. */
  26443. this.scene = scene;
  26444. /**
  26445. * A reference to the camera.
  26446. *
  26447. * @type {Camera}
  26448. */
  26449. this.camera = camera;
  26450. /**
  26451. * Options for the internal render target.
  26452. *
  26453. * @type {Object}
  26454. */
  26455. this.options = options;
  26456. /**
  26457. * The pass's pixel ratio. Will be kept automatically kept in sync with the renderer's pixel ratio.
  26458. *
  26459. * @private
  26460. * @type {number}
  26461. * @default 1
  26462. */
  26463. this._pixelRatio = 1;
  26464. /**
  26465. * The pass's pixel width. Will be kept automatically kept in sync with the renderer's width.
  26466. * @private
  26467. * @type {number}
  26468. * @default 1
  26469. */
  26470. this._width = 1;
  26471. /**
  26472. * The pass's pixel height. Will be kept automatically kept in sync with the renderer's height.
  26473. * @private
  26474. * @type {number}
  26475. * @default 1
  26476. */
  26477. this._height = 1;
  26478. const depthTexture = new DepthTexture();
  26479. depthTexture.isRenderTargetTexture = true;
  26480. //depthTexture.type = FloatType;
  26481. depthTexture.name = 'depth';
  26482. const renderTarget = new RenderTarget( this._width * this._pixelRatio, this._height * this._pixelRatio, { type: HalfFloatType, ...options, } );
  26483. renderTarget.texture.name = 'output';
  26484. renderTarget.depthTexture = depthTexture;
  26485. /**
  26486. * The pass's render target.
  26487. *
  26488. * @type {RenderTarget}
  26489. */
  26490. this.renderTarget = renderTarget;
  26491. /**
  26492. * A dictionary holding the internal result textures.
  26493. *
  26494. * @private
  26495. * @type {Object<string, Texture>}
  26496. */
  26497. this._textures = {
  26498. output: renderTarget.texture,
  26499. depth: depthTexture
  26500. };
  26501. /**
  26502. * A dictionary holding the internal texture nodes.
  26503. *
  26504. * @private
  26505. * @type {Object<string, TextureNode>}
  26506. */
  26507. this._textureNodes = {};
  26508. /**
  26509. * A dictionary holding the internal depth nodes.
  26510. *
  26511. * @private
  26512. * @type {Object}
  26513. */
  26514. this._linearDepthNodes = {};
  26515. /**
  26516. * A dictionary holding the internal viewZ nodes.
  26517. *
  26518. * @private
  26519. * @type {Object}
  26520. */
  26521. this._viewZNodes = {};
  26522. /**
  26523. * A dictionary holding the texture data of the previous frame.
  26524. * Used for computing velocity/motion vectors.
  26525. *
  26526. * @private
  26527. * @type {Object<string, Texture>}
  26528. */
  26529. this._previousTextures = {};
  26530. /**
  26531. * A dictionary holding the texture nodes of the previous frame.
  26532. * Used for computing velocity/motion vectors.
  26533. *
  26534. * @private
  26535. * @type {Object<string, TextureNode>}
  26536. */
  26537. this._previousTextureNodes = {};
  26538. /**
  26539. * The `near` property of the camera as a uniform.
  26540. *
  26541. * @private
  26542. * @type {UniformNode}
  26543. */
  26544. this._cameraNear = uniform( 0 );
  26545. /**
  26546. * The `far` property of the camera as a uniform.
  26547. *
  26548. * @private
  26549. * @type {UniformNode}
  26550. */
  26551. this._cameraFar = uniform( 0 );
  26552. /**
  26553. * A MRT node configuring the MRT settings.
  26554. *
  26555. * @private
  26556. * @type {?MRTNode}
  26557. * @default null
  26558. */
  26559. this._mrt = null;
  26560. /**
  26561. * Layer object for configuring the camera that is used
  26562. * to produce the pass.
  26563. *
  26564. * @private
  26565. * @type {?Layers}
  26566. * @default null
  26567. */
  26568. this._layers = null;
  26569. /**
  26570. * Scales the resolution of the internal render target.
  26571. *
  26572. * @private
  26573. * @type {number}
  26574. * @default 1
  26575. */
  26576. this._resolutionScale = 1;
  26577. /**
  26578. * Custom viewport definition.
  26579. *
  26580. * @private
  26581. * @type {?Vector4}
  26582. * @default null
  26583. */
  26584. this._viewport = null;
  26585. /**
  26586. * Custom scissor definition.
  26587. *
  26588. * @private
  26589. * @type {?Vector4}
  26590. * @default null
  26591. */
  26592. this._scissor = null;
  26593. /**
  26594. * This flag can be used for type testing.
  26595. *
  26596. * @type {boolean}
  26597. * @readonly
  26598. * @default true
  26599. */
  26600. this.isPassNode = true;
  26601. /**
  26602. * The `updateBeforeType` is set to `NodeUpdateType.FRAME` since the node renders the
  26603. * scene once per frame in its {@link PassNode#updateBefore} method.
  26604. *
  26605. * @type {string}
  26606. * @default 'frame'
  26607. */
  26608. this.updateBeforeType = NodeUpdateType.FRAME;
  26609. /**
  26610. * This flag is used for global cache.
  26611. *
  26612. * @type {boolean}
  26613. * @default true
  26614. */
  26615. this.global = true;
  26616. }
  26617. /**
  26618. * Sets the resolution scale for the pass.
  26619. * The resolution scale is a factor that is multiplied with the renderer's width and height.
  26620. *
  26621. * @param {number} resolutionScale - The resolution scale to set. A value of `1` means full resolution.
  26622. * @return {PassNode} A reference to this pass.
  26623. */
  26624. setResolutionScale( resolutionScale ) {
  26625. this._resolutionScale = resolutionScale;
  26626. return this;
  26627. }
  26628. /**
  26629. * Gets the current resolution scale of the pass.
  26630. *
  26631. * @return {number} The current resolution scale. A value of `1` means full resolution.
  26632. */
  26633. getResolutionScale() {
  26634. return this._resolutionScale;
  26635. }
  26636. /**
  26637. * Sets the resolution for the pass.
  26638. * The resolution is a factor that is multiplied with the renderer's width and height.
  26639. *
  26640. * @param {number} resolution - The resolution to set. A value of `1` means full resolution.
  26641. * @return {PassNode} A reference to this pass.
  26642. * @deprecated since r181. Use {@link PassNode#setResolutionScale `setResolutionScale()`} instead.
  26643. */
  26644. setResolution( resolution ) { // @deprecated, r181
  26645. warn( 'PassNode: .setResolution() is deprecated. Use .setResolutionScale() instead.' );
  26646. return this.setResolutionScale( resolution );
  26647. }
  26648. /**
  26649. * Gets the current resolution of the pass.
  26650. *
  26651. * @return {number} The current resolution. A value of `1` means full resolution.
  26652. * @deprecated since r181. Use {@link PassNode#getResolutionScale `getResolutionScale()`} instead.
  26653. */
  26654. getResolution() { // @deprecated, r181
  26655. warn( 'PassNode: .getResolution() is deprecated. Use .getResolutionScale() instead.' );
  26656. return this.getResolutionScale();
  26657. }
  26658. /**
  26659. * Sets the layer configuration that should be used when rendering the pass.
  26660. *
  26661. * @param {Layers} layers - The layers object to set.
  26662. * @return {PassNode} A reference to this pass.
  26663. */
  26664. setLayers( layers ) {
  26665. this._layers = layers;
  26666. return this;
  26667. }
  26668. /**
  26669. * Gets the current layer configuration of the pass.
  26670. *
  26671. * @return {?Layers} .
  26672. */
  26673. getLayers() {
  26674. return this._layers;
  26675. }
  26676. /**
  26677. * Sets the given MRT node to setup MRT for this pass.
  26678. *
  26679. * @param {MRTNode} mrt - The MRT object.
  26680. * @return {PassNode} A reference to this pass.
  26681. */
  26682. setMRT( mrt ) {
  26683. this._mrt = mrt;
  26684. return this;
  26685. }
  26686. /**
  26687. * Returns the current MRT node.
  26688. *
  26689. * @return {MRTNode} The current MRT node.
  26690. */
  26691. getMRT() {
  26692. return this._mrt;
  26693. }
  26694. /**
  26695. * Returns the texture for the given output name.
  26696. *
  26697. * @param {string} name - The output name to get the texture for.
  26698. * @return {Texture} The texture.
  26699. */
  26700. getTexture( name ) {
  26701. let texture = this._textures[ name ];
  26702. if ( texture === undefined ) {
  26703. const refTexture = this.renderTarget.texture;
  26704. texture = refTexture.clone();
  26705. texture.name = name;
  26706. this._textures[ name ] = texture;
  26707. this.renderTarget.textures.push( texture );
  26708. }
  26709. return texture;
  26710. }
  26711. /**
  26712. * Returns the texture holding the data of the previous frame for the given output name.
  26713. *
  26714. * @param {string} name - The output name to get the texture for.
  26715. * @return {Texture} The texture holding the data of the previous frame.
  26716. */
  26717. getPreviousTexture( name ) {
  26718. let texture = this._previousTextures[ name ];
  26719. if ( texture === undefined ) {
  26720. texture = this.getTexture( name ).clone();
  26721. this._previousTextures[ name ] = texture;
  26722. }
  26723. return texture;
  26724. }
  26725. /**
  26726. * Switches current and previous textures for the given output name.
  26727. *
  26728. * @param {string} name - The output name.
  26729. */
  26730. toggleTexture( name ) {
  26731. const prevTexture = this._previousTextures[ name ];
  26732. if ( prevTexture !== undefined ) {
  26733. const texture = this._textures[ name ];
  26734. const index = this.renderTarget.textures.indexOf( texture );
  26735. this.renderTarget.textures[ index ] = prevTexture;
  26736. this._textures[ name ] = prevTexture;
  26737. this._previousTextures[ name ] = texture;
  26738. this._textureNodes[ name ].updateTexture();
  26739. this._previousTextureNodes[ name ].updateTexture();
  26740. }
  26741. }
  26742. /**
  26743. * Returns the texture node for the given output name.
  26744. *
  26745. * @param {string} [name='output'] - The output name to get the texture node for.
  26746. * @return {TextureNode} The texture node.
  26747. */
  26748. getTextureNode( name = 'output' ) {
  26749. let textureNode = this._textureNodes[ name ];
  26750. if ( textureNode === undefined ) {
  26751. textureNode = nodeObject( new PassMultipleTextureNode( this, name ) );
  26752. textureNode.updateTexture();
  26753. this._textureNodes[ name ] = textureNode;
  26754. }
  26755. return textureNode;
  26756. }
  26757. /**
  26758. * Returns the previous texture node for the given output name.
  26759. *
  26760. * @param {string} [name='output'] - The output name to get the previous texture node for.
  26761. * @return {TextureNode} The previous texture node.
  26762. */
  26763. getPreviousTextureNode( name = 'output' ) {
  26764. let textureNode = this._previousTextureNodes[ name ];
  26765. if ( textureNode === undefined ) {
  26766. if ( this._textureNodes[ name ] === undefined ) this.getTextureNode( name );
  26767. textureNode = nodeObject( new PassMultipleTextureNode( this, name, true ) );
  26768. textureNode.updateTexture();
  26769. this._previousTextureNodes[ name ] = textureNode;
  26770. }
  26771. return textureNode;
  26772. }
  26773. /**
  26774. * Returns a viewZ node of this pass.
  26775. *
  26776. * @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.
  26777. * @return {Node} The viewZ node.
  26778. */
  26779. getViewZNode( name = 'depth' ) {
  26780. let viewZNode = this._viewZNodes[ name ];
  26781. if ( viewZNode === undefined ) {
  26782. const cameraNear = this._cameraNear;
  26783. const cameraFar = this._cameraFar;
  26784. this._viewZNodes[ name ] = viewZNode = perspectiveDepthToViewZ( this.getTextureNode( name ), cameraNear, cameraFar );
  26785. }
  26786. return viewZNode;
  26787. }
  26788. /**
  26789. * Returns a linear depth node of this pass.
  26790. *
  26791. * @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.
  26792. * @return {Node} The linear depth node.
  26793. */
  26794. getLinearDepthNode( name = 'depth' ) {
  26795. let linearDepthNode = this._linearDepthNodes[ name ];
  26796. if ( linearDepthNode === undefined ) {
  26797. const cameraNear = this._cameraNear;
  26798. const cameraFar = this._cameraFar;
  26799. const viewZNode = this.getViewZNode( name );
  26800. // TODO: just if ( builder.camera.isPerspectiveCamera )
  26801. this._linearDepthNodes[ name ] = linearDepthNode = viewZToOrthographicDepth( viewZNode, cameraNear, cameraFar );
  26802. }
  26803. return linearDepthNode;
  26804. }
  26805. /**
  26806. * Precompiles the pass.
  26807. *
  26808. * Note that this method must be called after the pass configuration is complete.
  26809. * So calls like `setMRT()` and `getTextureNode()` must proceed the precompilation.
  26810. *
  26811. * @async
  26812. * @param {Renderer} renderer - The renderer.
  26813. * @return {Promise} A Promise that resolves when the compile has been finished.
  26814. * @see {@link Renderer#compileAsync}
  26815. */
  26816. async compileAsync( renderer ) {
  26817. const currentRenderTarget = renderer.getRenderTarget();
  26818. const currentMRT = renderer.getMRT();
  26819. renderer.setRenderTarget( this.renderTarget );
  26820. renderer.setMRT( this._mrt );
  26821. await renderer.compileAsync( this.scene, this.camera );
  26822. renderer.setRenderTarget( currentRenderTarget );
  26823. renderer.setMRT( currentMRT );
  26824. }
  26825. setup( { renderer } ) {
  26826. this.renderTarget.samples = this.options.samples === undefined ? renderer.samples : this.options.samples;
  26827. this.renderTarget.texture.type = renderer.getColorBufferType();
  26828. return this.scope === PassNode.COLOR ? this.getTextureNode() : this.getLinearDepthNode();
  26829. }
  26830. updateBefore( frame ) {
  26831. const { renderer } = frame;
  26832. const { scene } = this;
  26833. let camera;
  26834. let pixelRatio;
  26835. const outputRenderTarget = renderer.getOutputRenderTarget();
  26836. if ( outputRenderTarget && outputRenderTarget.isXRRenderTarget === true ) {
  26837. pixelRatio = 1;
  26838. camera = renderer.xr.getCamera();
  26839. renderer.xr.updateCamera( camera );
  26840. _size.set( outputRenderTarget.width, outputRenderTarget.height );
  26841. } else {
  26842. camera = this.camera;
  26843. pixelRatio = renderer.getPixelRatio();
  26844. renderer.getSize( _size );
  26845. }
  26846. this._pixelRatio = pixelRatio;
  26847. this.setSize( _size.width, _size.height );
  26848. const currentRenderTarget = renderer.getRenderTarget();
  26849. const currentMRT = renderer.getMRT();
  26850. const currentAutoClear = renderer.autoClear;
  26851. const currentMask = camera.layers.mask;
  26852. this._cameraNear.value = camera.near;
  26853. this._cameraFar.value = camera.far;
  26854. if ( this._layers !== null ) {
  26855. camera.layers.mask = this._layers.mask;
  26856. }
  26857. for ( const name in this._previousTextures ) {
  26858. this.toggleTexture( name );
  26859. }
  26860. renderer.setRenderTarget( this.renderTarget );
  26861. renderer.setMRT( this._mrt );
  26862. renderer.autoClear = true;
  26863. const currentSceneName = scene.name;
  26864. scene.name = this.name ? this.name : scene.name;
  26865. renderer.render( scene, camera );
  26866. scene.name = currentSceneName;
  26867. renderer.setRenderTarget( currentRenderTarget );
  26868. renderer.setMRT( currentMRT );
  26869. renderer.autoClear = currentAutoClear;
  26870. camera.layers.mask = currentMask;
  26871. }
  26872. /**
  26873. * Sets the size of the pass's render target. Honors the pixel ratio.
  26874. *
  26875. * @param {number} width - The width to set.
  26876. * @param {number} height - The height to set.
  26877. */
  26878. setSize( width, height ) {
  26879. this._width = width;
  26880. this._height = height;
  26881. const effectiveWidth = Math.floor( this._width * this._pixelRatio * this._resolutionScale );
  26882. const effectiveHeight = Math.floor( this._height * this._pixelRatio * this._resolutionScale );
  26883. this.renderTarget.setSize( effectiveWidth, effectiveHeight );
  26884. if ( this._scissor !== null ) this.renderTarget.scissor.copy( this._scissor );
  26885. if ( this._viewport !== null ) this.renderTarget.viewport.copy( this._viewport );
  26886. }
  26887. /**
  26888. * This method allows to define the pass's scissor rectangle. By default, the scissor rectangle is kept
  26889. * in sync with the pass's dimensions. To reverse the process and use auto-sizing again, call the method
  26890. * with `null` as the single argument.
  26891. *
  26892. * @param {?(number | Vector4)} x - The horizontal coordinate for the lower left corner of the box in logical pixel unit.
  26893. * Instead of passing four arguments, the method also works with a single four-dimensional vector.
  26894. * @param {number} y - The vertical coordinate for the lower left corner of the box in logical pixel unit.
  26895. * @param {number} width - The width of the scissor box in logical pixel unit.
  26896. * @param {number} height - The height of the scissor box in logical pixel unit.
  26897. */
  26898. setScissor( x, y, width, height ) {
  26899. if ( x === null ) {
  26900. this._scissor = null;
  26901. } else {
  26902. if ( this._scissor === null ) this._scissor = new Vector4();
  26903. if ( x.isVector4 ) {
  26904. this._scissor.copy( x );
  26905. } else {
  26906. this._scissor.set( x, y, width, height );
  26907. }
  26908. this._scissor.multiplyScalar( this._pixelRatio * this._resolutionScale ).floor();
  26909. }
  26910. }
  26911. /**
  26912. * This method allows to define the pass's viewport. By default, the viewport is kept in sync
  26913. * with the pass's dimensions. To reverse the process and use auto-sizing again, call the method
  26914. * with `null` as the single argument.
  26915. *
  26916. * @param {number | Vector4} x - The horizontal coordinate for the lower left corner of the viewport origin in logical pixel unit.
  26917. * @param {number} y - The vertical coordinate for the lower left corner of the viewport origin in logical pixel unit.
  26918. * @param {number} width - The width of the viewport in logical pixel unit.
  26919. * @param {number} height - The height of the viewport in logical pixel unit.
  26920. */
  26921. setViewport( x, y, width, height ) {
  26922. if ( x === null ) {
  26923. this._viewport = null;
  26924. } else {
  26925. if ( this._viewport === null ) this._viewport = new Vector4();
  26926. if ( x.isVector4 ) {
  26927. this._viewport.copy( x );
  26928. } else {
  26929. this._viewport.set( x, y, width, height );
  26930. }
  26931. this._viewport.multiplyScalar( this._pixelRatio * this._resolutionScale ).floor();
  26932. }
  26933. }
  26934. /**
  26935. * Sets the pixel ratio the pass's render target and updates the size.
  26936. *
  26937. * @param {number} pixelRatio - The pixel ratio to set.
  26938. */
  26939. setPixelRatio( pixelRatio ) {
  26940. this._pixelRatio = pixelRatio;
  26941. this.setSize( this._width, this._height );
  26942. }
  26943. /**
  26944. * Frees internal resources. Should be called when the node is no longer in use.
  26945. */
  26946. dispose() {
  26947. this.renderTarget.dispose();
  26948. }
  26949. }
  26950. /**
  26951. * @static
  26952. * @type {'color'}
  26953. * @default 'color'
  26954. */
  26955. PassNode.COLOR = 'color';
  26956. /**
  26957. * @static
  26958. * @type {'depth'}
  26959. * @default 'depth'
  26960. */
  26961. PassNode.DEPTH = 'depth';
  26962. /**
  26963. * TSL function for creating a pass node.
  26964. *
  26965. * @tsl
  26966. * @function
  26967. * @param {Scene} scene - A reference to the scene.
  26968. * @param {Camera} camera - A reference to the camera.
  26969. * @param {Object} options - Options for the internal render target.
  26970. * @returns {PassNode}
  26971. */
  26972. const pass = ( scene, camera, options ) => nodeObject( new PassNode( PassNode.COLOR, scene, camera, options ) );
  26973. /**
  26974. * TSL function for creating a pass texture node.
  26975. *
  26976. * @tsl
  26977. * @function
  26978. * @param {PassNode} pass - The pass node.
  26979. * @param {Texture} texture - The output texture.
  26980. * @returns {PassTextureNode}
  26981. */
  26982. const passTexture = ( pass, texture ) => nodeObject( new PassTextureNode( pass, texture ) );
  26983. /**
  26984. * TSL function for creating a depth pass node.
  26985. *
  26986. * @tsl
  26987. * @function
  26988. * @param {Scene} scene - A reference to the scene.
  26989. * @param {Camera} camera - A reference to the camera.
  26990. * @param {Object} options - Options for the internal render target.
  26991. * @returns {PassNode}
  26992. */
  26993. const depthPass = ( scene, camera, options ) => nodeObject( new PassNode( PassNode.DEPTH, scene, camera, options ) );
  26994. /**
  26995. * Represents a render pass for producing a toon outline effect on compatible objects.
  26996. * Only 3D objects with materials of type `MeshToonMaterial` and `MeshToonNodeMaterial`
  26997. * will receive the outline.
  26998. *
  26999. * ```js
  27000. * const postProcessing = new PostProcessing( renderer );
  27001. *
  27002. * const scenePass = toonOutlinePass( scene, camera );
  27003. *
  27004. * postProcessing.outputNode = scenePass;
  27005. * ```
  27006. * @augments PassNode
  27007. */
  27008. class ToonOutlinePassNode extends PassNode {
  27009. static get type() {
  27010. return 'ToonOutlinePassNode';
  27011. }
  27012. /**
  27013. * Constructs a new outline pass node.
  27014. *
  27015. * @param {Scene} scene - A reference to the scene.
  27016. * @param {Camera} camera - A reference to the camera.
  27017. * @param {Node} colorNode - Defines the outline's color.
  27018. * @param {Node} thicknessNode - Defines the outline's thickness.
  27019. * @param {Node} alphaNode - Defines the outline's alpha.
  27020. */
  27021. constructor( scene, camera, colorNode, thicknessNode, alphaNode ) {
  27022. super( PassNode.COLOR, scene, camera );
  27023. /**
  27024. * Defines the outline's color.
  27025. *
  27026. * @type {Node}
  27027. */
  27028. this.colorNode = colorNode;
  27029. /**
  27030. * Defines the outline's thickness.
  27031. *
  27032. * @type {Node}
  27033. */
  27034. this.thicknessNode = thicknessNode;
  27035. /**
  27036. * Defines the outline's alpha.
  27037. *
  27038. * @type {Node}
  27039. */
  27040. this.alphaNode = alphaNode;
  27041. /**
  27042. * An internal material cache.
  27043. *
  27044. * @private
  27045. * @type {WeakMap<Material, NodeMaterial>}
  27046. */
  27047. this._materialCache = new WeakMap();
  27048. /**
  27049. * The name of this pass.
  27050. *
  27051. * @type {string}
  27052. * @default 'Outline Pass'
  27053. */
  27054. this.name = 'Outline Pass';
  27055. }
  27056. updateBefore( frame ) {
  27057. const { renderer } = frame;
  27058. const currentRenderObjectFunction = renderer.getRenderObjectFunction();
  27059. renderer.setRenderObjectFunction( ( object, scene, camera, geometry, material, group, lightsNode, clippingContext ) => {
  27060. // only render outline for supported materials
  27061. if ( material.isMeshToonMaterial || material.isMeshToonNodeMaterial ) {
  27062. if ( material.wireframe === false ) {
  27063. const outlineMaterial = this._getOutlineMaterial( material );
  27064. renderer.renderObject( object, scene, camera, geometry, outlineMaterial, group, lightsNode, clippingContext );
  27065. }
  27066. }
  27067. // default
  27068. renderer.renderObject( object, scene, camera, geometry, material, group, lightsNode, clippingContext );
  27069. } );
  27070. super.updateBefore( frame );
  27071. renderer.setRenderObjectFunction( currentRenderObjectFunction );
  27072. }
  27073. /**
  27074. * Creates the material used for outline rendering.
  27075. *
  27076. * @private
  27077. * @return {NodeMaterial} The outline material.
  27078. */
  27079. _createMaterial() {
  27080. const material = new NodeMaterial();
  27081. material.isMeshToonOutlineMaterial = true;
  27082. material.name = 'Toon_Outline';
  27083. material.side = BackSide;
  27084. // vertex node
  27085. const outlineNormal = normalLocal.negate();
  27086. const mvp = cameraProjectionMatrix.mul( modelViewMatrix );
  27087. const ratio = float( 1.0 ); // TODO: support outline thickness ratio for each vertex
  27088. const pos = mvp.mul( vec4( positionLocal, 1.0 ) );
  27089. const pos2 = mvp.mul( vec4( positionLocal.add( outlineNormal ), 1.0 ) );
  27090. const norm = normalize( pos.sub( pos2 ) ); // NOTE: subtract pos2 from pos because BackSide objectNormal is negative
  27091. material.vertexNode = pos.add( norm.mul( this.thicknessNode ).mul( pos.w ).mul( ratio ) );
  27092. // color node
  27093. material.colorNode = vec4( this.colorNode, this.alphaNode );
  27094. return material;
  27095. }
  27096. /**
  27097. * For the given toon material, this method returns a corresponding
  27098. * outline material.
  27099. *
  27100. * @private
  27101. * @param {(MeshToonMaterial|MeshToonNodeMaterial)} originalMaterial - The toon material.
  27102. * @return {NodeMaterial} The outline material.
  27103. */
  27104. _getOutlineMaterial( originalMaterial ) {
  27105. let outlineMaterial = this._materialCache.get( originalMaterial );
  27106. if ( outlineMaterial === undefined ) {
  27107. outlineMaterial = this._createMaterial();
  27108. this._materialCache.set( originalMaterial, outlineMaterial );
  27109. }
  27110. return outlineMaterial;
  27111. }
  27112. }
  27113. /**
  27114. * TSL function for creating a toon outline pass node.
  27115. *
  27116. * @tsl
  27117. * @function
  27118. * @param {Scene} scene - A reference to the scene.
  27119. * @param {Camera} camera - A reference to the camera.
  27120. * @param {Color} color - Defines the outline's color.
  27121. * @param {number} [thickness=0.003] - Defines the outline's thickness.
  27122. * @param {number} [alpha=1] - Defines the outline's alpha.
  27123. * @returns {ToonOutlinePassNode}
  27124. */
  27125. 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 ) ) );
  27126. /**
  27127. * Linear tone mapping, exposure only.
  27128. *
  27129. * @tsl
  27130. * @function
  27131. * @param {Node<vec3>} color - The color that should be tone mapped.
  27132. * @param {Node<float>} exposure - The exposure.
  27133. * @return {Node<vec3>} The tone mapped color.
  27134. */
  27135. const linearToneMapping = /*@__PURE__*/ Fn( ( [ color, exposure ] ) => {
  27136. return color.mul( exposure ).clamp();
  27137. } ).setLayout( {
  27138. name: 'linearToneMapping',
  27139. type: 'vec3',
  27140. inputs: [
  27141. { name: 'color', type: 'vec3' },
  27142. { name: 'exposure', type: 'float' }
  27143. ]
  27144. } );
  27145. /**
  27146. * Reinhard tone mapping.
  27147. *
  27148. * Reference: {@link https://www.cs.utah.edu/docs/techreports/2002/pdf/UUCS-02-001.pdf}
  27149. *
  27150. * @tsl
  27151. * @function
  27152. * @param {Node<vec3>} color - The color that should be tone mapped.
  27153. * @param {Node<float>} exposure - The exposure.
  27154. * @return {Node<vec3>} The tone mapped color.
  27155. */
  27156. const reinhardToneMapping = /*@__PURE__*/ Fn( ( [ color, exposure ] ) => {
  27157. color = color.mul( exposure );
  27158. return color.div( color.add( 1.0 ) ).clamp();
  27159. } ).setLayout( {
  27160. name: 'reinhardToneMapping',
  27161. type: 'vec3',
  27162. inputs: [
  27163. { name: 'color', type: 'vec3' },
  27164. { name: 'exposure', type: 'float' }
  27165. ]
  27166. } );
  27167. /**
  27168. * Cineon tone mapping.
  27169. *
  27170. * Reference: {@link http://filmicworlds.com/blog/filmic-tonemapping-operators/}
  27171. *
  27172. * @tsl
  27173. * @function
  27174. * @param {Node<vec3>} color - The color that should be tone mapped.
  27175. * @param {Node<float>} exposure - The exposure.
  27176. * @return {Node<vec3>} The tone mapped color.
  27177. */
  27178. const cineonToneMapping = /*@__PURE__*/ Fn( ( [ color, exposure ] ) => {
  27179. // filmic operator by Jim Hejl and Richard Burgess-Dawson
  27180. color = color.mul( exposure );
  27181. color = color.sub( 0.004 ).max( 0.0 );
  27182. const a = color.mul( color.mul( 6.2 ).add( 0.5 ) );
  27183. const b = color.mul( color.mul( 6.2 ).add( 1.7 ) ).add( 0.06 );
  27184. return a.div( b ).pow( 2.2 );
  27185. } ).setLayout( {
  27186. name: 'cineonToneMapping',
  27187. type: 'vec3',
  27188. inputs: [
  27189. { name: 'color', type: 'vec3' },
  27190. { name: 'exposure', type: 'float' }
  27191. ]
  27192. } );
  27193. // source: https://github.com/selfshadow/ltc_code/blob/master/webgl/shaders/ltc/ltc_blit.fs
  27194. const RRTAndODTFit = /*@__PURE__*/ Fn( ( [ color ] ) => {
  27195. const a = color.mul( color.add( 0.0245786 ) ).sub( 0.000090537 );
  27196. const b = color.mul( color.add( 0.4329510 ).mul( 0.983729 ) ).add( 0.238081 );
  27197. return a.div( b );
  27198. } );
  27199. /**
  27200. * ACESFilmic tone mapping.
  27201. *
  27202. * Reference: {@link https://github.com/selfshadow/ltc_code/blob/master/webgl/shaders/ltc/ltc_blit.fs}
  27203. *
  27204. * @tsl
  27205. * @function
  27206. * @param {Node<vec3>} color - The color that should be tone mapped.
  27207. * @param {Node<float>} exposure - The exposure.
  27208. * @return {Node<vec3>} The tone mapped color.
  27209. */
  27210. const acesFilmicToneMapping = /*@__PURE__*/ Fn( ( [ color, exposure ] ) => {
  27211. // sRGB => XYZ => D65_2_D60 => AP1 => RRT_SAT
  27212. const ACESInputMat = mat3(
  27213. 0.59719, 0.35458, 0.04823,
  27214. 0.07600, 0.90834, 0.01566,
  27215. 0.02840, 0.13383, 0.83777
  27216. );
  27217. // ODT_SAT => XYZ => D60_2_D65 => sRGB
  27218. const ACESOutputMat = mat3(
  27219. 1.60475, -0.53108, -0.07367,
  27220. -0.10208, 1.10813, -605e-5,
  27221. -327e-5, -0.07276, 1.07602
  27222. );
  27223. color = color.mul( exposure ).div( 0.6 );
  27224. color = ACESInputMat.mul( color );
  27225. // Apply RRT and ODT
  27226. color = RRTAndODTFit( color );
  27227. color = ACESOutputMat.mul( color );
  27228. // Clamp to [0, 1]
  27229. return color.clamp();
  27230. } ).setLayout( {
  27231. name: 'acesFilmicToneMapping',
  27232. type: 'vec3',
  27233. inputs: [
  27234. { name: 'color', type: 'vec3' },
  27235. { name: 'exposure', type: 'float' }
  27236. ]
  27237. } );
  27238. 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, -83e-4, 1.1187 ) );
  27239. 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 ) );
  27240. const agxDefaultContrastApprox = /*@__PURE__*/ Fn( ( [ x_immutable ] ) => {
  27241. const x = vec3( x_immutable ).toVar();
  27242. const x2 = vec3( x.mul( x ) ).toVar();
  27243. const x4 = vec3( x2.mul( x2 ) ).toVar();
  27244. 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 ) ) ) );
  27245. } );
  27246. /**
  27247. * AgX tone mapping.
  27248. *
  27249. * @tsl
  27250. * @function
  27251. * @param {Node<vec3>} color - The color that should be tone mapped.
  27252. * @param {Node<float>} exposure - The exposure.
  27253. * @return {Node<vec3>} The tone mapped color.
  27254. */
  27255. const agxToneMapping = /*@__PURE__*/ Fn( ( [ color, exposure ] ) => {
  27256. const colortone = vec3( color ).toVar();
  27257. const AgXInsetMatrix = mat3( vec3( 0.856627153315983, 0.137318972929847, 0.11189821299995 ), vec3( 0.0951212405381588, 0.761241990602591, 0.0767994186031903 ), vec3( 0.0482516061458583, 0.101439036467562, 0.811302368396859 ) );
  27258. const AgXOutsetMatrix = mat3( vec3( 1.1271005818144368, -0.1413297634984383, -0.14132976349843826 ), vec3( -0.11060664309660323, 1.157823702216272, -0.11060664309660294 ), vec3( -0.016493938717834573, -0.016493938717834257, 1.2519364065950405 ) );
  27259. const AgxMinEv = float( -12.47393 );
  27260. const AgxMaxEv = float( 4.026069 );
  27261. colortone.mulAssign( exposure );
  27262. colortone.assign( LINEAR_SRGB_TO_LINEAR_REC2020.mul( colortone ) );
  27263. colortone.assign( AgXInsetMatrix.mul( colortone ) );
  27264. colortone.assign( max$1( colortone, 1e-10 ) );
  27265. colortone.assign( log2( colortone ) );
  27266. colortone.assign( colortone.sub( AgxMinEv ).div( AgxMaxEv.sub( AgxMinEv ) ) );
  27267. colortone.assign( clamp( colortone, 0.0, 1.0 ) );
  27268. colortone.assign( agxDefaultContrastApprox( colortone ) );
  27269. colortone.assign( AgXOutsetMatrix.mul( colortone ) );
  27270. colortone.assign( pow( max$1( vec3( 0.0 ), colortone ), vec3( 2.2 ) ) );
  27271. colortone.assign( LINEAR_REC2020_TO_LINEAR_SRGB.mul( colortone ) );
  27272. colortone.assign( clamp( colortone, 0.0, 1.0 ) );
  27273. return colortone;
  27274. } ).setLayout( {
  27275. name: 'agxToneMapping',
  27276. type: 'vec3',
  27277. inputs: [
  27278. { name: 'color', type: 'vec3' },
  27279. { name: 'exposure', type: 'float' }
  27280. ]
  27281. } );
  27282. /**
  27283. * Neutral tone mapping.
  27284. *
  27285. * Reference: {@link https://modelviewer.dev/examples/tone-mapping}
  27286. *
  27287. * @tsl
  27288. * @function
  27289. * @param {Node<vec3>} color - The color that should be tone mapped.
  27290. * @param {Node<float>} exposure - The exposure.
  27291. * @return {Node<vec3>} The tone mapped color.
  27292. */
  27293. const neutralToneMapping = /*@__PURE__*/ Fn( ( [ color, exposure ] ) => {
  27294. const StartCompression = float( 0.8 - 0.04 );
  27295. const Desaturation = float( 0.15 );
  27296. color = color.mul( exposure );
  27297. const x = min$1( color.r, min$1( color.g, color.b ) );
  27298. const offset = select( x.lessThan( 0.08 ), x.sub( mul( 6.25, x.mul( x ) ) ), 0.04 );
  27299. color.subAssign( offset );
  27300. const peak = max$1( color.r, max$1( color.g, color.b ) );
  27301. If( peak.lessThan( StartCompression ), () => {
  27302. return color;
  27303. } );
  27304. const d = sub( 1, StartCompression );
  27305. const newPeak = sub( 1, d.mul( d ).div( peak.add( d.sub( StartCompression ) ) ) );
  27306. color.mulAssign( newPeak.div( peak ) );
  27307. const g = sub( 1, div( 1, Desaturation.mul( peak.sub( newPeak ) ).add( 1 ) ) );
  27308. return mix( color, vec3( newPeak ), g );
  27309. } ).setLayout( {
  27310. name: 'neutralToneMapping',
  27311. type: 'vec3',
  27312. inputs: [
  27313. { name: 'color', type: 'vec3' },
  27314. { name: 'exposure', type: 'float' }
  27315. ]
  27316. } );
  27317. /**
  27318. * This class represents native code sections. It is the base
  27319. * class for modules like {@link FunctionNode} which allows to implement
  27320. * functions with native shader languages.
  27321. *
  27322. * @augments Node
  27323. */
  27324. class CodeNode extends Node {
  27325. static get type() {
  27326. return 'CodeNode';
  27327. }
  27328. /**
  27329. * Constructs a new code node.
  27330. *
  27331. * @param {string} [code=''] - The native code.
  27332. * @param {Array<Node>} [includes=[]] - An array of includes.
  27333. * @param {('js'|'wgsl'|'glsl')} [language=''] - The used language.
  27334. */
  27335. constructor( code = '', includes = [], language = '' ) {
  27336. super( 'code' );
  27337. /**
  27338. * This flag can be used for type testing.
  27339. *
  27340. * @type {boolean}
  27341. * @readonly
  27342. * @default true
  27343. */
  27344. this.isCodeNode = true;
  27345. /**
  27346. * This flag is used for global cache.
  27347. *
  27348. * @type {boolean}
  27349. * @default true
  27350. */
  27351. this.global = true;
  27352. /**
  27353. * The native code.
  27354. *
  27355. * @type {string}
  27356. * @default ''
  27357. */
  27358. this.code = code;
  27359. /**
  27360. * An array of includes
  27361. *
  27362. * @type {Array<Node>}
  27363. * @default []
  27364. */
  27365. this.includes = includes;
  27366. /**
  27367. * The used language.
  27368. *
  27369. * @type {('js'|'wgsl'|'glsl')}
  27370. * @default ''
  27371. */
  27372. this.language = language;
  27373. }
  27374. /**
  27375. * Sets the includes of this code node.
  27376. *
  27377. * @param {Array<Node>} includes - The includes to set.
  27378. * @return {CodeNode} A reference to this node.
  27379. */
  27380. setIncludes( includes ) {
  27381. this.includes = includes;
  27382. return this;
  27383. }
  27384. /**
  27385. * Returns the includes of this code node.
  27386. *
  27387. * @param {NodeBuilder} builder - The current node builder.
  27388. * @return {Array<Node>} The includes.
  27389. */
  27390. getIncludes( /*builder*/ ) {
  27391. return this.includes;
  27392. }
  27393. generate( builder ) {
  27394. const includes = this.getIncludes( builder );
  27395. for ( const include of includes ) {
  27396. include.build( builder );
  27397. }
  27398. const nodeCode = builder.getCodeFromNode( this, this.getNodeType( builder ) );
  27399. nodeCode.code = this.code;
  27400. return nodeCode.code;
  27401. }
  27402. serialize( data ) {
  27403. super.serialize( data );
  27404. data.code = this.code;
  27405. data.language = this.language;
  27406. }
  27407. deserialize( data ) {
  27408. super.deserialize( data );
  27409. this.code = data.code;
  27410. this.language = data.language;
  27411. }
  27412. }
  27413. /**
  27414. * TSL function for creating a code node.
  27415. *
  27416. * @tsl
  27417. * @function
  27418. * @param {string} [code] - The native code.
  27419. * @param {?Array<Node>} [includes=[]] - An array of includes.
  27420. * @param {?('js'|'wgsl'|'glsl')} [language=''] - The used language.
  27421. * @returns {CodeNode}
  27422. */
  27423. const code = /*@__PURE__*/ nodeProxy( CodeNode ).setParameterLength( 1, 3 );
  27424. /**
  27425. * TSL function for creating a JS code node.
  27426. *
  27427. * @tsl
  27428. * @function
  27429. * @param {string} src - The native code.
  27430. * @param {Array<Node>} includes - An array of includes.
  27431. * @returns {CodeNode}
  27432. */
  27433. const js = ( src, includes ) => code( src, includes, 'js' );
  27434. /**
  27435. * TSL function for creating a WGSL code node.
  27436. *
  27437. * @tsl
  27438. * @function
  27439. * @param {string} src - The native code.
  27440. * @param {Array<Node>} includes - An array of includes.
  27441. * @returns {CodeNode}
  27442. */
  27443. const wgsl = ( src, includes ) => code( src, includes, 'wgsl' );
  27444. /**
  27445. * TSL function for creating a GLSL code node.
  27446. *
  27447. * @tsl
  27448. * @function
  27449. * @param {string} src - The native code.
  27450. * @param {Array<Node>} includes - An array of includes.
  27451. * @returns {CodeNode}
  27452. */
  27453. const glsl = ( src, includes ) => code( src, includes, 'glsl' );
  27454. /**
  27455. * This class represents a native shader function. It can be used to implement
  27456. * certain aspects of a node material with native shader code. There are two predefined
  27457. * TSL functions for easier usage.
  27458. *
  27459. * - `wgslFn`: Creates a WGSL function node.
  27460. * - `glslFn`: Creates a GLSL function node.
  27461. *
  27462. * A basic example with one include looks like so:
  27463. *
  27464. * ```js
  27465. * const desaturateWGSLFn = wgslFn( `
  27466. * fn desaturate( color:vec3<f32> ) -> vec3<f32> {
  27467. * let lum = vec3<f32>( 0.299, 0.587, 0.114 );
  27468. * return vec3<f32>( dot( lum, color ) );
  27469. * }`
  27470. *);
  27471. * const someWGSLFn = wgslFn( `
  27472. * fn someFn( color:vec3<f32> ) -> vec3<f32> {
  27473. * return desaturate( color );
  27474. * }
  27475. * `, [ desaturateWGSLFn ] );
  27476. * material.colorNode = someWGSLFn( { color: texture( map ) } );
  27477. *```
  27478. * @augments CodeNode
  27479. */
  27480. class FunctionNode extends CodeNode {
  27481. static get type() {
  27482. return 'FunctionNode';
  27483. }
  27484. /**
  27485. * Constructs a new function node.
  27486. *
  27487. * @param {string} [code=''] - The native code.
  27488. * @param {Array<Node>} [includes=[]] - An array of includes.
  27489. * @param {('js'|'wgsl'|'glsl')} [language=''] - The used language.
  27490. */
  27491. constructor( code = '', includes = [], language = '' ) {
  27492. super( code, includes, language );
  27493. }
  27494. /**
  27495. * Returns the type of this function node.
  27496. *
  27497. * @param {NodeBuilder} builder - The current node builder.
  27498. * @return {string} The type.
  27499. */
  27500. getNodeType( builder ) {
  27501. return this.getNodeFunction( builder ).type;
  27502. }
  27503. /**
  27504. * Returns the type of a member of this function node.
  27505. *
  27506. * @param {NodeBuilder} builder - The current node builder.
  27507. * @param {string} name - The name of the member.
  27508. * @return {string} The type of the member.
  27509. */
  27510. getMemberType( builder, name ) {
  27511. const type = this.getNodeType( builder );
  27512. const structType = builder.getStructTypeNode( type );
  27513. return structType.getMemberType( builder, name );
  27514. }
  27515. /**
  27516. * Returns the inputs of this function node.
  27517. *
  27518. * @param {NodeBuilder} builder - The current node builder.
  27519. * @return {Array<NodeFunctionInput>} The inputs.
  27520. */
  27521. getInputs( builder ) {
  27522. return this.getNodeFunction( builder ).inputs;
  27523. }
  27524. /**
  27525. * Returns the node function for this function node.
  27526. *
  27527. * @param {NodeBuilder} builder - The current node builder.
  27528. * @return {NodeFunction} The node function.
  27529. */
  27530. getNodeFunction( builder ) {
  27531. const nodeData = builder.getDataFromNode( this );
  27532. let nodeFunction = nodeData.nodeFunction;
  27533. if ( nodeFunction === undefined ) {
  27534. nodeFunction = builder.parser.parseFunction( this.code );
  27535. nodeData.nodeFunction = nodeFunction;
  27536. }
  27537. return nodeFunction;
  27538. }
  27539. generate( builder, output ) {
  27540. super.generate( builder );
  27541. const nodeFunction = this.getNodeFunction( builder );
  27542. const name = nodeFunction.name;
  27543. const type = nodeFunction.type;
  27544. const nodeCode = builder.getCodeFromNode( this, type );
  27545. if ( name !== '' ) {
  27546. // use a custom property name
  27547. nodeCode.name = name;
  27548. }
  27549. const propertyName = builder.getPropertyName( nodeCode );
  27550. const code = this.getNodeFunction( builder ).getCode( propertyName );
  27551. nodeCode.code = code + '\n';
  27552. if ( output === 'property' ) {
  27553. return propertyName;
  27554. } else {
  27555. return builder.format( `${ propertyName }()`, type, output );
  27556. }
  27557. }
  27558. }
  27559. const nativeFn = ( code, includes = [], language = '' ) => {
  27560. for ( let i = 0; i < includes.length; i ++ ) {
  27561. const include = includes[ i ];
  27562. // TSL Function: glslFn, wgslFn
  27563. if ( typeof include === 'function' ) {
  27564. includes[ i ] = include.functionNode;
  27565. }
  27566. }
  27567. const functionNode = nodeObject( new FunctionNode( code, includes, language ) );
  27568. const fn = ( ...params ) => functionNode.call( ...params );
  27569. fn.functionNode = functionNode;
  27570. return fn;
  27571. };
  27572. const glslFn = ( code, includes ) => nativeFn( code, includes, 'glsl' );
  27573. const wgslFn = ( code, includes ) => nativeFn( code, includes, 'wgsl' );
  27574. /**
  27575. * `ScriptableNode` uses this class to manage script inputs and outputs.
  27576. *
  27577. * @augments Node
  27578. */
  27579. class ScriptableValueNode extends Node {
  27580. static get type() {
  27581. return 'ScriptableValueNode';
  27582. }
  27583. /**
  27584. * Constructs a new scriptable node.
  27585. *
  27586. * @param {any} [value=null] - The value.
  27587. */
  27588. constructor( value = null ) {
  27589. super();
  27590. /**
  27591. * A reference to the value.
  27592. *
  27593. * @private
  27594. * @default null
  27595. */
  27596. this._value = value;
  27597. /**
  27598. * Depending on the type of `_value`, this property might cache parsed data.
  27599. *
  27600. * @private
  27601. * @default null
  27602. */
  27603. this._cache = null;
  27604. /**
  27605. * If this node represents an input, this property represents the input type.
  27606. *
  27607. * @type {?string}
  27608. * @default null
  27609. */
  27610. this.inputType = null;
  27611. /**
  27612. * If this node represents an output, this property represents the output type.
  27613. *
  27614. * @type {?string}
  27615. * @default null
  27616. */
  27617. this.outputType = null;
  27618. /**
  27619. * An event dispatcher for managing events.
  27620. *
  27621. * @type {EventDispatcher}
  27622. */
  27623. this.events = new EventDispatcher();
  27624. /**
  27625. * This flag can be used for type testing.
  27626. *
  27627. * @type {boolean}
  27628. * @readonly
  27629. * @default true
  27630. */
  27631. this.isScriptableValueNode = true;
  27632. }
  27633. /**
  27634. * Whether this node represents an output or not.
  27635. *
  27636. * @type {boolean}
  27637. * @readonly
  27638. * @default true
  27639. */
  27640. get isScriptableOutputNode() {
  27641. return this.outputType !== null;
  27642. }
  27643. set value( val ) {
  27644. if ( this._value === val ) return;
  27645. if ( this._cache && this.inputType === 'URL' && this.value.value instanceof ArrayBuffer ) {
  27646. URL.revokeObjectURL( this._cache );
  27647. this._cache = null;
  27648. }
  27649. this._value = val;
  27650. this.events.dispatchEvent( { type: 'change' } );
  27651. this.refresh();
  27652. }
  27653. /**
  27654. * The node's value.
  27655. *
  27656. * @type {any}
  27657. */
  27658. get value() {
  27659. return this._value;
  27660. }
  27661. /**
  27662. * Dispatches the `refresh` event.
  27663. */
  27664. refresh() {
  27665. this.events.dispatchEvent( { type: 'refresh' } );
  27666. }
  27667. /**
  27668. * The `value` property usually represents a node or even binary data in form of array buffers.
  27669. * In this case, this method tries to return the actual value behind the complex type.
  27670. *
  27671. * @return {any} The value.
  27672. */
  27673. getValue() {
  27674. const value = this.value;
  27675. if ( value && this._cache === null && this.inputType === 'URL' && value.value instanceof ArrayBuffer ) {
  27676. this._cache = URL.createObjectURL( new Blob( [ value.value ] ) );
  27677. } else if ( value && value.value !== null && value.value !== undefined && (
  27678. ( ( this.inputType === 'URL' || this.inputType === 'String' ) && typeof value.value === 'string' ) ||
  27679. ( this.inputType === 'Number' && typeof value.value === 'number' ) ||
  27680. ( this.inputType === 'Vector2' && value.value.isVector2 ) ||
  27681. ( this.inputType === 'Vector3' && value.value.isVector3 ) ||
  27682. ( this.inputType === 'Vector4' && value.value.isVector4 ) ||
  27683. ( this.inputType === 'Color' && value.value.isColor ) ||
  27684. ( this.inputType === 'Matrix3' && value.value.isMatrix3 ) ||
  27685. ( this.inputType === 'Matrix4' && value.value.isMatrix4 )
  27686. ) ) {
  27687. return value.value;
  27688. }
  27689. return this._cache || value;
  27690. }
  27691. /**
  27692. * Overwritten since the node type is inferred from the value.
  27693. *
  27694. * @param {NodeBuilder} builder - The current node builder.
  27695. * @return {string} The node type.
  27696. */
  27697. getNodeType( builder ) {
  27698. return this.value && this.value.isNode ? this.value.getNodeType( builder ) : 'float';
  27699. }
  27700. setup() {
  27701. return this.value && this.value.isNode ? this.value : float();
  27702. }
  27703. serialize( data ) {
  27704. super.serialize( data );
  27705. if ( this.value !== null ) {
  27706. if ( this.inputType === 'ArrayBuffer' ) {
  27707. data.value = arrayBufferToBase64( this.value );
  27708. } else {
  27709. data.value = this.value ? this.value.toJSON( data.meta ).uuid : null;
  27710. }
  27711. } else {
  27712. data.value = null;
  27713. }
  27714. data.inputType = this.inputType;
  27715. data.outputType = this.outputType;
  27716. }
  27717. deserialize( data ) {
  27718. super.deserialize( data );
  27719. let value = null;
  27720. if ( data.value !== null ) {
  27721. if ( data.inputType === 'ArrayBuffer' ) {
  27722. value = base64ToArrayBuffer( data.value );
  27723. } else if ( data.inputType === 'Texture' ) {
  27724. value = data.meta.textures[ data.value ];
  27725. } else {
  27726. value = data.meta.nodes[ data.value ] || null;
  27727. }
  27728. }
  27729. this.value = value;
  27730. this.inputType = data.inputType;
  27731. this.outputType = data.outputType;
  27732. }
  27733. }
  27734. /**
  27735. * TSL function for creating a scriptable value node.
  27736. *
  27737. * @tsl
  27738. * @function
  27739. * @param {any} [value] - The value.
  27740. * @returns {ScriptableValueNode}
  27741. */
  27742. const scriptableValue = /*@__PURE__*/ nodeProxy( ScriptableValueNode ).setParameterLength( 1 );
  27743. /**
  27744. * A Map-like data structure for managing resources of scriptable nodes.
  27745. *
  27746. * @augments Map
  27747. */
  27748. class Resources extends Map {
  27749. get( key, callback = null, ...params ) {
  27750. if ( this.has( key ) ) return super.get( key );
  27751. if ( callback !== null ) {
  27752. const value = callback( ...params );
  27753. this.set( key, value );
  27754. return value;
  27755. }
  27756. }
  27757. }
  27758. class Parameters {
  27759. constructor( scriptableNode ) {
  27760. this.scriptableNode = scriptableNode;
  27761. }
  27762. get parameters() {
  27763. return this.scriptableNode.parameters;
  27764. }
  27765. get layout() {
  27766. return this.scriptableNode.getLayout();
  27767. }
  27768. getInputLayout( id ) {
  27769. return this.scriptableNode.getInputLayout( id );
  27770. }
  27771. get( name ) {
  27772. const param = this.parameters[ name ];
  27773. const value = param ? param.getValue() : null;
  27774. return value;
  27775. }
  27776. }
  27777. /**
  27778. * Defines the resources (e.g. namespaces) of scriptable nodes.
  27779. *
  27780. * @type {Resources}
  27781. */
  27782. const ScriptableNodeResources = new Resources();
  27783. /**
  27784. * This type of node allows to implement nodes with custom scripts. The script
  27785. * section is represented as an instance of `CodeNode` written with JavaScript.
  27786. * The script itself must adhere to a specific structure.
  27787. *
  27788. * - main(): Executed once by default and every time `node.needsUpdate` is set.
  27789. * - layout: The layout object defines the script's interface (inputs and outputs).
  27790. *
  27791. * ```js
  27792. * ScriptableNodeResources.set( 'TSL', TSL );
  27793. *
  27794. * const scriptableNode = scriptable( js( `
  27795. * layout = {
  27796. * outputType: 'node',
  27797. * elements: [
  27798. * { name: 'source', inputType: 'node' },
  27799. * ]
  27800. * };
  27801. *
  27802. * const { mul, oscSine } = TSL;
  27803. *
  27804. * function main() {
  27805. * const source = parameters.get( 'source' ) || float();
  27806. * return mul( source, oscSine() ) );
  27807. * }
  27808. *
  27809. * ` ) );
  27810. *
  27811. * scriptableNode.setParameter( 'source', color( 1, 0, 0 ) );
  27812. *
  27813. * const material = new THREE.MeshBasicNodeMaterial();
  27814. * material.colorNode = scriptableNode;
  27815. * ```
  27816. *
  27817. * @augments Node
  27818. */
  27819. class ScriptableNode extends Node {
  27820. static get type() {
  27821. return 'ScriptableNode';
  27822. }
  27823. /**
  27824. * Constructs a new scriptable node.
  27825. *
  27826. * @param {?CodeNode} [codeNode=null] - The code node.
  27827. * @param {Object} [parameters={}] - The parameters definition.
  27828. */
  27829. constructor( codeNode = null, parameters = {} ) {
  27830. super();
  27831. /**
  27832. * The code node.
  27833. *
  27834. * @type {?CodeNode}
  27835. * @default null
  27836. */
  27837. this.codeNode = codeNode;
  27838. /**
  27839. * The parameters definition.
  27840. *
  27841. * @type {Object}
  27842. * @default {}
  27843. */
  27844. this.parameters = parameters;
  27845. this._local = new Resources();
  27846. this._output = scriptableValue( null );
  27847. this._outputs = {};
  27848. this._source = this.source;
  27849. this._method = null;
  27850. this._object = null;
  27851. this._value = null;
  27852. this._needsOutputUpdate = true;
  27853. this.onRefresh = this.onRefresh.bind( this );
  27854. /**
  27855. * This flag can be used for type testing.
  27856. *
  27857. * @type {boolean}
  27858. * @readonly
  27859. * @default true
  27860. */
  27861. this.isScriptableNode = true;
  27862. }
  27863. /**
  27864. * The source code of the scriptable node.
  27865. *
  27866. * @type {string}
  27867. */
  27868. get source() {
  27869. return this.codeNode ? this.codeNode.code : '';
  27870. }
  27871. /**
  27872. * Sets the reference of a local script variable.
  27873. *
  27874. * @param {string} name - The variable name.
  27875. * @param {Object} value - The reference to set.
  27876. * @return {Resources} The resource map
  27877. */
  27878. setLocal( name, value ) {
  27879. return this._local.set( name, value );
  27880. }
  27881. /**
  27882. * Gets the value of a local script variable.
  27883. *
  27884. * @param {string} name - The variable name.
  27885. * @return {Object} The value.
  27886. */
  27887. getLocal( name ) {
  27888. return this._local.get( name );
  27889. }
  27890. /**
  27891. * Event listener for the `refresh` event.
  27892. */
  27893. onRefresh() {
  27894. this._refresh();
  27895. }
  27896. /**
  27897. * Returns an input from the layout with the given id/name.
  27898. *
  27899. * @param {string} id - The id/name of the input.
  27900. * @return {Object} The element entry.
  27901. */
  27902. getInputLayout( id ) {
  27903. for ( const element of this.getLayout() ) {
  27904. if ( element.inputType && ( element.id === id || element.name === id ) ) {
  27905. return element;
  27906. }
  27907. }
  27908. }
  27909. /**
  27910. * Returns an output from the layout with the given id/name.
  27911. *
  27912. * @param {string} id - The id/name of the output.
  27913. * @return {Object} The element entry.
  27914. */
  27915. getOutputLayout( id ) {
  27916. for ( const element of this.getLayout() ) {
  27917. if ( element.outputType && ( element.id === id || element.name === id ) ) {
  27918. return element;
  27919. }
  27920. }
  27921. }
  27922. /**
  27923. * Defines a script output for the given name and value.
  27924. *
  27925. * @param {string} name - The name of the output.
  27926. * @param {Node} value - The node value.
  27927. * @return {ScriptableNode} A reference to this node.
  27928. */
  27929. setOutput( name, value ) {
  27930. const outputs = this._outputs;
  27931. if ( outputs[ name ] === undefined ) {
  27932. outputs[ name ] = scriptableValue( value );
  27933. } else {
  27934. outputs[ name ].value = value;
  27935. }
  27936. return this;
  27937. }
  27938. /**
  27939. * Returns a script output for the given name.
  27940. *
  27941. * @param {string} name - The name of the output.
  27942. * @return {ScriptableValueNode} The node value.
  27943. */
  27944. getOutput( name ) {
  27945. return this._outputs[ name ];
  27946. }
  27947. /**
  27948. * Returns a parameter for the given name
  27949. *
  27950. * @param {string} name - The name of the parameter.
  27951. * @return {ScriptableValueNode} The node value.
  27952. */
  27953. getParameter( name ) {
  27954. return this.parameters[ name ];
  27955. }
  27956. /**
  27957. * Sets a value for the given parameter name.
  27958. *
  27959. * @param {string} name - The parameter name.
  27960. * @param {any} value - The parameter value.
  27961. * @return {ScriptableNode} A reference to this node.
  27962. */
  27963. setParameter( name, value ) {
  27964. const parameters = this.parameters;
  27965. if ( value && value.isScriptableNode ) {
  27966. this.deleteParameter( name );
  27967. parameters[ name ] = value;
  27968. parameters[ name ].getDefaultOutput().events.addEventListener( 'refresh', this.onRefresh );
  27969. } else if ( value && value.isScriptableValueNode ) {
  27970. this.deleteParameter( name );
  27971. parameters[ name ] = value;
  27972. parameters[ name ].events.addEventListener( 'refresh', this.onRefresh );
  27973. } else if ( parameters[ name ] === undefined ) {
  27974. parameters[ name ] = scriptableValue( value );
  27975. parameters[ name ].events.addEventListener( 'refresh', this.onRefresh );
  27976. } else {
  27977. parameters[ name ].value = value;
  27978. }
  27979. return this;
  27980. }
  27981. /**
  27982. * Returns the value of this node which is the value of
  27983. * the default output.
  27984. *
  27985. * @return {Node} The value.
  27986. */
  27987. getValue() {
  27988. return this.getDefaultOutput().getValue();
  27989. }
  27990. /**
  27991. * Deletes a parameter from the script.
  27992. *
  27993. * @param {string} name - The parameter to remove.
  27994. * @return {ScriptableNode} A reference to this node.
  27995. */
  27996. deleteParameter( name ) {
  27997. let valueNode = this.parameters[ name ];
  27998. if ( valueNode ) {
  27999. if ( valueNode.isScriptableNode ) valueNode = valueNode.getDefaultOutput();
  28000. valueNode.events.removeEventListener( 'refresh', this.onRefresh );
  28001. }
  28002. return this;
  28003. }
  28004. /**
  28005. * Deletes all parameters from the script.
  28006. *
  28007. * @return {ScriptableNode} A reference to this node.
  28008. */
  28009. clearParameters() {
  28010. for ( const name of Object.keys( this.parameters ) ) {
  28011. this.deleteParameter( name );
  28012. }
  28013. this.needsUpdate = true;
  28014. return this;
  28015. }
  28016. /**
  28017. * Calls a function from the script.
  28018. *
  28019. * @param {string} name - The function name.
  28020. * @param {...any} params - A list of parameters.
  28021. * @return {any} The result of the function call.
  28022. */
  28023. call( name, ...params ) {
  28024. const object = this.getObject();
  28025. const method = object[ name ];
  28026. if ( typeof method === 'function' ) {
  28027. return method( ...params );
  28028. }
  28029. }
  28030. /**
  28031. * Asynchronously calls a function from the script.
  28032. *
  28033. * @param {string} name - The function name.
  28034. * @param {...any} params - A list of parameters.
  28035. * @return {Promise<any>} The result of the function call.
  28036. */
  28037. async callAsync( name, ...params ) {
  28038. const object = this.getObject();
  28039. const method = object[ name ];
  28040. if ( typeof method === 'function' ) {
  28041. return method.constructor.name === 'AsyncFunction' ? await method( ...params ) : method( ...params );
  28042. }
  28043. }
  28044. /**
  28045. * Overwritten since the node types is inferred from the script's output.
  28046. *
  28047. * @param {NodeBuilder} builder - The current node builder
  28048. * @return {string} The node type.
  28049. */
  28050. getNodeType( builder ) {
  28051. return this.getDefaultOutputNode().getNodeType( builder );
  28052. }
  28053. /**
  28054. * Refreshes the script node.
  28055. *
  28056. * @param {?string} [output=null] - An optional output.
  28057. */
  28058. refresh( output = null ) {
  28059. if ( output !== null ) {
  28060. this.getOutput( output ).refresh();
  28061. } else {
  28062. this._refresh();
  28063. }
  28064. }
  28065. /**
  28066. * Returns an object representation of the script.
  28067. *
  28068. * @return {Object} The result object.
  28069. */
  28070. getObject() {
  28071. if ( this.needsUpdate ) this.dispose();
  28072. if ( this._object !== null ) return this._object;
  28073. //
  28074. const refresh = () => this.refresh();
  28075. const setOutput = ( id, value ) => this.setOutput( id, value );
  28076. const parameters = new Parameters( this );
  28077. const THREE = ScriptableNodeResources.get( 'THREE' );
  28078. const TSL = ScriptableNodeResources.get( 'TSL' );
  28079. const method = this.getMethod();
  28080. const params = [ parameters, this._local, ScriptableNodeResources, refresh, setOutput, THREE, TSL ];
  28081. this._object = method( ...params );
  28082. const layout = this._object.layout;
  28083. if ( layout ) {
  28084. if ( layout.cache === false ) {
  28085. this._local.clear();
  28086. }
  28087. // default output
  28088. this._output.outputType = layout.outputType || null;
  28089. if ( Array.isArray( layout.elements ) ) {
  28090. for ( const element of layout.elements ) {
  28091. const id = element.id || element.name;
  28092. if ( element.inputType ) {
  28093. if ( this.getParameter( id ) === undefined ) this.setParameter( id, null );
  28094. this.getParameter( id ).inputType = element.inputType;
  28095. }
  28096. if ( element.outputType ) {
  28097. if ( this.getOutput( id ) === undefined ) this.setOutput( id, null );
  28098. this.getOutput( id ).outputType = element.outputType;
  28099. }
  28100. }
  28101. }
  28102. }
  28103. return this._object;
  28104. }
  28105. deserialize( data ) {
  28106. super.deserialize( data );
  28107. for ( const name in this.parameters ) {
  28108. let valueNode = this.parameters[ name ];
  28109. if ( valueNode.isScriptableNode ) valueNode = valueNode.getDefaultOutput();
  28110. valueNode.events.addEventListener( 'refresh', this.onRefresh );
  28111. }
  28112. }
  28113. /**
  28114. * Returns the layout of the script.
  28115. *
  28116. * @return {Object} The script's layout.
  28117. */
  28118. getLayout() {
  28119. return this.getObject().layout;
  28120. }
  28121. /**
  28122. * Returns default node output of the script.
  28123. *
  28124. * @return {Node} The default node output.
  28125. */
  28126. getDefaultOutputNode() {
  28127. const output = this.getDefaultOutput().value;
  28128. if ( output && output.isNode ) {
  28129. return output;
  28130. }
  28131. return float();
  28132. }
  28133. /**
  28134. * Returns default output of the script.
  28135. *
  28136. * @return {ScriptableValueNode} The default output.
  28137. */
  28138. getDefaultOutput() {
  28139. return this._exec()._output;
  28140. }
  28141. /**
  28142. * Returns a function created from the node's script.
  28143. *
  28144. * @return {Function} The function representing the node's code.
  28145. */
  28146. getMethod() {
  28147. if ( this.needsUpdate ) this.dispose();
  28148. if ( this._method !== null ) return this._method;
  28149. //
  28150. const parametersProps = [ 'parameters', 'local', 'global', 'refresh', 'setOutput', 'THREE', 'TSL' ];
  28151. const interfaceProps = [ 'layout', 'init', 'main', 'dispose' ];
  28152. const properties = interfaceProps.join( ', ' );
  28153. const declarations = 'var ' + properties + '; var output = {};\n';
  28154. const returns = '\nreturn { ...output, ' + properties + ' };';
  28155. const code = declarations + this.codeNode.code + returns;
  28156. //
  28157. this._method = new Function( ...parametersProps, code );
  28158. return this._method;
  28159. }
  28160. /**
  28161. * Frees all internal resources.
  28162. */
  28163. dispose() {
  28164. if ( this._method === null ) return;
  28165. if ( this._object && typeof this._object.dispose === 'function' ) {
  28166. this._object.dispose();
  28167. }
  28168. this._method = null;
  28169. this._object = null;
  28170. this._source = null;
  28171. this._value = null;
  28172. this._needsOutputUpdate = true;
  28173. this._output.value = null;
  28174. this._outputs = {};
  28175. }
  28176. setup() {
  28177. return this.getDefaultOutputNode();
  28178. }
  28179. getCacheKey( force ) {
  28180. const values = [ hashString( this.source ), this.getDefaultOutputNode().getCacheKey( force ) ];
  28181. for ( const param in this.parameters ) {
  28182. values.push( this.parameters[ param ].getCacheKey( force ) );
  28183. }
  28184. return hashArray( values );
  28185. }
  28186. set needsUpdate( value ) {
  28187. if ( value === true ) this.dispose();
  28188. }
  28189. get needsUpdate() {
  28190. return this.source !== this._source;
  28191. }
  28192. /**
  28193. * Executes the `main` function of the script.
  28194. *
  28195. * @private
  28196. * @return {ScriptableNode} A reference to this node.
  28197. */
  28198. _exec() {
  28199. if ( this.codeNode === null ) return this;
  28200. if ( this._needsOutputUpdate === true ) {
  28201. this._value = this.call( 'main' );
  28202. this._needsOutputUpdate = false;
  28203. }
  28204. this._output.value = this._value;
  28205. return this;
  28206. }
  28207. /**
  28208. * Executes the refresh.
  28209. *
  28210. * @private
  28211. */
  28212. _refresh() {
  28213. this.needsUpdate = true;
  28214. this._exec();
  28215. this._output.refresh();
  28216. }
  28217. }
  28218. /**
  28219. * TSL function for creating a scriptable node.
  28220. *
  28221. * @tsl
  28222. * @function
  28223. * @param {CodeNode} [codeNode] - The code node.
  28224. * @param {?Object} [parameters={}] - The parameters definition.
  28225. * @returns {ScriptableNode}
  28226. */
  28227. const scriptable = /*@__PURE__*/ nodeProxy( ScriptableNode ).setParameterLength( 1, 2 );
  28228. /**
  28229. * Returns a node that represents the `z` coordinate in view space
  28230. * for the current fragment. It's a different representation of the
  28231. * default depth value.
  28232. *
  28233. * This value can be part of a computation that defines how the fog
  28234. * density increases when moving away from the camera.
  28235. *
  28236. * @param {NodeBuilder} builder - The current node builder.
  28237. * @return {Node} The viewZ node.
  28238. */
  28239. function getViewZNode( builder ) {
  28240. let viewZ;
  28241. const getViewZ = builder.context.getViewZ;
  28242. if ( getViewZ !== undefined ) {
  28243. viewZ = getViewZ( this );
  28244. }
  28245. return ( viewZ || positionView.z ).negate();
  28246. }
  28247. /**
  28248. * Constructs a new range factor node.
  28249. *
  28250. * @tsl
  28251. * @function
  28252. * @param {Node} near - Defines the near value.
  28253. * @param {Node} far - Defines the far value.
  28254. */
  28255. const rangeFogFactor = Fn( ( [ near, far ], builder ) => {
  28256. const viewZ = getViewZNode( builder );
  28257. return smoothstep( near, far, viewZ );
  28258. } );
  28259. /**
  28260. * Represents an exponential squared fog. This type of fog gives
  28261. * a clear view near the camera and a faster than exponentially
  28262. * densening fog farther from the camera.
  28263. *
  28264. * @tsl
  28265. * @function
  28266. * @param {Node} density - Defines the fog density.
  28267. */
  28268. const densityFogFactor = Fn( ( [ density ], builder ) => {
  28269. const viewZ = getViewZNode( builder );
  28270. return density.mul( density, viewZ, viewZ ).negate().exp().oneMinus();
  28271. } );
  28272. /**
  28273. * This class can be used to configure a fog for the scene.
  28274. * Nodes of this type are assigned to `Scene.fogNode`.
  28275. *
  28276. * @tsl
  28277. * @function
  28278. * @param {Node} color - Defines the color of the fog.
  28279. * @param {Node} factor - Defines how the fog is factored in the scene.
  28280. */
  28281. const fog = Fn( ( [ color, factor ] ) => {
  28282. return vec4( factor.toFloat().mix( output.rgb, color.toVec3() ), output.a );
  28283. } );
  28284. // Deprecated
  28285. /**
  28286. * @tsl
  28287. * @function
  28288. * @deprecated since r171. Use `fog( color, rangeFogFactor( near, far ) )` instead.
  28289. *
  28290. * @param {Node} color
  28291. * @param {Node} near
  28292. * @param {Node} far
  28293. * @returns {Function}
  28294. */
  28295. function rangeFog( color, near, far ) { // @deprecated, r171
  28296. warn( 'TSL: "rangeFog( color, near, far )" is deprecated. Use "fog( color, rangeFogFactor( near, far ) )" instead.' );
  28297. return fog( color, rangeFogFactor( near, far ) );
  28298. }
  28299. /**
  28300. * @tsl
  28301. * @function
  28302. * @deprecated since r171. Use `fog( color, densityFogFactor( density ) )` instead.
  28303. *
  28304. * @param {Node} color
  28305. * @param {Node} density
  28306. * @returns {Function}
  28307. */
  28308. function densityFog( color, density ) { // @deprecated, r171
  28309. warn( 'TSL: "densityFog( color, density )" is deprecated. Use "fog( color, densityFogFactor( density ) )" instead.' );
  28310. return fog( color, densityFogFactor( density ) );
  28311. }
  28312. let min = null;
  28313. let max = null;
  28314. /**
  28315. * `RangeNode` generates random instanced attribute data in a defined range.
  28316. * An exemplary use case for this utility node is to generate random per-instance
  28317. * colors:
  28318. * ```js
  28319. * const material = new MeshBasicNodeMaterial();
  28320. * material.colorNode = range( new Color( 0x000000 ), new Color( 0xFFFFFF ) );
  28321. * const mesh = new InstancedMesh( geometry, material, count );
  28322. * ```
  28323. * @augments Node
  28324. */
  28325. class RangeNode extends Node {
  28326. static get type() {
  28327. return 'RangeNode';
  28328. }
  28329. /**
  28330. * Constructs a new range node.
  28331. *
  28332. * @param {Node<any>} [minNode=float()] - A node defining the lower bound of the range.
  28333. * @param {Node<any>} [maxNode=float()] - A node defining the upper bound of the range.
  28334. */
  28335. constructor( minNode = float(), maxNode = float() ) {
  28336. super();
  28337. /**
  28338. * A node defining the lower bound of the range.
  28339. *
  28340. * @type {Node<any>}
  28341. * @default float()
  28342. */
  28343. this.minNode = minNode;
  28344. /**
  28345. * A node defining the upper bound of the range.
  28346. *
  28347. * @type {Node<any>}
  28348. * @default float()
  28349. */
  28350. this.maxNode = maxNode;
  28351. }
  28352. /**
  28353. * Returns the vector length which is computed based on the range definition.
  28354. *
  28355. * @param {NodeBuilder} builder - The current node builder.
  28356. * @return {number} The vector length.
  28357. */
  28358. getVectorLength( builder ) {
  28359. const minNode = this.getConstNode( this.minNode );
  28360. const maxNode = this.getConstNode( this.maxNode );
  28361. const minLength = builder.getTypeLength( getValueType( minNode.value ) );
  28362. const maxLength = builder.getTypeLength( getValueType( maxNode.value ) );
  28363. return minLength > maxLength ? minLength : maxLength;
  28364. }
  28365. /**
  28366. * This method is overwritten since the node type is inferred from range definition.
  28367. *
  28368. * @param {NodeBuilder} builder - The current node builder.
  28369. * @return {string} The node type.
  28370. */
  28371. getNodeType( builder ) {
  28372. return builder.object.count > 1 ? builder.getTypeFromLength( this.getVectorLength( builder ) ) : 'float';
  28373. }
  28374. /**
  28375. * Returns a constant node from the given node by traversing it.
  28376. *
  28377. * @param {Node} node - The node to traverse.
  28378. * @returns {Node} The constant node, if found.
  28379. */
  28380. getConstNode( node ) {
  28381. let output = null;
  28382. node.traverse( n => {
  28383. if ( n.isConstNode === true ) {
  28384. output = n;
  28385. }
  28386. } );
  28387. if ( output === null ) {
  28388. throw new Error( 'THREE.TSL: No "ConstNode" found in node graph.' );
  28389. }
  28390. return output;
  28391. }
  28392. setup( builder ) {
  28393. const object = builder.object;
  28394. let output = null;
  28395. if ( object.count > 1 ) {
  28396. const minNode = this.getConstNode( this.minNode );
  28397. const maxNode = this.getConstNode( this.maxNode );
  28398. const minValue = minNode.value;
  28399. const maxValue = maxNode.value;
  28400. const minLength = builder.getTypeLength( getValueType( minValue ) );
  28401. const maxLength = builder.getTypeLength( getValueType( maxValue ) );
  28402. min = min || new Vector4();
  28403. max = max || new Vector4();
  28404. min.setScalar( 0 );
  28405. max.setScalar( 0 );
  28406. if ( minLength === 1 ) min.setScalar( minValue );
  28407. else if ( minValue.isColor ) min.set( minValue.r, minValue.g, minValue.b, 1 );
  28408. else min.set( minValue.x, minValue.y, minValue.z || 0, minValue.w || 0 );
  28409. if ( maxLength === 1 ) max.setScalar( maxValue );
  28410. else if ( maxValue.isColor ) max.set( maxValue.r, maxValue.g, maxValue.b, 1 );
  28411. else max.set( maxValue.x, maxValue.y, maxValue.z || 0, maxValue.w || 0 );
  28412. const stride = 4;
  28413. const length = stride * object.count;
  28414. const array = new Float32Array( length );
  28415. for ( let i = 0; i < length; i ++ ) {
  28416. const index = i % stride;
  28417. const minElementValue = min.getComponent( index );
  28418. const maxElementValue = max.getComponent( index );
  28419. array[ i ] = MathUtils.lerp( minElementValue, maxElementValue, Math.random() );
  28420. }
  28421. const nodeType = this.getNodeType( builder );
  28422. if ( object.count <= 4096 ) {
  28423. output = buffer( array, 'vec4', object.count ).element( instanceIndex ).convert( nodeType );
  28424. } else {
  28425. // TODO: Improve anonymous buffer attribute creation removing this part
  28426. const bufferAttribute = new InstancedBufferAttribute( array, 4 );
  28427. builder.geometry.setAttribute( '__range' + this.id, bufferAttribute );
  28428. output = instancedBufferAttribute( bufferAttribute ).convert( nodeType );
  28429. }
  28430. } else {
  28431. output = float( 0 );
  28432. }
  28433. return output;
  28434. }
  28435. }
  28436. /**
  28437. * TSL function for creating a range node.
  28438. *
  28439. * @tsl
  28440. * @function
  28441. * @param {Node<any>} [minNode=float()] - A node defining the lower bound of the range.
  28442. * @param {Node<any>} [maxNode=float()] - A node defining the upper bound of the range.
  28443. * @returns {RangeNode}
  28444. */
  28445. const range = /*@__PURE__*/ nodeProxy( RangeNode ).setParameterLength( 2 );
  28446. /**
  28447. * `ComputeBuiltinNode` represents a compute-scope builtin value that expose information
  28448. * about the currently running dispatch and/or the device it is running on.
  28449. *
  28450. * This node can only be used with a WebGPU backend.
  28451. *
  28452. * @augments Node
  28453. */
  28454. class ComputeBuiltinNode extends Node {
  28455. static get type() {
  28456. return 'ComputeBuiltinNode';
  28457. }
  28458. /**
  28459. * Constructs a new compute builtin node.
  28460. *
  28461. * @param {string} builtinName - The built-in name.
  28462. * @param {string} nodeType - The node type.
  28463. */
  28464. constructor( builtinName, nodeType ) {
  28465. super( nodeType );
  28466. /**
  28467. * The built-in name.
  28468. *
  28469. * @private
  28470. * @type {string}
  28471. */
  28472. this._builtinName = builtinName;
  28473. }
  28474. /**
  28475. * This method is overwritten since hash is derived from the built-in name.
  28476. *
  28477. * @param {NodeBuilder} builder - The current node builder.
  28478. * @return {string} The hash.
  28479. */
  28480. getHash( builder ) {
  28481. return this.getBuiltinName( builder );
  28482. }
  28483. /**
  28484. * This method is overwritten since the node type is simply derived from `nodeType`..
  28485. *
  28486. * @param {NodeBuilder} builder - The current node builder.
  28487. * @return {string} The node type.
  28488. */
  28489. getNodeType( /*builder*/ ) {
  28490. return this.nodeType;
  28491. }
  28492. /**
  28493. * Sets the builtin name.
  28494. *
  28495. * @param {string} builtinName - The built-in name.
  28496. * @return {ComputeBuiltinNode} A reference to this node.
  28497. */
  28498. setBuiltinName( builtinName ) {
  28499. this._builtinName = builtinName;
  28500. return this;
  28501. }
  28502. /**
  28503. * Returns the builtin name.
  28504. *
  28505. * @param {NodeBuilder} builder - The current node builder.
  28506. * @return {string} The builtin name.
  28507. */
  28508. getBuiltinName( /*builder*/ ) {
  28509. return this._builtinName;
  28510. }
  28511. /**
  28512. * Whether the current node builder has the builtin or not.
  28513. *
  28514. * @param {NodeBuilder} builder - The current node builder.
  28515. * @return {boolean} Whether the builder has the builtin or not.
  28516. */
  28517. hasBuiltin( builder ) {
  28518. return builder.hasBuiltin( this._builtinName );
  28519. }
  28520. generate( builder, output ) {
  28521. const builtinName = this.getBuiltinName( builder );
  28522. const nodeType = this.getNodeType( builder );
  28523. if ( builder.shaderStage === 'compute' ) {
  28524. return builder.format( builtinName, nodeType, output );
  28525. } else {
  28526. warn( `ComputeBuiltinNode: Compute built-in value ${builtinName} can not be accessed in the ${builder.shaderStage} stage` );
  28527. return builder.generateConst( nodeType );
  28528. }
  28529. }
  28530. serialize( data ) {
  28531. super.serialize( data );
  28532. data.global = this.global;
  28533. data._builtinName = this._builtinName;
  28534. }
  28535. deserialize( data ) {
  28536. super.deserialize( data );
  28537. this.global = data.global;
  28538. this._builtinName = data._builtinName;
  28539. }
  28540. }
  28541. /**
  28542. * TSL function for creating a compute builtin node.
  28543. *
  28544. * @tsl
  28545. * @function
  28546. * @param {string} name - The built-in name.
  28547. * @param {string} nodeType - The node type.
  28548. * @returns {ComputeBuiltinNode}
  28549. */
  28550. const computeBuiltin = ( name, nodeType ) => nodeObject( new ComputeBuiltinNode( name, nodeType ) );
  28551. /**
  28552. * Represents the number of workgroups dispatched by the compute shader.
  28553. * ```js
  28554. * // Run 512 invocations/threads with a workgroup size of 128.
  28555. * const computeFn = Fn(() => {
  28556. *
  28557. * // numWorkgroups.x = 4
  28558. * storageBuffer.element(0).assign(numWorkgroups.x)
  28559. *
  28560. * })().compute(512, [128]);
  28561. *
  28562. * // Run 512 invocations/threads with the default workgroup size of 64.
  28563. * const computeFn = Fn(() => {
  28564. *
  28565. * // numWorkgroups.x = 8
  28566. * storageBuffer.element(0).assign(numWorkgroups.x)
  28567. *
  28568. * })().compute(512);
  28569. * ```
  28570. *
  28571. * @tsl
  28572. * @type {ComputeBuiltinNode<uvec3>}
  28573. */
  28574. const numWorkgroups = /*@__PURE__*/ computeBuiltin( 'numWorkgroups', 'uvec3' );
  28575. /**
  28576. * Represents the 3-dimensional index of the workgroup the current compute invocation belongs to.
  28577. * ```js
  28578. * // Execute 12 compute threads with a workgroup size of 3.
  28579. * const computeFn = Fn( () => {
  28580. *
  28581. * If( workgroupId.x.mod( 2 ).equal( 0 ), () => {
  28582. *
  28583. * storageBuffer.element( instanceIndex ).assign( instanceIndex );
  28584. *
  28585. * } ).Else( () => {
  28586. *
  28587. * storageBuffer.element( instanceIndex ).assign( 0 );
  28588. *
  28589. * } );
  28590. *
  28591. * } )().compute( 12, [ 3 ] );
  28592. *
  28593. * // workgroupId.x = [0, 0, 0, 1, 1, 1, 2, 2, 2, 3, 3, 3];
  28594. * // Buffer Output = [0, 1, 2, 0, 0, 0, 6, 7, 8, 0, 0, 0];
  28595. * ```
  28596. *
  28597. * @tsl
  28598. * @type {ComputeBuiltinNode<uvec3>}
  28599. */
  28600. const workgroupId = /*@__PURE__*/ computeBuiltin( 'workgroupId', 'uvec3' );
  28601. /**
  28602. * A non-linearized 3-dimensional representation of the current invocation's position within a 3D global grid.
  28603. *
  28604. * @tsl
  28605. * @type {ComputeBuiltinNode<uvec3>}
  28606. */
  28607. const globalId = /*@__PURE__*/ computeBuiltin( 'globalId', 'uvec3' );
  28608. /**
  28609. * A non-linearized 3-dimensional representation of the current invocation's position within a 3D workgroup grid.
  28610. *
  28611. * @tsl
  28612. * @type {ComputeBuiltinNode<uvec3>}
  28613. */
  28614. const localId = /*@__PURE__*/ computeBuiltin( 'localId', 'uvec3' );
  28615. /**
  28616. * A device dependent variable that exposes the size of the current invocation's subgroup.
  28617. *
  28618. * @tsl
  28619. * @type {ComputeBuiltinNode<uint>}
  28620. */
  28621. const subgroupSize = /*@__PURE__*/ computeBuiltin( 'subgroupSize', 'uint' );
  28622. /**
  28623. * Represents a GPU control barrier that synchronizes compute operations within a given scope.
  28624. *
  28625. * This node can only be used with a WebGPU backend.
  28626. *
  28627. * @augments Node
  28628. */
  28629. class BarrierNode extends Node {
  28630. /**
  28631. * Constructs a new barrier node.
  28632. *
  28633. * @param {string} scope - The scope defines the behavior of the node.
  28634. */
  28635. constructor( scope ) {
  28636. super();
  28637. this.scope = scope;
  28638. }
  28639. generate( builder ) {
  28640. const { scope } = this;
  28641. const { renderer } = builder;
  28642. if ( renderer.backend.isWebGLBackend === true ) {
  28643. builder.addFlowCode( `\t// ${scope}Barrier \n` );
  28644. } else {
  28645. builder.addLineFlowCode( `${scope}Barrier()`, this );
  28646. }
  28647. }
  28648. }
  28649. /**
  28650. * TSL function for creating a barrier node.
  28651. *
  28652. * @tsl
  28653. * @function
  28654. * @param {string} scope - The scope defines the behavior of the node..
  28655. * @returns {BarrierNode}
  28656. */
  28657. const barrier = nodeProxy( BarrierNode );
  28658. /**
  28659. * TSL function for creating a workgroup barrier. All compute shader
  28660. * invocations must wait for each invocation within a workgroup to
  28661. * complete before the barrier can be surpassed.
  28662. *
  28663. * @tsl
  28664. * @function
  28665. * @returns {BarrierNode}
  28666. */
  28667. const workgroupBarrier = () => barrier( 'workgroup' ).toStack();
  28668. /**
  28669. * TSL function for creating a storage barrier. All invocations must
  28670. * wait for each access to variables within the 'storage' address space
  28671. * to complete before the barrier can be passed.
  28672. *
  28673. * @tsl
  28674. * @function
  28675. * @returns {BarrierNode}
  28676. */
  28677. const storageBarrier = () => barrier( 'storage' ).toStack();
  28678. /**
  28679. * TSL function for creating a texture barrier. All invocations must
  28680. * wait for each access to variables within the 'texture' address space
  28681. * to complete before the barrier can be passed.
  28682. *
  28683. * @tsl
  28684. * @function
  28685. * @returns {BarrierNode}
  28686. */
  28687. const textureBarrier = () => barrier( 'texture' ).toStack();
  28688. /**
  28689. * Represents an element of a 'workgroup' scoped buffer.
  28690. *
  28691. * @augments ArrayElementNode
  28692. */
  28693. class WorkgroupInfoElementNode extends ArrayElementNode {
  28694. /**
  28695. * Constructs a new workgroup info element node.
  28696. *
  28697. * @param {Node} workgroupInfoNode - The workgroup info node.
  28698. * @param {Node} indexNode - The index node that defines the element access.
  28699. */
  28700. constructor( workgroupInfoNode, indexNode ) {
  28701. super( workgroupInfoNode, indexNode );
  28702. /**
  28703. * This flag can be used for type testing.
  28704. *
  28705. * @type {boolean}
  28706. * @readonly
  28707. * @default true
  28708. */
  28709. this.isWorkgroupInfoElementNode = true;
  28710. }
  28711. generate( builder, output ) {
  28712. let snippet;
  28713. const isAssignContext = builder.context.assign;
  28714. snippet = super.generate( builder );
  28715. if ( isAssignContext !== true ) {
  28716. const type = this.getNodeType( builder );
  28717. snippet = builder.format( snippet, type, output );
  28718. }
  28719. // TODO: Possibly activate clip distance index on index access rather than from clipping context
  28720. return snippet;
  28721. }
  28722. }
  28723. /**
  28724. * A node allowing the user to create a 'workgroup' scoped buffer within the
  28725. * context of a compute shader. Typically, workgroup scoped buffers are
  28726. * created to hold data that is transferred from a global storage scope into
  28727. * a local workgroup scope. For invocations within a workgroup, data
  28728. * access speeds on 'workgroup' scoped buffers can be significantly faster
  28729. * than similar access operations on globally accessible storage buffers.
  28730. *
  28731. * This node can only be used with a WebGPU backend.
  28732. *
  28733. * @augments Node
  28734. */
  28735. class WorkgroupInfoNode extends Node {
  28736. /**
  28737. * Constructs a new buffer scoped to type scope.
  28738. *
  28739. * @param {string} scope - TODO.
  28740. * @param {string} bufferType - The data type of a 'workgroup' scoped buffer element.
  28741. * @param {number} [bufferCount=0] - The number of elements in the buffer.
  28742. */
  28743. constructor( scope, bufferType, bufferCount = 0 ) {
  28744. super( bufferType );
  28745. /**
  28746. * The buffer type.
  28747. *
  28748. * @type {string}
  28749. */
  28750. this.bufferType = bufferType;
  28751. /**
  28752. * The buffer count.
  28753. *
  28754. * @type {number}
  28755. * @default 0
  28756. */
  28757. this.bufferCount = bufferCount;
  28758. /**
  28759. * This flag can be used for type testing.
  28760. *
  28761. * @type {boolean}
  28762. * @readonly
  28763. * @default true
  28764. */
  28765. this.isWorkgroupInfoNode = true;
  28766. /**
  28767. * The data type of the array buffer.
  28768. *
  28769. * @type {string}
  28770. */
  28771. this.elementType = bufferType;
  28772. /**
  28773. * TODO.
  28774. *
  28775. * @type {string}
  28776. */
  28777. this.scope = scope;
  28778. /**
  28779. * The name of the workgroup scoped buffer.
  28780. *
  28781. * @type {string}
  28782. * @default ''
  28783. */
  28784. this.name = '';
  28785. }
  28786. /**
  28787. * Sets the name of this node.
  28788. *
  28789. * @param {string} name - The name to set.
  28790. * @return {WorkgroupInfoNode} A reference to this node.
  28791. */
  28792. setName( name ) {
  28793. this.name = name;
  28794. return this;
  28795. }
  28796. /**
  28797. * Sets the name/label of this node.
  28798. *
  28799. * @deprecated
  28800. * @param {string} name - The name to set.
  28801. * @return {WorkgroupInfoNode} A reference to this node.
  28802. */
  28803. label( name ) {
  28804. warn( 'TSL: "label()" has been deprecated. Use "setName()" instead.' ); // @deprecated r179
  28805. return this.setName( name );
  28806. }
  28807. /**
  28808. * Sets the scope of this node.
  28809. *
  28810. * @param {string} scope - The scope to set.
  28811. * @return {WorkgroupInfoNode} A reference to this node.
  28812. */
  28813. setScope( scope ) {
  28814. this.scope = scope;
  28815. return this;
  28816. }
  28817. /**
  28818. * The data type of the array buffer.
  28819. *
  28820. * @return {string} The element type.
  28821. */
  28822. getElementType() {
  28823. return this.elementType;
  28824. }
  28825. /**
  28826. * Overwrites the default implementation since the input type
  28827. * is inferred from the scope.
  28828. *
  28829. * @param {NodeBuilder} builder - The current node builder.
  28830. * @return {string} The input type.
  28831. */
  28832. getInputType( /*builder*/ ) {
  28833. return `${this.scope}Array`;
  28834. }
  28835. /**
  28836. * This method can be used to access elements via an index node.
  28837. *
  28838. * @param {IndexNode} indexNode - indexNode.
  28839. * @return {WorkgroupInfoElementNode} A reference to an element.
  28840. */
  28841. element( indexNode ) {
  28842. return nodeObject( new WorkgroupInfoElementNode( this, indexNode ) );
  28843. }
  28844. generate( builder ) {
  28845. const name = ( this.name !== '' ) ? this.name : `${this.scope}Array_${this.id}`;
  28846. return builder.getScopedArray( name, this.scope.toLowerCase(), this.bufferType, this.bufferCount );
  28847. }
  28848. }
  28849. /**
  28850. * TSL function for creating a workgroup info node.
  28851. * Creates a new 'workgroup' scoped array buffer.
  28852. *
  28853. * @tsl
  28854. * @function
  28855. * @param {string} type - The data type of a 'workgroup' scoped buffer element.
  28856. * @param {number} [count=0] - The number of elements in the buffer.
  28857. * @returns {WorkgroupInfoNode}
  28858. */
  28859. const workgroupArray = ( type, count ) => nodeObject( new WorkgroupInfoNode( 'Workgroup', type, count ) );
  28860. /**
  28861. * `AtomicFunctionNode` represents any function that can operate on atomic variable types
  28862. * within a shader. In an atomic function, any modification to an atomic variable will
  28863. * occur as an indivisible step with a defined order relative to other modifications.
  28864. * Accordingly, even if multiple atomic functions are modifying an atomic variable at once
  28865. * atomic operations will not interfere with each other.
  28866. *
  28867. * This node can only be used with a WebGPU backend.
  28868. *
  28869. * @augments Node
  28870. */
  28871. class AtomicFunctionNode extends Node {
  28872. static get type() {
  28873. return 'AtomicFunctionNode';
  28874. }
  28875. /**
  28876. * Constructs a new atomic function node.
  28877. *
  28878. * @param {string} method - The signature of the atomic function to construct.
  28879. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  28880. * @param {Node} valueNode - The value that mutates the atomic variable.
  28881. */
  28882. constructor( method, pointerNode, valueNode ) {
  28883. super( 'uint' );
  28884. /**
  28885. * The signature of the atomic function to construct.
  28886. *
  28887. * @type {string}
  28888. */
  28889. this.method = method;
  28890. /**
  28891. * An atomic variable or element of an atomic buffer.
  28892. *
  28893. * @type {Node}
  28894. */
  28895. this.pointerNode = pointerNode;
  28896. /**
  28897. * A value that modifies the atomic variable.
  28898. *
  28899. * @type {Node}
  28900. */
  28901. this.valueNode = valueNode;
  28902. /**
  28903. * Creates a list of the parents for this node for detecting if the node needs to return a value.
  28904. *
  28905. * @type {boolean}
  28906. * @default true
  28907. */
  28908. this.parents = true;
  28909. }
  28910. /**
  28911. * Overwrites the default implementation to return the type of
  28912. * the pointer node.
  28913. *
  28914. * @param {NodeBuilder} builder - The current node builder.
  28915. * @return {string} The input type.
  28916. */
  28917. getInputType( builder ) {
  28918. return this.pointerNode.getNodeType( builder );
  28919. }
  28920. /**
  28921. * Overwritten since the node type is inferred from the input type.
  28922. *
  28923. * @param {NodeBuilder} builder - The current node builder.
  28924. * @return {string} The node type.
  28925. */
  28926. getNodeType( builder ) {
  28927. return this.getInputType( builder );
  28928. }
  28929. generate( builder ) {
  28930. const properties = builder.getNodeProperties( this );
  28931. const parents = properties.parents;
  28932. const method = this.method;
  28933. const type = this.getNodeType( builder );
  28934. const inputType = this.getInputType( builder );
  28935. const a = this.pointerNode;
  28936. const b = this.valueNode;
  28937. const params = [];
  28938. params.push( `&${ a.build( builder, inputType ) }` );
  28939. if ( b !== null ) {
  28940. params.push( b.build( builder, inputType ) );
  28941. }
  28942. const methodSnippet = `${ builder.getMethod( method, type ) }( ${ params.join( ', ' ) } )`;
  28943. const isVoid = parents ? ( parents.length === 1 && parents[ 0 ].isStackNode === true ) : false;
  28944. if ( isVoid ) {
  28945. builder.addLineFlowCode( methodSnippet, this );
  28946. } else {
  28947. if ( properties.constNode === undefined ) {
  28948. properties.constNode = expression( methodSnippet, type ).toConst();
  28949. }
  28950. return properties.constNode.build( builder );
  28951. }
  28952. }
  28953. }
  28954. AtomicFunctionNode.ATOMIC_LOAD = 'atomicLoad';
  28955. AtomicFunctionNode.ATOMIC_STORE = 'atomicStore';
  28956. AtomicFunctionNode.ATOMIC_ADD = 'atomicAdd';
  28957. AtomicFunctionNode.ATOMIC_SUB = 'atomicSub';
  28958. AtomicFunctionNode.ATOMIC_MAX = 'atomicMax';
  28959. AtomicFunctionNode.ATOMIC_MIN = 'atomicMin';
  28960. AtomicFunctionNode.ATOMIC_AND = 'atomicAnd';
  28961. AtomicFunctionNode.ATOMIC_OR = 'atomicOr';
  28962. AtomicFunctionNode.ATOMIC_XOR = 'atomicXor';
  28963. /**
  28964. * TSL function for creating an atomic function node.
  28965. *
  28966. * @tsl
  28967. * @function
  28968. * @param {string} method - The signature of the atomic function to construct.
  28969. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  28970. * @param {Node} valueNode - The value that mutates the atomic variable.
  28971. * @returns {AtomicFunctionNode}
  28972. */
  28973. const atomicNode = nodeProxy( AtomicFunctionNode );
  28974. /**
  28975. * TSL function for appending an atomic function call into the programmatic flow of a compute shader.
  28976. *
  28977. * @tsl
  28978. * @function
  28979. * @param {string} method - The signature of the atomic function to construct.
  28980. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  28981. * @param {Node} valueNode - The value that mutates the atomic variable.
  28982. * @returns {AtomicFunctionNode}
  28983. */
  28984. const atomicFunc = ( method, pointerNode, valueNode ) => {
  28985. return atomicNode( method, pointerNode, valueNode ).toStack();
  28986. };
  28987. /**
  28988. * Loads the value stored in the atomic variable.
  28989. *
  28990. * @tsl
  28991. * @function
  28992. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  28993. * @returns {AtomicFunctionNode}
  28994. */
  28995. const atomicLoad = ( pointerNode ) => atomicFunc( AtomicFunctionNode.ATOMIC_LOAD, pointerNode, null );
  28996. /**
  28997. * Stores a value in the atomic variable.
  28998. *
  28999. * @tsl
  29000. * @function
  29001. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  29002. * @param {Node} valueNode - The value that mutates the atomic variable.
  29003. * @returns {AtomicFunctionNode}
  29004. */
  29005. const atomicStore = ( pointerNode, valueNode ) => atomicFunc( AtomicFunctionNode.ATOMIC_STORE, pointerNode, valueNode );
  29006. /**
  29007. * Increments the value stored in the atomic variable.
  29008. *
  29009. * @tsl
  29010. * @function
  29011. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  29012. * @param {Node} valueNode - The value that mutates the atomic variable.
  29013. * @returns {AtomicFunctionNode}
  29014. */
  29015. const atomicAdd = ( pointerNode, valueNode ) => atomicFunc( AtomicFunctionNode.ATOMIC_ADD, pointerNode, valueNode );
  29016. /**
  29017. * Decrements the value stored in the atomic variable.
  29018. *
  29019. * @tsl
  29020. * @function
  29021. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  29022. * @param {Node} valueNode - The value that mutates the atomic variable.
  29023. * @returns {AtomicFunctionNode}
  29024. */
  29025. const atomicSub = ( pointerNode, valueNode ) => atomicFunc( AtomicFunctionNode.ATOMIC_SUB, pointerNode, valueNode );
  29026. /**
  29027. * Stores in an atomic variable the maximum between its current value and a parameter.
  29028. *
  29029. * @tsl
  29030. * @function
  29031. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  29032. * @param {Node} valueNode - The value that mutates the atomic variable.
  29033. * @returns {AtomicFunctionNode}
  29034. */
  29035. const atomicMax = ( pointerNode, valueNode ) => atomicFunc( AtomicFunctionNode.ATOMIC_MAX, pointerNode, valueNode );
  29036. /**
  29037. * Stores in an atomic variable the minimum between its current value and a parameter.
  29038. *
  29039. * @tsl
  29040. * @function
  29041. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  29042. * @param {Node} valueNode - The value that mutates the atomic variable.
  29043. * @returns {AtomicFunctionNode}
  29044. */
  29045. const atomicMin = ( pointerNode, valueNode ) => atomicFunc( AtomicFunctionNode.ATOMIC_MIN, pointerNode, valueNode );
  29046. /**
  29047. * Stores in an atomic variable the bitwise AND of its value with a parameter.
  29048. *
  29049. * @tsl
  29050. * @function
  29051. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  29052. * @param {Node} valueNode - The value that mutates the atomic variable.
  29053. * @returns {AtomicFunctionNode}
  29054. */
  29055. const atomicAnd = ( pointerNode, valueNode ) => atomicFunc( AtomicFunctionNode.ATOMIC_AND, pointerNode, valueNode );
  29056. /**
  29057. * Stores in an atomic variable the bitwise OR of its value with a parameter.
  29058. *
  29059. * @tsl
  29060. * @function
  29061. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  29062. * @param {Node} valueNode - The value that mutates the atomic variable.
  29063. * @returns {AtomicFunctionNode}
  29064. */
  29065. const atomicOr = ( pointerNode, valueNode ) => atomicFunc( AtomicFunctionNode.ATOMIC_OR, pointerNode, valueNode );
  29066. /**
  29067. * Stores in an atomic variable the bitwise XOR of its value with a parameter.
  29068. *
  29069. * @tsl
  29070. * @function
  29071. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  29072. * @param {Node} valueNode - The value that mutates the atomic variable.
  29073. * @returns {AtomicFunctionNode}
  29074. */
  29075. const atomicXor = ( pointerNode, valueNode ) => atomicFunc( AtomicFunctionNode.ATOMIC_XOR, pointerNode, valueNode );
  29076. /**
  29077. * This class represents a set of built in WGSL shader functions that sync
  29078. * synchronously execute an operation across a subgroup, or 'warp', of compute
  29079. * or fragment shader invocations within a workgroup. Typically, these functions
  29080. * will synchronously execute an operation using data from all active invocations
  29081. * within the subgroup, then broadcast that result to all active invocations. In
  29082. * other graphics APIs, subgroup functions are also referred to as wave intrinsics
  29083. * (DirectX/HLSL) or warp intrinsics (CUDA).
  29084. *
  29085. * @augments TempNode
  29086. */
  29087. class SubgroupFunctionNode extends TempNode {
  29088. static get type() {
  29089. return 'SubgroupFunctionNode';
  29090. }
  29091. /**
  29092. * Constructs a new function node.
  29093. *
  29094. * @param {string} method - The subgroup/wave intrinsic method to construct.
  29095. * @param {Node} [aNode=null] - The method's first argument.
  29096. * @param {Node} [bNode=null] - The method's second argument.
  29097. */
  29098. constructor( method, aNode = null, bNode = null ) {
  29099. super();
  29100. /**
  29101. * The subgroup/wave intrinsic method to construct.
  29102. *
  29103. * @type {String}
  29104. */
  29105. this.method = method;
  29106. /**
  29107. * The method's first argument.
  29108. *
  29109. * @type {Node}
  29110. */
  29111. this.aNode = aNode;
  29112. /**
  29113. * The method's second argument.
  29114. *
  29115. * @type {Node}
  29116. */
  29117. this.bNode = bNode;
  29118. }
  29119. getInputType( builder ) {
  29120. const aType = this.aNode ? this.aNode.getNodeType( builder ) : null;
  29121. const bType = this.bNode ? this.bNode.getNodeType( builder ) : null;
  29122. const aLen = builder.isMatrix( aType ) ? 0 : builder.getTypeLength( aType );
  29123. const bLen = builder.isMatrix( bType ) ? 0 : builder.getTypeLength( bType );
  29124. if ( aLen > bLen ) {
  29125. return aType;
  29126. } else {
  29127. return bType;
  29128. }
  29129. }
  29130. getNodeType( builder ) {
  29131. const method = this.method;
  29132. if ( method === SubgroupFunctionNode.SUBGROUP_ELECT ) {
  29133. return 'bool';
  29134. } else if ( method === SubgroupFunctionNode.SUBGROUP_BALLOT ) {
  29135. return 'uvec4';
  29136. } else {
  29137. return this.getInputType( builder );
  29138. }
  29139. }
  29140. generate( builder, output ) {
  29141. const method = this.method;
  29142. const type = this.getNodeType( builder );
  29143. const inputType = this.getInputType( builder );
  29144. const a = this.aNode;
  29145. const b = this.bNode;
  29146. const params = [];
  29147. if (
  29148. method === SubgroupFunctionNode.SUBGROUP_BROADCAST ||
  29149. method === SubgroupFunctionNode.SUBGROUP_SHUFFLE ||
  29150. method === SubgroupFunctionNode.QUAD_BROADCAST
  29151. ) {
  29152. const bType = b.getNodeType( builder );
  29153. params.push(
  29154. a.build( builder, type ),
  29155. b.build( builder, bType === 'float' ? 'int' : type )
  29156. );
  29157. } else if (
  29158. method === SubgroupFunctionNode.SUBGROUP_SHUFFLE_XOR ||
  29159. method === SubgroupFunctionNode.SUBGROUP_SHUFFLE_DOWN ||
  29160. method === SubgroupFunctionNode.SUBGROUP_SHUFFLE_UP
  29161. ) {
  29162. params.push(
  29163. a.build( builder, type ),
  29164. b.build( builder, 'uint' )
  29165. );
  29166. } else {
  29167. if ( a !== null ) params.push( a.build( builder, inputType ) );
  29168. if ( b !== null ) params.push( b.build( builder, inputType ) );
  29169. }
  29170. const paramsString = params.length === 0 ? '()' : `( ${params.join( ', ' )} )`;
  29171. return builder.format( `${ builder.getMethod( method, type ) }${paramsString}`, type, output );
  29172. }
  29173. serialize( data ) {
  29174. super.serialize( data );
  29175. data.method = this.method;
  29176. }
  29177. deserialize( data ) {
  29178. super.deserialize( data );
  29179. this.method = data.method;
  29180. }
  29181. }
  29182. // 0 inputs
  29183. SubgroupFunctionNode.SUBGROUP_ELECT = 'subgroupElect';
  29184. // 1 input
  29185. SubgroupFunctionNode.SUBGROUP_BALLOT = 'subgroupBallot';
  29186. SubgroupFunctionNode.SUBGROUP_ADD = 'subgroupAdd';
  29187. SubgroupFunctionNode.SUBGROUP_INCLUSIVE_ADD = 'subgroupInclusiveAdd';
  29188. SubgroupFunctionNode.SUBGROUP_EXCLUSIVE_AND = 'subgroupExclusiveAdd';
  29189. SubgroupFunctionNode.SUBGROUP_MUL = 'subgroupMul';
  29190. SubgroupFunctionNode.SUBGROUP_INCLUSIVE_MUL = 'subgroupInclusiveMul';
  29191. SubgroupFunctionNode.SUBGROUP_EXCLUSIVE_MUL = 'subgroupExclusiveMul';
  29192. SubgroupFunctionNode.SUBGROUP_AND = 'subgroupAnd';
  29193. SubgroupFunctionNode.SUBGROUP_OR = 'subgroupOr';
  29194. SubgroupFunctionNode.SUBGROUP_XOR = 'subgroupXor';
  29195. SubgroupFunctionNode.SUBGROUP_MIN = 'subgroupMin';
  29196. SubgroupFunctionNode.SUBGROUP_MAX = 'subgroupMax';
  29197. SubgroupFunctionNode.SUBGROUP_ALL = 'subgroupAll';
  29198. SubgroupFunctionNode.SUBGROUP_ANY = 'subgroupAny';
  29199. SubgroupFunctionNode.SUBGROUP_BROADCAST_FIRST = 'subgroupBroadcastFirst';
  29200. SubgroupFunctionNode.QUAD_SWAP_X = 'quadSwapX';
  29201. SubgroupFunctionNode.QUAD_SWAP_Y = 'quadSwapY';
  29202. SubgroupFunctionNode.QUAD_SWAP_DIAGONAL = 'quadSwapDiagonal';
  29203. // 2 inputs
  29204. SubgroupFunctionNode.SUBGROUP_BROADCAST = 'subgroupBroadcast';
  29205. SubgroupFunctionNode.SUBGROUP_SHUFFLE = 'subgroupShuffle';
  29206. SubgroupFunctionNode.SUBGROUP_SHUFFLE_XOR = 'subgroupShuffleXor';
  29207. SubgroupFunctionNode.SUBGROUP_SHUFFLE_UP = 'subgroupShuffleUp';
  29208. SubgroupFunctionNode.SUBGROUP_SHUFFLE_DOWN = 'subgroupShuffleDown';
  29209. SubgroupFunctionNode.QUAD_BROADCAST = 'quadBroadcast';
  29210. /**
  29211. * Returns true if this invocation has the lowest subgroup_invocation_id
  29212. * among active invocations in the subgroup.
  29213. *
  29214. * @tsl
  29215. * @method
  29216. * @return {bool} The result of the computation.
  29217. */
  29218. const subgroupElect = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_ELECT ).setParameterLength( 0 );
  29219. /**
  29220. * Returns a set of bitfields where the bit corresponding to subgroup_invocation_id
  29221. * is 1 if pred is true for that active invocation and 0 otherwise.
  29222. *
  29223. * @tsl
  29224. * @method
  29225. * @param {bool} pred - A boolean that sets the bit corresponding to the invocations subgroup invocation id.
  29226. * @return {vec4<u32>}- A bitfield corresponding to the pred value of each subgroup invocation.
  29227. */
  29228. const subgroupBallot = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_BALLOT ).setParameterLength( 1 );
  29229. /**
  29230. * A reduction that adds e among all active invocations and returns that result.
  29231. *
  29232. * @tsl
  29233. * @method
  29234. * @param {number} e - The value provided to the reduction by the current invocation.
  29235. * @return {number} The accumulated result of the reduction operation.
  29236. */
  29237. const subgroupAdd = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_ADD ).setParameterLength( 1 );
  29238. /**
  29239. * An inclusive scan returning the sum of e for all active invocations with subgroup_invocation_id less than or equal to this invocation.
  29240. *
  29241. * @tsl
  29242. * @method
  29243. * @param {number} e - The value provided to the inclusive scan by the current invocation.
  29244. * @return {number} The accumulated result of the inclusive scan operation.
  29245. */
  29246. const subgroupInclusiveAdd = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_INCLUSIVE_ADD ).setParameterLength( 1 );
  29247. /**
  29248. * An exclusive scan that returns the sum of e for all active invocations with subgroup_invocation_id less than this invocation.
  29249. *
  29250. * @tsl
  29251. * @method
  29252. * @param {number} e - The value provided to the exclusive scan by the current invocation.
  29253. * @return {number} The accumulated result of the exclusive scan operation.
  29254. */
  29255. const subgroupExclusiveAdd = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_EXCLUSIVE_AND ).setParameterLength( 1 );
  29256. /**
  29257. * A reduction that multiplies e among all active invocations and returns that result.
  29258. *
  29259. * @tsl
  29260. * @method
  29261. * @param {number} e - The value provided to the reduction by the current invocation.
  29262. * @return {number} The accumulated result of the reduction operation.
  29263. */
  29264. const subgroupMul = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_MUL ).setParameterLength( 1 );
  29265. /**
  29266. * An inclusive scan returning the product of e for all active invocations with subgroup_invocation_id less than or equal to this invocation.
  29267. *
  29268. * @tsl
  29269. * @method
  29270. * @param {number} e - The value provided to the inclusive scan by the current invocation.
  29271. * @return {number} The accumulated result of the inclusive scan operation.
  29272. */
  29273. const subgroupInclusiveMul = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_INCLUSIVE_MUL ).setParameterLength( 1 );
  29274. /**
  29275. * An exclusive scan that returns the product of e for all active invocations with subgroup_invocation_id less than this invocation.
  29276. *
  29277. * @tsl
  29278. * @method
  29279. * @param {number} e - The value provided to the exclusive scan by the current invocation.
  29280. * @return {number} The accumulated result of the exclusive scan operation.
  29281. */
  29282. const subgroupExclusiveMul = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_EXCLUSIVE_MUL ).setParameterLength( 1 );
  29283. /**
  29284. * A reduction that performs a bitwise and of e among all active invocations and returns that result.
  29285. *
  29286. * @tsl
  29287. * @method
  29288. * @param {number} e - The value provided to the reduction by the current invocation.
  29289. * @return {number} The result of the reduction operation.
  29290. */
  29291. const subgroupAnd = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_AND ).setParameterLength( 1 );
  29292. /**
  29293. * A reduction that performs a bitwise or of e among all active invocations and returns that result.
  29294. *
  29295. * @tsl
  29296. * @method
  29297. * @param {number} e - The value provided to the reduction by the current invocation.
  29298. * @return {number} The result of the reduction operation.
  29299. */
  29300. const subgroupOr = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_OR ).setParameterLength( 1 );
  29301. /**
  29302. * A reduction that performs a bitwise xor of e among all active invocations and returns that result.
  29303. *
  29304. * @tsl
  29305. * @method
  29306. * @param {number} e - The value provided to the reduction by the current invocation.
  29307. * @return {number} The result of the reduction operation.
  29308. */
  29309. const subgroupXor = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_XOR ).setParameterLength( 1 );
  29310. /**
  29311. * A reduction that performs a min of e among all active invocations and returns that result.
  29312. *
  29313. * @tsl
  29314. * @method
  29315. * @param {number} e - The value provided to the reduction by the current invocation.
  29316. * @return {number} The result of the reduction operation.
  29317. */
  29318. const subgroupMin = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_MIN ).setParameterLength( 1 );
  29319. /**
  29320. * A reduction that performs a max of e among all active invocations and returns that result.
  29321. *
  29322. * @tsl
  29323. * @method
  29324. * @param {number} e - The value provided to the reduction by the current invocation.
  29325. * @return {number} The result of the reduction operation.
  29326. */
  29327. const subgroupMax = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_MAX ).setParameterLength( 1 );
  29328. /**
  29329. * Returns true if e is true for all active invocations in the subgroup.
  29330. *
  29331. * @tsl
  29332. * @method
  29333. * @return {bool} The result of the computation.
  29334. */
  29335. const subgroupAll = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_ALL ).setParameterLength( 0 );
  29336. /**
  29337. * Returns true if e is true for any active invocation in the subgroup
  29338. *
  29339. * @tsl
  29340. * @method
  29341. * @return {bool} The result of the computation.
  29342. */
  29343. const subgroupAny = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_ANY ).setParameterLength( 0 );
  29344. /**
  29345. * Broadcasts e from the active invocation with the lowest subgroup_invocation_id in the subgroup to all other active invocations.
  29346. *
  29347. * @tsl
  29348. * @method
  29349. * @param {number} e - The value to broadcast from the lowest subgroup invocation.
  29350. * @param {number} id - The subgroup invocation to broadcast from.
  29351. * @return {number} The broadcast value.
  29352. */
  29353. const subgroupBroadcastFirst = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_BROADCAST_FIRST ).setParameterLength( 2 );
  29354. /**
  29355. * Swaps e between invocations in the quad in the X direction.
  29356. *
  29357. * @tsl
  29358. * @method
  29359. * @param {number} e - The value to swap from the current invocation.
  29360. * @return {number} The value received from the swap operation.
  29361. */
  29362. const quadSwapX = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.QUAD_SWAP_X ).setParameterLength( 1 );
  29363. /**
  29364. * Swaps e between invocations in the quad in the Y direction.
  29365. *
  29366. * @tsl
  29367. * @method
  29368. * @param {number} e - The value to swap from the current invocation.
  29369. * @return {number} The value received from the swap operation.
  29370. */
  29371. const quadSwapY = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.QUAD_SWAP_Y ).setParameterLength( 1 );
  29372. /**
  29373. * Swaps e between invocations in the quad diagonally.
  29374. *
  29375. * @tsl
  29376. * @method
  29377. * @param {number} e - The value to swap from the current invocation.
  29378. * @return {number} The value received from the swap operation.
  29379. */
  29380. const quadSwapDiagonal = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.QUAD_SWAP_DIAGONAL ).setParameterLength( 1 );
  29381. /**
  29382. * Broadcasts e from the invocation whose subgroup_invocation_id matches id, to all active invocations.
  29383. *
  29384. * @tsl
  29385. * @method
  29386. * @param {number} e - The value to broadcast from subgroup invocation 'id'.
  29387. * @param {number} id - The subgroup invocation to broadcast from.
  29388. * @return {number} The broadcast value.
  29389. */
  29390. const subgroupBroadcast = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_BROADCAST ).setParameterLength( 2 );
  29391. /**
  29392. * Returns v from the active invocation whose subgroup_invocation_id matches id
  29393. *
  29394. * @tsl
  29395. * @method
  29396. * @param {number} v - The value to return from subgroup invocation id^mask.
  29397. * @param {number} id - The subgroup invocation which returns the value v.
  29398. * @return {number} The broadcast value.
  29399. */
  29400. const subgroupShuffle = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_SHUFFLE ).setParameterLength( 2 );
  29401. /**
  29402. * Returns v from the active invocation whose subgroup_invocation_id matches subgroup_invocation_id ^ mask.
  29403. *
  29404. * @tsl
  29405. * @method
  29406. * @param {number} v - The value to return from subgroup invocation id^mask.
  29407. * @param {number} mask - A bitmask that determines the target invocation via a XOR operation.
  29408. * @return {number} The broadcast value.
  29409. */
  29410. const subgroupShuffleXor = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_SHUFFLE_XOR ).setParameterLength( 2 );
  29411. /**
  29412. * Returns v from the active invocation whose subgroup_invocation_id matches subgroup_invocation_id - delta
  29413. *
  29414. * @tsl
  29415. * @method
  29416. * @param {number} v - The value to return from subgroup invocation id^mask.
  29417. * @param {number} delta - A value that offsets the current in.
  29418. * @return {number} The broadcast value.
  29419. */
  29420. const subgroupShuffleUp = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_SHUFFLE_UP ).setParameterLength( 2 );
  29421. /**
  29422. * Returns v from the active invocation whose subgroup_invocation_id matches subgroup_invocation_id + delta
  29423. *
  29424. * @tsl
  29425. * @method
  29426. * @param {number} v - The value to return from subgroup invocation id^mask.
  29427. * @param {number} delta - A value that offsets the current subgroup invocation.
  29428. * @return {number} The broadcast value.
  29429. */
  29430. const subgroupShuffleDown = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_SHUFFLE_DOWN ).setParameterLength( 2 );
  29431. /**
  29432. * Broadcasts e from the quad invocation with id equal to id.
  29433. *
  29434. * @tsl
  29435. * @method
  29436. * @param {number} e - The value to broadcast.
  29437. * @return {number} The broadcast value.
  29438. */
  29439. const quadBroadcast = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.QUAD_BROADCAST ).setParameterLength( 1 );
  29440. let uniformsLib;
  29441. function getLightData( light ) {
  29442. uniformsLib = uniformsLib || new WeakMap();
  29443. let uniforms = uniformsLib.get( light );
  29444. if ( uniforms === undefined ) uniformsLib.set( light, uniforms = {} );
  29445. return uniforms;
  29446. }
  29447. /**
  29448. * TSL function for getting a shadow matrix uniform node for the given light.
  29449. *
  29450. * @tsl
  29451. * @function
  29452. * @param {Light} light -The light source.
  29453. * @returns {UniformNode<mat4>} The shadow matrix uniform node.
  29454. */
  29455. function lightShadowMatrix( light ) {
  29456. const data = getLightData( light );
  29457. return data.shadowMatrix || ( data.shadowMatrix = uniform( 'mat4' ).setGroup( renderGroup ).onRenderUpdate( ( frame ) => {
  29458. // normally, shadow matrices are updated in ShadowNode. However, if the shadow matrix is used outside
  29459. // of shadow rendering (like in ProjectorLightNode), the shadow matrix still requires an update
  29460. if ( light.castShadow !== true || frame.renderer.shadowMap.enabled === false ) {
  29461. if ( light.shadow.camera.coordinateSystem !== frame.camera.coordinateSystem ) {
  29462. light.shadow.camera.coordinateSystem = frame.camera.coordinateSystem;
  29463. light.shadow.camera.updateProjectionMatrix();
  29464. }
  29465. light.shadow.updateMatrices( light );
  29466. }
  29467. return light.shadow.matrix;
  29468. } ) );
  29469. }
  29470. /**
  29471. * TSL function for getting projected uv coordinates for the given light.
  29472. * Relevant when using maps with spot lights.
  29473. *
  29474. * @tsl
  29475. * @function
  29476. * @param {Light} light -The light source.
  29477. * @param {Node<vec3>} [position=positionWorld] -The position to project.
  29478. * @returns {Node<vec3>} The projected uvs.
  29479. */
  29480. function lightProjectionUV( light, position = positionWorld ) {
  29481. const spotLightCoord = lightShadowMatrix( light ).mul( position );
  29482. const projectionUV = spotLightCoord.xyz.div( spotLightCoord.w );
  29483. return projectionUV;
  29484. }
  29485. /**
  29486. * TSL function for getting the position in world space for the given light.
  29487. *
  29488. * @tsl
  29489. * @function
  29490. * @param {Light} light -The light source.
  29491. * @returns {UniformNode<vec3>} The light's position in world space.
  29492. */
  29493. function lightPosition( light ) {
  29494. const data = getLightData( light );
  29495. return data.position || ( data.position = uniform( new Vector3() ).setGroup( renderGroup ).onRenderUpdate( ( _, self ) => self.value.setFromMatrixPosition( light.matrixWorld ) ) );
  29496. }
  29497. /**
  29498. * TSL function for getting the light target position in world space for the given light.
  29499. *
  29500. * @tsl
  29501. * @function
  29502. * @param {Light} light -The light source.
  29503. * @returns {UniformNode<vec3>} The light target position in world space.
  29504. */
  29505. function lightTargetPosition( light ) {
  29506. const data = getLightData( light );
  29507. return data.targetPosition || ( data.targetPosition = uniform( new Vector3() ).setGroup( renderGroup ).onRenderUpdate( ( _, self ) => self.value.setFromMatrixPosition( light.target.matrixWorld ) ) );
  29508. }
  29509. /**
  29510. * TSL function for getting the position in view space for the given light.
  29511. *
  29512. * @tsl
  29513. * @function
  29514. * @param {Light} light - The light source.
  29515. * @returns {UniformNode<vec3>} The light's position in view space.
  29516. */
  29517. function lightViewPosition( light ) {
  29518. const data = getLightData( light );
  29519. return data.viewPosition || ( data.viewPosition = uniform( new Vector3() ).setGroup( renderGroup ).onRenderUpdate( ( { camera }, self ) => {
  29520. self.value = self.value || new Vector3();
  29521. self.value.setFromMatrixPosition( light.matrixWorld );
  29522. self.value.applyMatrix4( camera.matrixWorldInverse );
  29523. } ) );
  29524. }
  29525. /**
  29526. * TSL function for getting the light target direction for the given light.
  29527. *
  29528. * @tsl
  29529. * @function
  29530. * @param {Light} light -The light source.
  29531. * @returns {Node<vec3>} The light's target direction.
  29532. */
  29533. const lightTargetDirection = ( light ) => cameraViewMatrix.transformDirection( lightPosition( light ).sub( lightTargetPosition( light ) ) );
  29534. const sortLights = ( lights ) => {
  29535. return lights.sort( ( a, b ) => a.id - b.id );
  29536. };
  29537. const getLightNodeById = ( id, lightNodes ) => {
  29538. for ( const lightNode of lightNodes ) {
  29539. if ( lightNode.isAnalyticLightNode && lightNode.light.id === id ) {
  29540. return lightNode;
  29541. }
  29542. }
  29543. return null;
  29544. };
  29545. const _lightsNodeRef = /*@__PURE__*/ new WeakMap();
  29546. const _hashData = [];
  29547. /**
  29548. * This node represents the scene's lighting and manages the lighting model's life cycle
  29549. * for the current build 3D object. It is responsible for computing the total outgoing
  29550. * light in a given lighting context.
  29551. *
  29552. * @augments Node
  29553. */
  29554. class LightsNode extends Node {
  29555. static get type() {
  29556. return 'LightsNode';
  29557. }
  29558. /**
  29559. * Constructs a new lights node.
  29560. */
  29561. constructor() {
  29562. super( 'vec3' );
  29563. /**
  29564. * A node representing the total diffuse light.
  29565. *
  29566. * @type {Node<vec3>}
  29567. */
  29568. this.totalDiffuseNode = property( 'vec3', 'totalDiffuse' );
  29569. /**
  29570. * A node representing the total specular light.
  29571. *
  29572. * @type {Node<vec3>}
  29573. */
  29574. this.totalSpecularNode = property( 'vec3', 'totalSpecular' );
  29575. /**
  29576. * A node representing the outgoing light.
  29577. *
  29578. * @type {Node<vec3>}
  29579. */
  29580. this.outgoingLightNode = property( 'vec3', 'outgoingLight' );
  29581. /**
  29582. * An array representing the lights in the scene.
  29583. *
  29584. * @private
  29585. * @type {Array<Light>}
  29586. */
  29587. this._lights = [];
  29588. /**
  29589. * For each light in the scene, this node will create a
  29590. * corresponding light node.
  29591. *
  29592. * @private
  29593. * @type {?Array<LightingNode>}
  29594. * @default null
  29595. */
  29596. this._lightNodes = null;
  29597. /**
  29598. * A hash for identifying the current light nodes setup.
  29599. *
  29600. * @private
  29601. * @type {?string}
  29602. * @default null
  29603. */
  29604. this._lightNodesHash = null;
  29605. /**
  29606. * `LightsNode` sets this property to `true` by default.
  29607. *
  29608. * @type {boolean}
  29609. * @default true
  29610. */
  29611. this.global = true;
  29612. }
  29613. /**
  29614. * Overwrites the default {@link Node#customCacheKey} implementation by including
  29615. * light data into the cache key.
  29616. *
  29617. * @return {number} The custom cache key.
  29618. */
  29619. customCacheKey() {
  29620. const lights = this._lights;
  29621. for ( let i = 0; i < lights.length; i ++ ) {
  29622. const light = lights[ i ];
  29623. _hashData.push( light.id );
  29624. _hashData.push( light.castShadow ? 1 : 0 );
  29625. if ( light.isSpotLight === true ) {
  29626. const hashMap = ( light.map !== null ) ? light.map.id : -1;
  29627. const hashColorNode = ( light.colorNode ) ? light.colorNode.getCacheKey() : -1;
  29628. _hashData.push( hashMap, hashColorNode );
  29629. }
  29630. }
  29631. const cacheKey = hashArray( _hashData );
  29632. _hashData.length = 0;
  29633. return cacheKey;
  29634. }
  29635. /**
  29636. * Computes a hash value for identifying the current light nodes setup.
  29637. *
  29638. * @param {NodeBuilder} builder - A reference to the current node builder.
  29639. * @return {string} The computed hash.
  29640. */
  29641. getHash( builder ) {
  29642. if ( this._lightNodesHash === null ) {
  29643. if ( this._lightNodes === null ) this.setupLightsNode( builder );
  29644. const hash = [];
  29645. for ( const lightNode of this._lightNodes ) {
  29646. hash.push( lightNode.getHash() );
  29647. }
  29648. this._lightNodesHash = 'lights-' + hash.join( ',' );
  29649. }
  29650. return this._lightNodesHash;
  29651. }
  29652. analyze( builder ) {
  29653. const properties = builder.getNodeProperties( this );
  29654. for ( const node of properties.nodes ) {
  29655. node.build( builder );
  29656. }
  29657. properties.outputNode.build( builder );
  29658. }
  29659. /**
  29660. * Creates lighting nodes for each scene light. This makes it possible to further
  29661. * process lights in the node system.
  29662. *
  29663. * @param {NodeBuilder} builder - A reference to the current node builder.
  29664. */
  29665. setupLightsNode( builder ) {
  29666. const lightNodes = [];
  29667. const previousLightNodes = this._lightNodes;
  29668. const lights = sortLights( this._lights );
  29669. const nodeLibrary = builder.renderer.library;
  29670. for ( const light of lights ) {
  29671. if ( light.isNode ) {
  29672. lightNodes.push( nodeObject( light ) );
  29673. } else {
  29674. let lightNode = null;
  29675. if ( previousLightNodes !== null ) {
  29676. lightNode = getLightNodeById( light.id, previousLightNodes ); // reuse existing light node
  29677. }
  29678. if ( lightNode === null ) {
  29679. // find the corresponding node type for a given light
  29680. const lightNodeClass = nodeLibrary.getLightNodeClass( light.constructor );
  29681. if ( lightNodeClass === null ) {
  29682. warn( `LightsNode.setupNodeLights: Light node not found for ${ light.constructor.name }` );
  29683. continue;
  29684. }
  29685. let lightNode = null;
  29686. if ( ! _lightsNodeRef.has( light ) ) {
  29687. lightNode = nodeObject( new lightNodeClass( light ) );
  29688. _lightsNodeRef.set( light, lightNode );
  29689. } else {
  29690. lightNode = _lightsNodeRef.get( light );
  29691. }
  29692. lightNodes.push( lightNode );
  29693. }
  29694. }
  29695. }
  29696. this._lightNodes = lightNodes;
  29697. }
  29698. /**
  29699. * Sets up a direct light in the lighting model.
  29700. *
  29701. * @param {Object} builder - The builder object containing the context and stack.
  29702. * @param {Object} lightNode - The light node.
  29703. * @param {Object} lightData - The light object containing color and direction properties.
  29704. */
  29705. setupDirectLight( builder, lightNode, lightData ) {
  29706. const { lightingModel, reflectedLight } = builder.context;
  29707. lightingModel.direct( {
  29708. ...lightData,
  29709. lightNode,
  29710. reflectedLight
  29711. }, builder );
  29712. }
  29713. setupDirectRectAreaLight( builder, lightNode, lightData ) {
  29714. const { lightingModel, reflectedLight } = builder.context;
  29715. lightingModel.directRectArea( {
  29716. ...lightData,
  29717. lightNode,
  29718. reflectedLight
  29719. }, builder );
  29720. }
  29721. /**
  29722. * Setups the internal lights by building all respective
  29723. * light nodes.
  29724. *
  29725. * @param {NodeBuilder} builder - A reference to the current node builder.
  29726. * @param {Array<LightingNode>} lightNodes - An array of lighting nodes.
  29727. */
  29728. setupLights( builder, lightNodes ) {
  29729. for ( const lightNode of lightNodes ) {
  29730. lightNode.build( builder );
  29731. }
  29732. }
  29733. getLightNodes( builder ) {
  29734. if ( this._lightNodes === null ) this.setupLightsNode( builder );
  29735. return this._lightNodes;
  29736. }
  29737. /**
  29738. * The implementation makes sure that for each light in the scene
  29739. * there is a corresponding light node. By building the light nodes
  29740. * and evaluating the lighting model the outgoing light is computed.
  29741. *
  29742. * @param {NodeBuilder} builder - A reference to the current node builder.
  29743. * @return {Node<vec3>} A node representing the outgoing light.
  29744. */
  29745. setup( builder ) {
  29746. const currentLightsNode = builder.lightsNode;
  29747. builder.lightsNode = this;
  29748. //
  29749. let outgoingLightNode = this.outgoingLightNode;
  29750. const context = builder.context;
  29751. const lightingModel = context.lightingModel;
  29752. const properties = builder.getNodeProperties( this );
  29753. if ( lightingModel ) {
  29754. const { totalDiffuseNode, totalSpecularNode } = this;
  29755. context.outgoingLight = outgoingLightNode;
  29756. const stack = builder.addStack();
  29757. //
  29758. properties.nodes = stack.nodes;
  29759. //
  29760. lightingModel.start( builder );
  29761. //
  29762. const { backdrop, backdropAlpha } = context;
  29763. const { directDiffuse, directSpecular, indirectDiffuse, indirectSpecular } = context.reflectedLight;
  29764. let totalDiffuse = directDiffuse.add( indirectDiffuse );
  29765. if ( backdrop !== null ) {
  29766. if ( backdropAlpha !== null ) {
  29767. totalDiffuse = vec3( backdropAlpha.mix( totalDiffuse, backdrop ) );
  29768. } else {
  29769. totalDiffuse = vec3( backdrop );
  29770. }
  29771. }
  29772. totalDiffuseNode.assign( totalDiffuse );
  29773. totalSpecularNode.assign( directSpecular.add( indirectSpecular ) );
  29774. outgoingLightNode.assign( totalDiffuseNode.add( totalSpecularNode ) );
  29775. //
  29776. lightingModel.finish( builder );
  29777. //
  29778. outgoingLightNode = outgoingLightNode.bypass( builder.removeStack() );
  29779. } else {
  29780. properties.nodes = [];
  29781. }
  29782. //
  29783. builder.lightsNode = currentLightsNode;
  29784. return outgoingLightNode;
  29785. }
  29786. /**
  29787. * Configures this node with an array of lights.
  29788. *
  29789. * @param {Array<Light>} lights - An array of lights.
  29790. * @return {LightsNode} A reference to this node.
  29791. */
  29792. setLights( lights ) {
  29793. this._lights = lights;
  29794. this._lightNodes = null;
  29795. this._lightNodesHash = null;
  29796. return this;
  29797. }
  29798. /**
  29799. * Returns an array of the scene's lights.
  29800. *
  29801. * @return {Array<Light>} The scene's lights.
  29802. */
  29803. getLights() {
  29804. return this._lights;
  29805. }
  29806. /**
  29807. * Whether the scene has lights or not.
  29808. *
  29809. * @type {boolean}
  29810. */
  29811. get hasLights() {
  29812. return this._lights.length > 0;
  29813. }
  29814. }
  29815. /**
  29816. * TSL function for creating an instance of `LightsNode` and configuring
  29817. * it with the given array of lights.
  29818. *
  29819. * @tsl
  29820. * @function
  29821. * @param {Array<Light>} lights - An array of lights.
  29822. * @return {LightsNode} The created lights node.
  29823. */
  29824. const lights = ( lights = [] ) => nodeObject( new LightsNode() ).setLights( lights );
  29825. /**
  29826. * Base class for all shadow nodes.
  29827. *
  29828. * Shadow nodes encapsulate shadow related logic and are always coupled to lighting nodes.
  29829. * Lighting nodes might share the same shadow node type or use specific ones depending on
  29830. * their requirements.
  29831. *
  29832. * @augments Node
  29833. */
  29834. class ShadowBaseNode extends Node {
  29835. static get type() {
  29836. return 'ShadowBaseNode';
  29837. }
  29838. /**
  29839. * Constructs a new shadow base node.
  29840. *
  29841. * @param {Light} light - The shadow casting light.
  29842. */
  29843. constructor( light ) {
  29844. super();
  29845. /**
  29846. * The shadow casting light.
  29847. *
  29848. * @type {Light}
  29849. */
  29850. this.light = light;
  29851. /**
  29852. * Overwritten since shadows are updated by default per render.
  29853. *
  29854. * @type {string}
  29855. * @default 'render'
  29856. */
  29857. this.updateBeforeType = NodeUpdateType.RENDER;
  29858. /**
  29859. * This flag can be used for type testing.
  29860. *
  29861. * @type {boolean}
  29862. * @readonly
  29863. * @default true
  29864. */
  29865. this.isShadowBaseNode = true;
  29866. }
  29867. /**
  29868. * Setups the shadow position node which is by default the predefined TSL node object `shadowPositionWorld`.
  29869. *
  29870. * @param {NodeBuilder} object - A configuration object that must at least hold a material reference.
  29871. */
  29872. setupShadowPosition( { context, material } ) {
  29873. // Use assign inside an Fn()
  29874. shadowPositionWorld.assign( material.receivedShadowPositionNode || context.shadowPositionWorld || positionWorld );
  29875. }
  29876. }
  29877. /**
  29878. * TSL object that represents the vertex position in world space during the shadow pass.
  29879. *
  29880. * @tsl
  29881. * @type {Node<vec3>}
  29882. */
  29883. const shadowPositionWorld = /*@__PURE__*/ property( 'vec3', 'shadowPositionWorld' );
  29884. /**
  29885. * Saves the state of the given renderer and stores it into the given state object.
  29886. *
  29887. * If not state object is provided, the function creates one.
  29888. *
  29889. * @private
  29890. * @function
  29891. * @param {Renderer} renderer - The renderer.
  29892. * @param {Object} [state={}] - The state.
  29893. * @return {Object} The state.
  29894. */
  29895. function saveRendererState( renderer, state = {} ) {
  29896. state.toneMapping = renderer.toneMapping;
  29897. state.toneMappingExposure = renderer.toneMappingExposure;
  29898. state.outputColorSpace = renderer.outputColorSpace;
  29899. state.renderTarget = renderer.getRenderTarget();
  29900. state.activeCubeFace = renderer.getActiveCubeFace();
  29901. state.activeMipmapLevel = renderer.getActiveMipmapLevel();
  29902. state.renderObjectFunction = renderer.getRenderObjectFunction();
  29903. state.pixelRatio = renderer.getPixelRatio();
  29904. state.mrt = renderer.getMRT();
  29905. state.clearColor = renderer.getClearColor( state.clearColor || new Color() );
  29906. state.clearAlpha = renderer.getClearAlpha();
  29907. state.autoClear = renderer.autoClear;
  29908. state.scissorTest = renderer.getScissorTest();
  29909. return state;
  29910. }
  29911. /**
  29912. * Saves the state of the given renderer and stores it into the given state object.
  29913. * Besides, the function also resets the state of the renderer to its default values.
  29914. *
  29915. * If not state object is provided, the function creates one.
  29916. *
  29917. * @private
  29918. * @function
  29919. * @param {Renderer} renderer - The renderer.
  29920. * @param {Object} [state={}] - The state.
  29921. * @return {Object} The state.
  29922. */
  29923. function resetRendererState( renderer, state ) {
  29924. state = saveRendererState( renderer, state );
  29925. renderer.setMRT( null );
  29926. renderer.setRenderObjectFunction( null );
  29927. renderer.setClearColor( 0x000000, 1 );
  29928. renderer.autoClear = true;
  29929. return state;
  29930. }
  29931. /**
  29932. * Restores the state of the given renderer from the given state object.
  29933. *
  29934. * @private
  29935. * @function
  29936. * @param {Renderer} renderer - The renderer.
  29937. * @param {Object} state - The state to restore.
  29938. */
  29939. function restoreRendererState( renderer, state ) {
  29940. renderer.toneMapping = state.toneMapping;
  29941. renderer.toneMappingExposure = state.toneMappingExposure;
  29942. renderer.outputColorSpace = state.outputColorSpace;
  29943. renderer.setRenderTarget( state.renderTarget, state.activeCubeFace, state.activeMipmapLevel );
  29944. renderer.setRenderObjectFunction( state.renderObjectFunction );
  29945. renderer.setPixelRatio( state.pixelRatio );
  29946. renderer.setMRT( state.mrt );
  29947. renderer.setClearColor( state.clearColor, state.clearAlpha );
  29948. renderer.autoClear = state.autoClear;
  29949. renderer.setScissorTest( state.scissorTest );
  29950. }
  29951. /**
  29952. * Saves the state of the given scene and stores it into the given state object.
  29953. *
  29954. * If not state object is provided, the function creates one.
  29955. *
  29956. * @private
  29957. * @function
  29958. * @param {Scene} scene - The scene.
  29959. * @param {Object} [state={}] - The state.
  29960. * @return {Object} The state.
  29961. */
  29962. function saveSceneState( scene, state = {} ) {
  29963. state.background = scene.background;
  29964. state.backgroundNode = scene.backgroundNode;
  29965. state.overrideMaterial = scene.overrideMaterial;
  29966. return state;
  29967. }
  29968. /**
  29969. * Saves the state of the given scene and stores it into the given state object.
  29970. * Besides, the function also resets the state of the scene to its default values.
  29971. *
  29972. * If not state object is provided, the function creates one.
  29973. *
  29974. * @private
  29975. * @function
  29976. * @param {Scene} scene - The scene.
  29977. * @param {Object} [state={}] - The state.
  29978. * @return {Object} The state.
  29979. */
  29980. function resetSceneState( scene, state ) {
  29981. state = saveSceneState( scene, state );
  29982. scene.background = null;
  29983. scene.backgroundNode = null;
  29984. scene.overrideMaterial = null;
  29985. return state;
  29986. }
  29987. /**
  29988. * Restores the state of the given scene from the given state object.
  29989. *
  29990. * @private
  29991. * @function
  29992. * @param {Scene} scene - The scene.
  29993. * @param {Object} state - The state to restore.
  29994. */
  29995. function restoreSceneState( scene, state ) {
  29996. scene.background = state.background;
  29997. scene.backgroundNode = state.backgroundNode;
  29998. scene.overrideMaterial = state.overrideMaterial;
  29999. }
  30000. /**
  30001. * Saves the state of the given renderer and scene and stores it into the given state object.
  30002. *
  30003. * If not state object is provided, the function creates one.
  30004. *
  30005. * @private
  30006. * @function
  30007. * @param {Renderer} renderer - The renderer.
  30008. * @param {Scene} scene - The scene.
  30009. * @param {Object} [state={}] - The state.
  30010. * @return {Object} The state.
  30011. */
  30012. function saveRendererAndSceneState( renderer, scene, state = {} ) {
  30013. state = saveRendererState( renderer, state );
  30014. state = saveSceneState( scene, state );
  30015. return state;
  30016. }
  30017. /**
  30018. * Saves the state of the given renderer and scene and stores it into the given state object.
  30019. * Besides, the function also resets the state of the renderer and scene to its default values.
  30020. *
  30021. * If not state object is provided, the function creates one.
  30022. *
  30023. * @private
  30024. * @function
  30025. * @param {Renderer} renderer - The renderer.
  30026. * @param {Scene} scene - The scene.
  30027. * @param {Object} [state={}] - The state.
  30028. * @return {Object} The state.
  30029. */
  30030. function resetRendererAndSceneState( renderer, scene, state ) {
  30031. state = resetRendererState( renderer, state );
  30032. state = resetSceneState( scene, state );
  30033. return state;
  30034. }
  30035. /**
  30036. * Restores the state of the given renderer and scene from the given state object.
  30037. *
  30038. * @private
  30039. * @function
  30040. * @param {Renderer} renderer - The renderer.
  30041. * @param {Scene} scene - The scene.
  30042. * @param {Object} state - The state to restore.
  30043. */
  30044. function restoreRendererAndSceneState( renderer, scene, state ) {
  30045. restoreRendererState( renderer, state );
  30046. restoreSceneState( scene, state );
  30047. }
  30048. var RendererUtils = /*#__PURE__*/Object.freeze({
  30049. __proto__: null,
  30050. resetRendererAndSceneState: resetRendererAndSceneState,
  30051. resetRendererState: resetRendererState,
  30052. resetSceneState: resetSceneState,
  30053. restoreRendererAndSceneState: restoreRendererAndSceneState,
  30054. restoreRendererState: restoreRendererState,
  30055. restoreSceneState: restoreSceneState,
  30056. saveRendererAndSceneState: saveRendererAndSceneState,
  30057. saveRendererState: saveRendererState,
  30058. saveSceneState: saveSceneState
  30059. });
  30060. const shadowMaterialLib = /*@__PURE__*/ new WeakMap();
  30061. /**
  30062. * A shadow filtering function performing basic filtering. This is in fact an unfiltered version of the shadow map
  30063. * with a binary `[0,1]` result.
  30064. *
  30065. * @method
  30066. * @param {Object} inputs - The input parameter object.
  30067. * @param {DepthTexture} inputs.depthTexture - A reference to the shadow map's texture data.
  30068. * @param {Node<vec3>} inputs.shadowCoord - The shadow coordinates.
  30069. * @return {Node<float>} The filtering result.
  30070. */
  30071. const BasicShadowFilter = /*@__PURE__*/ Fn( ( { depthTexture, shadowCoord, depthLayer } ) => {
  30072. let basic = texture( depthTexture, shadowCoord.xy ).setName( 't_basic' );
  30073. if ( depthTexture.isArrayTexture ) {
  30074. basic = basic.depth( depthLayer );
  30075. }
  30076. return basic.compare( shadowCoord.z );
  30077. } );
  30078. /**
  30079. * A shadow filtering function performing PCF filtering.
  30080. *
  30081. * @method
  30082. * @param {Object} inputs - The input parameter object.
  30083. * @param {DepthTexture} inputs.depthTexture - A reference to the shadow map's texture data.
  30084. * @param {Node<vec3>} inputs.shadowCoord - The shadow coordinates.
  30085. * @param {LightShadow} inputs.shadow - The light shadow.
  30086. * @return {Node<float>} The filtering result.
  30087. */
  30088. const PCFShadowFilter = /*@__PURE__*/ Fn( ( { depthTexture, shadowCoord, shadow, depthLayer } ) => {
  30089. const depthCompare = ( uv, compare ) => {
  30090. let depth = texture( depthTexture, uv );
  30091. if ( depthTexture.isArrayTexture ) {
  30092. depth = depth.depth( depthLayer );
  30093. }
  30094. return depth.compare( compare );
  30095. };
  30096. const mapSize = reference( 'mapSize', 'vec2', shadow ).setGroup( renderGroup );
  30097. const radius = reference( 'radius', 'float', shadow ).setGroup( renderGroup );
  30098. const texelSize = vec2( 1 ).div( mapSize );
  30099. const dx0 = texelSize.x.negate().mul( radius );
  30100. const dy0 = texelSize.y.negate().mul( radius );
  30101. const dx1 = texelSize.x.mul( radius );
  30102. const dy1 = texelSize.y.mul( radius );
  30103. const dx2 = dx0.div( 2 );
  30104. const dy2 = dy0.div( 2 );
  30105. const dx3 = dx1.div( 2 );
  30106. const dy3 = dy1.div( 2 );
  30107. return add(
  30108. depthCompare( shadowCoord.xy.add( vec2( dx0, dy0 ) ), shadowCoord.z ),
  30109. depthCompare( shadowCoord.xy.add( vec2( 0, dy0 ) ), shadowCoord.z ),
  30110. depthCompare( shadowCoord.xy.add( vec2( dx1, dy0 ) ), shadowCoord.z ),
  30111. depthCompare( shadowCoord.xy.add( vec2( dx2, dy2 ) ), shadowCoord.z ),
  30112. depthCompare( shadowCoord.xy.add( vec2( 0, dy2 ) ), shadowCoord.z ),
  30113. depthCompare( shadowCoord.xy.add( vec2( dx3, dy2 ) ), shadowCoord.z ),
  30114. depthCompare( shadowCoord.xy.add( vec2( dx0, 0 ) ), shadowCoord.z ),
  30115. depthCompare( shadowCoord.xy.add( vec2( dx2, 0 ) ), shadowCoord.z ),
  30116. depthCompare( shadowCoord.xy, shadowCoord.z ),
  30117. depthCompare( shadowCoord.xy.add( vec2( dx3, 0 ) ), shadowCoord.z ),
  30118. depthCompare( shadowCoord.xy.add( vec2( dx1, 0 ) ), shadowCoord.z ),
  30119. depthCompare( shadowCoord.xy.add( vec2( dx2, dy3 ) ), shadowCoord.z ),
  30120. depthCompare( shadowCoord.xy.add( vec2( 0, dy3 ) ), shadowCoord.z ),
  30121. depthCompare( shadowCoord.xy.add( vec2( dx3, dy3 ) ), shadowCoord.z ),
  30122. depthCompare( shadowCoord.xy.add( vec2( dx0, dy1 ) ), shadowCoord.z ),
  30123. depthCompare( shadowCoord.xy.add( vec2( 0, dy1 ) ), shadowCoord.z ),
  30124. depthCompare( shadowCoord.xy.add( vec2( dx1, dy1 ) ), shadowCoord.z )
  30125. ).mul( 1 / 17 );
  30126. } );
  30127. /**
  30128. * A shadow filtering function performing PCF soft filtering.
  30129. *
  30130. * @method
  30131. * @param {Object} inputs - The input parameter object.
  30132. * @param {DepthTexture} inputs.depthTexture - A reference to the shadow map's texture data.
  30133. * @param {Node<vec3>} inputs.shadowCoord - The shadow coordinates.
  30134. * @param {LightShadow} inputs.shadow - The light shadow.
  30135. * @return {Node<float>} The filtering result.
  30136. */
  30137. const PCFSoftShadowFilter = /*@__PURE__*/ Fn( ( { depthTexture, shadowCoord, shadow, depthLayer } ) => {
  30138. const depthCompare = ( uv, compare ) => {
  30139. let depth = texture( depthTexture, uv );
  30140. if ( depthTexture.isArrayTexture ) {
  30141. depth = depth.depth( depthLayer );
  30142. }
  30143. return depth.compare( compare );
  30144. };
  30145. const mapSize = reference( 'mapSize', 'vec2', shadow ).setGroup( renderGroup );
  30146. const texelSize = vec2( 1 ).div( mapSize );
  30147. const dx = texelSize.x;
  30148. const dy = texelSize.y;
  30149. const uv = shadowCoord.xy;
  30150. const f = fract( uv.mul( mapSize ).add( 0.5 ) );
  30151. uv.subAssign( f.mul( texelSize ) );
  30152. return add(
  30153. depthCompare( uv, shadowCoord.z ),
  30154. depthCompare( uv.add( vec2( dx, 0 ) ), shadowCoord.z ),
  30155. depthCompare( uv.add( vec2( 0, dy ) ), shadowCoord.z ),
  30156. depthCompare( uv.add( texelSize ), shadowCoord.z ),
  30157. mix(
  30158. depthCompare( uv.add( vec2( dx.negate(), 0 ) ), shadowCoord.z ),
  30159. depthCompare( uv.add( vec2( dx.mul( 2 ), 0 ) ), shadowCoord.z ),
  30160. f.x
  30161. ),
  30162. mix(
  30163. depthCompare( uv.add( vec2( dx.negate(), dy ) ), shadowCoord.z ),
  30164. depthCompare( uv.add( vec2( dx.mul( 2 ), dy ) ), shadowCoord.z ),
  30165. f.x
  30166. ),
  30167. mix(
  30168. depthCompare( uv.add( vec2( 0, dy.negate() ) ), shadowCoord.z ),
  30169. depthCompare( uv.add( vec2( 0, dy.mul( 2 ) ) ), shadowCoord.z ),
  30170. f.y
  30171. ),
  30172. mix(
  30173. depthCompare( uv.add( vec2( dx, dy.negate() ) ), shadowCoord.z ),
  30174. depthCompare( uv.add( vec2( dx, dy.mul( 2 ) ) ), shadowCoord.z ),
  30175. f.y
  30176. ),
  30177. mix(
  30178. mix(
  30179. depthCompare( uv.add( vec2( dx.negate(), dy.negate() ) ), shadowCoord.z ),
  30180. depthCompare( uv.add( vec2( dx.mul( 2 ), dy.negate() ) ), shadowCoord.z ),
  30181. f.x
  30182. ),
  30183. mix(
  30184. depthCompare( uv.add( vec2( dx.negate(), dy.mul( 2 ) ) ), shadowCoord.z ),
  30185. depthCompare( uv.add( vec2( dx.mul( 2 ), dy.mul( 2 ) ) ), shadowCoord.z ),
  30186. f.x
  30187. ),
  30188. f.y
  30189. )
  30190. ).mul( 1 / 9 );
  30191. } );
  30192. /**
  30193. * A shadow filtering function performing VSM filtering.
  30194. *
  30195. * @method
  30196. * @param {Object} inputs - The input parameter object.
  30197. * @param {DepthTexture} inputs.depthTexture - A reference to the shadow map's texture data.
  30198. * @param {Node<vec3>} inputs.shadowCoord - The shadow coordinates.
  30199. * @return {Node<float>} The filtering result.
  30200. */
  30201. const VSMShadowFilter = /*@__PURE__*/ Fn( ( { depthTexture, shadowCoord, depthLayer } ) => {
  30202. const occlusion = float( 1 ).toVar();
  30203. let distribution = texture( depthTexture ).sample( shadowCoord.xy );
  30204. if ( depthTexture.isArrayTexture ) {
  30205. distribution = distribution.depth( depthLayer );
  30206. }
  30207. distribution = distribution.rg;
  30208. const hardShadow = step( shadowCoord.z, distribution.x );
  30209. If( hardShadow.notEqual( float( 1.0 ) ), () => {
  30210. const distance = shadowCoord.z.sub( distribution.x );
  30211. const variance = max$1( 0, distribution.y.mul( distribution.y ) );
  30212. let softnessProbability = variance.div( variance.add( distance.mul( distance ) ) ); // Chebeyshevs inequality
  30213. softnessProbability = clamp( sub( softnessProbability, 0.3 ).div( 0.95 - 0.3 ) );
  30214. occlusion.assign( clamp( max$1( hardShadow, softnessProbability ) ) );
  30215. } );
  30216. return occlusion;
  30217. } );
  30218. //
  30219. const linearDistance = /*@__PURE__*/ Fn( ( [ position, cameraNear, cameraFar ] ) => {
  30220. let dist = positionWorld.sub( position ).length();
  30221. dist = dist.sub( cameraNear ).div( cameraFar.sub( cameraNear ) );
  30222. dist = dist.saturate(); // clamp to [ 0, 1 ]
  30223. return dist;
  30224. } );
  30225. const linearShadowDistance = ( light ) => {
  30226. const camera = light.shadow.camera;
  30227. const nearDistance = reference( 'near', 'float', camera ).setGroup( renderGroup );
  30228. const farDistance = reference( 'far', 'float', camera ).setGroup( renderGroup );
  30229. const referencePosition = objectPosition( light );
  30230. return linearDistance( referencePosition, nearDistance, farDistance );
  30231. };
  30232. /**
  30233. * Retrieves or creates a shadow material for the given light source.
  30234. *
  30235. * This function checks if a shadow material already exists for the provided light.
  30236. * If not, it creates a new `NodeMaterial` configured for shadow rendering and stores it
  30237. * in the `shadowMaterialLib` for future use.
  30238. *
  30239. * @tsl
  30240. * @function
  30241. * @param {Light} light - The light source for which the shadow material is needed.
  30242. * If the light is a point light, a depth node is calculated
  30243. * using the linear shadow distance.
  30244. * @returns {NodeMaterial} The shadow material associated with the given light.
  30245. */
  30246. const getShadowMaterial = ( light ) => {
  30247. let material = shadowMaterialLib.get( light );
  30248. if ( material === undefined ) {
  30249. const depthNode = light.isPointLight ? linearShadowDistance( light ) : null;
  30250. material = new NodeMaterial();
  30251. material.colorNode = vec4( 0, 0, 0, 1 );
  30252. material.depthNode = depthNode;
  30253. material.isShadowPassMaterial = true; // Use to avoid other overrideMaterial override material.colorNode unintentionally when using material.shadowNode
  30254. material.name = 'ShadowMaterial';
  30255. material.fog = false;
  30256. shadowMaterialLib.set( light, material );
  30257. }
  30258. return material;
  30259. };
  30260. //
  30261. const _shadowRenderObjectLibrary = /*@__PURE__*/ new ChainMap();
  30262. const _shadowRenderObjectKeys = [];
  30263. /**
  30264. * Creates a function to render shadow objects in a scene.
  30265. *
  30266. * @tsl
  30267. * @function
  30268. * @param {Renderer} renderer - The renderer.
  30269. * @param {LightShadow} shadow - The light shadow object containing shadow properties.
  30270. * @param {number} shadowType - The type of shadow map (e.g., BasicShadowMap).
  30271. * @param {boolean} useVelocity - Whether to use velocity data for rendering.
  30272. * @return {shadowRenderObjectFunction} A function that renders shadow objects.
  30273. */
  30274. const getShadowRenderObjectFunction = ( renderer, shadow, shadowType, useVelocity ) => {
  30275. _shadowRenderObjectKeys[ 0 ] = renderer;
  30276. _shadowRenderObjectKeys[ 1 ] = shadow;
  30277. let renderObjectFunction = _shadowRenderObjectLibrary.get( _shadowRenderObjectKeys );
  30278. if ( renderObjectFunction === undefined || ( renderObjectFunction.shadowType !== shadowType || renderObjectFunction.useVelocity !== useVelocity ) ) {
  30279. renderObjectFunction = ( object, scene, _camera, geometry, material, group, ...params ) => {
  30280. if ( object.castShadow === true || ( object.receiveShadow && shadowType === VSMShadowMap ) ) {
  30281. if ( useVelocity ) {
  30282. getDataFromObject( object ).useVelocity = true;
  30283. }
  30284. object.onBeforeShadow( renderer, object, _camera, shadow.camera, geometry, scene.overrideMaterial, group );
  30285. renderer.renderObject( object, scene, _camera, geometry, material, group, ...params );
  30286. object.onAfterShadow( renderer, object, _camera, shadow.camera, geometry, scene.overrideMaterial, group );
  30287. }
  30288. };
  30289. renderObjectFunction.shadowType = shadowType;
  30290. renderObjectFunction.useVelocity = useVelocity;
  30291. _shadowRenderObjectLibrary.set( _shadowRenderObjectKeys, renderObjectFunction );
  30292. }
  30293. _shadowRenderObjectKeys[ 0 ] = null;
  30294. _shadowRenderObjectKeys[ 1 ] = null;
  30295. return renderObjectFunction;
  30296. };
  30297. /**
  30298. * Represents the shader code for the first VSM render pass.
  30299. *
  30300. * @private
  30301. * @method
  30302. * @param {Object} inputs - The input parameter object.
  30303. * @param {Node<float>} inputs.samples - The number of samples
  30304. * @param {Node<float>} inputs.radius - The radius.
  30305. * @param {Node<float>} inputs.size - The size.
  30306. * @param {TextureNode} inputs.shadowPass - A reference to the render target's depth data.
  30307. * @return {Node<vec2>} The VSM output.
  30308. */
  30309. const VSMPassVertical = /*@__PURE__*/ Fn( ( { samples, radius, size, shadowPass, depthLayer } ) => {
  30310. const mean = float( 0 ).toVar( 'meanVertical' );
  30311. const squaredMean = float( 0 ).toVar( 'squareMeanVertical' );
  30312. const uvStride = samples.lessThanEqual( float( 1 ) ).select( float( 0 ), float( 2 ).div( samples.sub( 1 ) ) );
  30313. const uvStart = samples.lessThanEqual( float( 1 ) ).select( float( 0 ), float( -1 ) );
  30314. Loop( { start: int( 0 ), end: int( samples ), type: 'int', condition: '<' }, ( { i } ) => {
  30315. const uvOffset = uvStart.add( float( i ).mul( uvStride ) );
  30316. let depth = shadowPass.sample( add( screenCoordinate.xy, vec2( 0, uvOffset ).mul( radius ) ).div( size ) );
  30317. if ( shadowPass.value.isArrayTexture ) {
  30318. depth = depth.depth( depthLayer );
  30319. }
  30320. depth = depth.x;
  30321. mean.addAssign( depth );
  30322. squaredMean.addAssign( depth.mul( depth ) );
  30323. } );
  30324. mean.divAssign( samples );
  30325. squaredMean.divAssign( samples );
  30326. const std_dev = sqrt( squaredMean.sub( mean.mul( mean ) ) );
  30327. return vec2( mean, std_dev );
  30328. } );
  30329. /**
  30330. * Represents the shader code for the second VSM render pass.
  30331. *
  30332. * @private
  30333. * @method
  30334. * @param {Object} inputs - The input parameter object.
  30335. * @param {Node<float>} inputs.samples - The number of samples
  30336. * @param {Node<float>} inputs.radius - The radius.
  30337. * @param {Node<float>} inputs.size - The size.
  30338. * @param {TextureNode} inputs.shadowPass - The result of the first VSM render pass.
  30339. * @return {Node<vec2>} The VSM output.
  30340. */
  30341. const VSMPassHorizontal = /*@__PURE__*/ Fn( ( { samples, radius, size, shadowPass, depthLayer } ) => {
  30342. const mean = float( 0 ).toVar( 'meanHorizontal' );
  30343. const squaredMean = float( 0 ).toVar( 'squareMeanHorizontal' );
  30344. const uvStride = samples.lessThanEqual( float( 1 ) ).select( float( 0 ), float( 2 ).div( samples.sub( 1 ) ) );
  30345. const uvStart = samples.lessThanEqual( float( 1 ) ).select( float( 0 ), float( -1 ) );
  30346. Loop( { start: int( 0 ), end: int( samples ), type: 'int', condition: '<' }, ( { i } ) => {
  30347. const uvOffset = uvStart.add( float( i ).mul( uvStride ) );
  30348. let distribution = shadowPass.sample( add( screenCoordinate.xy, vec2( uvOffset, 0 ).mul( radius ) ).div( size ) );
  30349. if ( shadowPass.value.isArrayTexture ) {
  30350. distribution = distribution.depth( depthLayer );
  30351. }
  30352. mean.addAssign( distribution.x );
  30353. squaredMean.addAssign( add( distribution.y.mul( distribution.y ), distribution.x.mul( distribution.x ) ) );
  30354. } );
  30355. mean.divAssign( samples );
  30356. squaredMean.divAssign( samples );
  30357. const std_dev = sqrt( squaredMean.sub( mean.mul( mean ) ) );
  30358. return vec2( mean, std_dev );
  30359. } );
  30360. const _shadowFilterLib = [ BasicShadowFilter, PCFShadowFilter, PCFSoftShadowFilter, VSMShadowFilter ];
  30361. //
  30362. let _rendererState;
  30363. const _quadMesh = /*@__PURE__*/ new QuadMesh();
  30364. /**
  30365. * Represents the default shadow implementation for lighting nodes.
  30366. *
  30367. * @augments ShadowBaseNode
  30368. */
  30369. class ShadowNode extends ShadowBaseNode {
  30370. static get type() {
  30371. return 'ShadowNode';
  30372. }
  30373. /**
  30374. * Constructs a new shadow node.
  30375. *
  30376. * @param {Light} light - The shadow casting light.
  30377. * @param {?LightShadow} [shadow=null] - An optional light shadow.
  30378. */
  30379. constructor( light, shadow = null ) {
  30380. super( light );
  30381. /**
  30382. * The light shadow which defines the properties light's
  30383. * shadow.
  30384. *
  30385. * @type {?LightShadow}
  30386. * @default null
  30387. */
  30388. this.shadow = shadow || light.shadow;
  30389. /**
  30390. * A reference to the shadow map which is a render target.
  30391. *
  30392. * @type {?RenderTarget}
  30393. * @default null
  30394. */
  30395. this.shadowMap = null;
  30396. /**
  30397. * Only relevant for VSM shadows. Render target for the
  30398. * first VSM render pass.
  30399. *
  30400. * @type {?RenderTarget}
  30401. * @default null
  30402. */
  30403. this.vsmShadowMapVertical = null;
  30404. /**
  30405. * Only relevant for VSM shadows. Render target for the
  30406. * second VSM render pass.
  30407. *
  30408. * @type {?RenderTarget}
  30409. * @default null
  30410. */
  30411. this.vsmShadowMapHorizontal = null;
  30412. /**
  30413. * Only relevant for VSM shadows. Node material which
  30414. * is used to render the first VSM pass.
  30415. *
  30416. * @type {?NodeMaterial}
  30417. * @default null
  30418. */
  30419. this.vsmMaterialVertical = null;
  30420. /**
  30421. * Only relevant for VSM shadows. Node material which
  30422. * is used to render the second VSM pass.
  30423. *
  30424. * @type {?NodeMaterial}
  30425. * @default null
  30426. */
  30427. this.vsmMaterialHorizontal = null;
  30428. /**
  30429. * A reference to the output node which defines the
  30430. * final result of this shadow node.
  30431. *
  30432. * @type {?Node}
  30433. * @private
  30434. * @default null
  30435. */
  30436. this._node = null;
  30437. /**
  30438. * The current shadow map type of this shadow node.
  30439. *
  30440. * @type {?number}
  30441. * @private
  30442. * @default null
  30443. */
  30444. this._currentShadowType = null;
  30445. /**
  30446. * A Weak Map holding the current frame ID per camera. Used
  30447. * to control the update of shadow maps.
  30448. *
  30449. * @type {WeakMap<Camera,number>}
  30450. * @private
  30451. */
  30452. this._cameraFrameId = new WeakMap();
  30453. /**
  30454. * This flag can be used for type testing.
  30455. *
  30456. * @type {boolean}
  30457. * @readonly
  30458. * @default true
  30459. */
  30460. this.isShadowNode = true;
  30461. /**
  30462. * This index can be used when overriding setupRenderTarget with a RenderTarget Array to specify the depth layer.
  30463. *
  30464. * @type {number}
  30465. * @readonly
  30466. * @default true
  30467. */
  30468. this.depthLayer = 0;
  30469. }
  30470. /**
  30471. * Setups the shadow filtering.
  30472. *
  30473. * @param {NodeBuilder} builder - A reference to the current node builder.
  30474. * @param {Object} inputs - A configuration object that defines the shadow filtering.
  30475. * @param {Function} inputs.filterFn - This function defines the filtering type of the shadow map e.g. PCF.
  30476. * @param {DepthTexture} inputs.depthTexture - A reference to the shadow map's texture data.
  30477. * @param {Node<vec3>} inputs.shadowCoord - Shadow coordinates which are used to sample from the shadow map.
  30478. * @param {LightShadow} inputs.shadow - The light shadow.
  30479. * @return {Node<float>} The result node of the shadow filtering.
  30480. */
  30481. setupShadowFilter( builder, { filterFn, depthTexture, shadowCoord, shadow, depthLayer } ) {
  30482. const frustumTest = shadowCoord.x.greaterThanEqual( 0 )
  30483. .and( shadowCoord.x.lessThanEqual( 1 ) )
  30484. .and( shadowCoord.y.greaterThanEqual( 0 ) )
  30485. .and( shadowCoord.y.lessThanEqual( 1 ) )
  30486. .and( shadowCoord.z.lessThanEqual( 1 ) );
  30487. const shadowNode = filterFn( { depthTexture, shadowCoord, shadow, depthLayer } );
  30488. return frustumTest.select( shadowNode, float( 1 ) );
  30489. }
  30490. /**
  30491. * Setups the shadow coordinates.
  30492. *
  30493. * @param {NodeBuilder} builder - A reference to the current node builder.
  30494. * @param {Node<vec3>} shadowPosition - A node representing the shadow position.
  30495. * @return {Node<vec3>} The shadow coordinates.
  30496. */
  30497. setupShadowCoord( builder, shadowPosition ) {
  30498. const { shadow } = this;
  30499. const { renderer } = builder;
  30500. const bias = reference( 'bias', 'float', shadow ).setGroup( renderGroup );
  30501. let shadowCoord = shadowPosition;
  30502. let coordZ;
  30503. if ( shadow.camera.isOrthographicCamera || renderer.logarithmicDepthBuffer !== true ) {
  30504. shadowCoord = shadowCoord.xyz.div( shadowCoord.w );
  30505. coordZ = shadowCoord.z;
  30506. if ( renderer.coordinateSystem === WebGPUCoordinateSystem ) {
  30507. coordZ = coordZ.mul( 2 ).sub( 1 ); // WebGPU: Conversion [ 0, 1 ] to [ - 1, 1 ]
  30508. }
  30509. } else {
  30510. const w = shadowCoord.w;
  30511. shadowCoord = shadowCoord.xy.div( w ); // <-- Only divide X/Y coords since we don't need Z
  30512. // The normally available "cameraNear" and "cameraFar" nodes cannot be used here because they do not get
  30513. // updated to use the shadow camera. So, we have to declare our own "local" ones here.
  30514. // TODO: How do we get the cameraNear/cameraFar nodes to use the shadow camera so we don't have to declare local ones here?
  30515. const cameraNearLocal = reference( 'near', 'float', shadow.camera ).setGroup( renderGroup );
  30516. const cameraFarLocal = reference( 'far', 'float', shadow.camera ).setGroup( renderGroup );
  30517. coordZ = viewZToLogarithmicDepth( w.negate(), cameraNearLocal, cameraFarLocal );
  30518. }
  30519. shadowCoord = vec3(
  30520. shadowCoord.x,
  30521. shadowCoord.y.oneMinus(), // follow webgpu standards
  30522. coordZ.add( bias )
  30523. );
  30524. return shadowCoord;
  30525. }
  30526. /**
  30527. * Returns the shadow filtering function for the given shadow type.
  30528. *
  30529. * @param {number} type - The shadow type.
  30530. * @return {Function} The filtering function.
  30531. */
  30532. getShadowFilterFn( type ) {
  30533. return _shadowFilterLib[ type ];
  30534. }
  30535. setupRenderTarget( shadow, builder ) {
  30536. const depthTexture = new DepthTexture( shadow.mapSize.width, shadow.mapSize.height );
  30537. depthTexture.name = 'ShadowDepthTexture';
  30538. depthTexture.compareFunction = LessCompare;
  30539. const shadowMap = builder.createRenderTarget( shadow.mapSize.width, shadow.mapSize.height );
  30540. shadowMap.texture.name = 'ShadowMap';
  30541. shadowMap.texture.type = shadow.mapType;
  30542. shadowMap.depthTexture = depthTexture;
  30543. return { shadowMap, depthTexture };
  30544. }
  30545. /**
  30546. * Setups the shadow output node.
  30547. *
  30548. * @param {NodeBuilder} builder - A reference to the current node builder.
  30549. * @return {Node<vec3>} The shadow output node.
  30550. */
  30551. setupShadow( builder ) {
  30552. const { renderer, camera } = builder;
  30553. const { light, shadow } = this;
  30554. const shadowMapType = renderer.shadowMap.type;
  30555. const { depthTexture, shadowMap } = this.setupRenderTarget( shadow, builder );
  30556. shadow.camera.coordinateSystem = camera.coordinateSystem;
  30557. shadow.camera.updateProjectionMatrix();
  30558. // VSM
  30559. if ( shadowMapType === VSMShadowMap && shadow.isPointLightShadow !== true ) {
  30560. depthTexture.compareFunction = null; // VSM does not use textureSampleCompare()/texture2DCompare()
  30561. if ( shadowMap.depth > 1 ) {
  30562. if ( ! shadowMap._vsmShadowMapVertical ) {
  30563. shadowMap._vsmShadowMapVertical = builder.createRenderTarget( shadow.mapSize.width, shadow.mapSize.height, { format: RGFormat, type: HalfFloatType, depth: shadowMap.depth, depthBuffer: false } );
  30564. shadowMap._vsmShadowMapVertical.texture.name = 'VSMVertical';
  30565. }
  30566. this.vsmShadowMapVertical = shadowMap._vsmShadowMapVertical;
  30567. if ( ! shadowMap._vsmShadowMapHorizontal ) {
  30568. shadowMap._vsmShadowMapHorizontal = builder.createRenderTarget( shadow.mapSize.width, shadow.mapSize.height, { format: RGFormat, type: HalfFloatType, depth: shadowMap.depth, depthBuffer: false } );
  30569. shadowMap._vsmShadowMapHorizontal.texture.name = 'VSMHorizontal';
  30570. }
  30571. this.vsmShadowMapHorizontal = shadowMap._vsmShadowMapHorizontal;
  30572. } else {
  30573. this.vsmShadowMapVertical = builder.createRenderTarget( shadow.mapSize.width, shadow.mapSize.height, { format: RGFormat, type: HalfFloatType, depthBuffer: false } );
  30574. this.vsmShadowMapHorizontal = builder.createRenderTarget( shadow.mapSize.width, shadow.mapSize.height, { format: RGFormat, type: HalfFloatType, depthBuffer: false } );
  30575. }
  30576. let shadowPassVertical = texture( depthTexture );
  30577. if ( depthTexture.isArrayTexture ) {
  30578. shadowPassVertical = shadowPassVertical.depth( this.depthLayer );
  30579. }
  30580. let shadowPassHorizontal = texture( this.vsmShadowMapVertical.texture );
  30581. if ( depthTexture.isArrayTexture ) {
  30582. shadowPassHorizontal = shadowPassHorizontal.depth( this.depthLayer );
  30583. }
  30584. const samples = reference( 'blurSamples', 'float', shadow ).setGroup( renderGroup );
  30585. const radius = reference( 'radius', 'float', shadow ).setGroup( renderGroup );
  30586. const size = reference( 'mapSize', 'vec2', shadow ).setGroup( renderGroup );
  30587. let material = this.vsmMaterialVertical || ( this.vsmMaterialVertical = new NodeMaterial() );
  30588. material.fragmentNode = VSMPassVertical( { samples, radius, size, shadowPass: shadowPassVertical, depthLayer: this.depthLayer } ).context( builder.getSharedContext() );
  30589. material.name = 'VSMVertical';
  30590. material = this.vsmMaterialHorizontal || ( this.vsmMaterialHorizontal = new NodeMaterial() );
  30591. material.fragmentNode = VSMPassHorizontal( { samples, radius, size, shadowPass: shadowPassHorizontal, depthLayer: this.depthLayer } ).context( builder.getSharedContext() );
  30592. material.name = 'VSMHorizontal';
  30593. }
  30594. //
  30595. const shadowIntensity = reference( 'intensity', 'float', shadow ).setGroup( renderGroup );
  30596. const normalBias = reference( 'normalBias', 'float', shadow ).setGroup( renderGroup );
  30597. const shadowPosition = lightShadowMatrix( light ).mul( shadowPositionWorld.add( normalWorld.mul( normalBias ) ) );
  30598. const shadowCoord = this.setupShadowCoord( builder, shadowPosition );
  30599. //
  30600. const filterFn = shadow.filterNode || this.getShadowFilterFn( renderer.shadowMap.type ) || null;
  30601. if ( filterFn === null ) {
  30602. throw new Error( 'THREE.WebGPURenderer: Shadow map type not supported yet.' );
  30603. }
  30604. const shadowDepthTexture = ( shadowMapType === VSMShadowMap && shadow.isPointLightShadow !== true ) ? this.vsmShadowMapHorizontal.texture : depthTexture;
  30605. const shadowNode = this.setupShadowFilter( builder, { filterFn, shadowTexture: shadowMap.texture, depthTexture: shadowDepthTexture, shadowCoord, shadow, depthLayer: this.depthLayer } );
  30606. let shadowColor = texture( shadowMap.texture, shadowCoord );
  30607. if ( depthTexture.isArrayTexture ) {
  30608. shadowColor = shadowColor.depth( this.depthLayer );
  30609. }
  30610. const shadowOutput = mix( 1, shadowNode.rgb.mix( shadowColor, 1 ), shadowIntensity.mul( shadowColor.a ) ).toVar();
  30611. this.shadowMap = shadowMap;
  30612. this.shadow.map = shadowMap;
  30613. // Shadow Output + Inspector
  30614. const inspectName = `${ this.light.type } Shadow [ ${ this.light.name || 'ID: ' + this.light.id } ]`;
  30615. return shadowOutput.toInspector( `${ inspectName } / Color`, () => {
  30616. return texture( this.shadowMap.texture );
  30617. } ).toInspector( `${ inspectName } / Depth`, () => {
  30618. return textureLoad( this.shadowMap.depthTexture, uv$1().mul( textureSize( texture( this.shadowMap.depthTexture ) ) ) ).x.oneMinus();
  30619. } );
  30620. }
  30621. /**
  30622. * The implementation performs the setup of the output node. An output is only
  30623. * produces if shadow mapping is globally enabled in the renderer.
  30624. *
  30625. * @param {NodeBuilder} builder - A reference to the current node builder.
  30626. * @return {ShaderCallNodeInternal} The output node.
  30627. */
  30628. setup( builder ) {
  30629. if ( builder.renderer.shadowMap.enabled === false ) return;
  30630. return Fn( () => {
  30631. const currentShadowType = builder.renderer.shadowMap.type;
  30632. if ( this._currentShadowType !== currentShadowType ) {
  30633. this._reset();
  30634. this._node = null;
  30635. }
  30636. let node = this._node;
  30637. this.setupShadowPosition( builder );
  30638. if ( node === null ) {
  30639. this._node = node = this.setupShadow( builder );
  30640. this._currentShadowType = currentShadowType;
  30641. }
  30642. if ( builder.material.shadowNode ) { // @deprecated, r171
  30643. warn( 'NodeMaterial: ".shadowNode" is deprecated. Use ".castShadowNode" instead.' );
  30644. }
  30645. if ( builder.material.receivedShadowNode ) {
  30646. node = builder.material.receivedShadowNode( node );
  30647. }
  30648. return node;
  30649. } )();
  30650. }
  30651. /**
  30652. * Renders the shadow. The logic of this function could be included
  30653. * into {@link ShadowNode#updateShadow} however more specialized shadow
  30654. * nodes might require a custom shadow map rendering. By having a
  30655. * dedicated method, it's easier to overwrite the default behavior.
  30656. *
  30657. * @param {NodeFrame} frame - A reference to the current node frame.
  30658. */
  30659. renderShadow( frame ) {
  30660. const { shadow, shadowMap, light } = this;
  30661. const { renderer, scene } = frame;
  30662. shadow.updateMatrices( light );
  30663. shadowMap.setSize( shadow.mapSize.width, shadow.mapSize.height, shadowMap.depth );
  30664. const currentSceneName = scene.name;
  30665. scene.name = `Shadow Map [ ${ light.name || 'ID: ' + light.id } ]`;
  30666. renderer.render( scene, shadow.camera );
  30667. scene.name = currentSceneName;
  30668. }
  30669. /**
  30670. * Updates the shadow.
  30671. *
  30672. * @param {NodeFrame} frame - A reference to the current node frame.
  30673. */
  30674. updateShadow( frame ) {
  30675. const { shadowMap, light, shadow } = this;
  30676. const { renderer, scene, camera } = frame;
  30677. const shadowType = renderer.shadowMap.type;
  30678. const depthVersion = shadowMap.depthTexture.version;
  30679. this._depthVersionCached = depthVersion;
  30680. const _shadowCameraLayer = shadow.camera.layers.mask;
  30681. if ( ( shadow.camera.layers.mask & 0xFFFFFFFE ) === 0 ) {
  30682. shadow.camera.layers.mask = camera.layers.mask;
  30683. }
  30684. const currentRenderObjectFunction = renderer.getRenderObjectFunction();
  30685. const currentMRT = renderer.getMRT();
  30686. const useVelocity = currentMRT ? currentMRT.has( 'velocity' ) : false;
  30687. _rendererState = resetRendererAndSceneState( renderer, scene, _rendererState );
  30688. scene.overrideMaterial = getShadowMaterial( light );
  30689. renderer.setRenderObjectFunction( getShadowRenderObjectFunction( renderer, shadow, shadowType, useVelocity ) );
  30690. renderer.setClearColor( 0x000000, 0 );
  30691. renderer.setRenderTarget( shadowMap );
  30692. this.renderShadow( frame );
  30693. renderer.setRenderObjectFunction( currentRenderObjectFunction );
  30694. // vsm blur pass
  30695. if ( shadowType === VSMShadowMap && shadow.isPointLightShadow !== true ) {
  30696. this.vsmPass( renderer );
  30697. }
  30698. shadow.camera.layers.mask = _shadowCameraLayer;
  30699. restoreRendererAndSceneState( renderer, scene, _rendererState );
  30700. }
  30701. /**
  30702. * For VSM additional render passes are required.
  30703. *
  30704. * @param {Renderer} renderer - A reference to the current renderer.
  30705. */
  30706. vsmPass( renderer ) {
  30707. const { shadow } = this;
  30708. const depth = this.shadowMap.depth;
  30709. this.vsmShadowMapVertical.setSize( shadow.mapSize.width, shadow.mapSize.height, depth );
  30710. this.vsmShadowMapHorizontal.setSize( shadow.mapSize.width, shadow.mapSize.height, depth );
  30711. renderer.setRenderTarget( this.vsmShadowMapVertical );
  30712. _quadMesh.material = this.vsmMaterialVertical;
  30713. _quadMesh.render( renderer );
  30714. renderer.setRenderTarget( this.vsmShadowMapHorizontal );
  30715. _quadMesh.material = this.vsmMaterialHorizontal;
  30716. _quadMesh.render( renderer );
  30717. }
  30718. /**
  30719. * Frees the internal resources of this shadow node.
  30720. */
  30721. dispose() {
  30722. this._reset();
  30723. super.dispose();
  30724. }
  30725. /**
  30726. * Resets the resouce state of this shadow node.
  30727. *
  30728. * @private
  30729. */
  30730. _reset() {
  30731. this._currentShadowType = null;
  30732. if ( this.shadowMap ) {
  30733. this.shadowMap.dispose();
  30734. this.shadowMap = null;
  30735. }
  30736. if ( this.vsmShadowMapVertical !== null ) {
  30737. this.vsmShadowMapVertical.dispose();
  30738. this.vsmShadowMapVertical = null;
  30739. this.vsmMaterialVertical.dispose();
  30740. this.vsmMaterialVertical = null;
  30741. }
  30742. if ( this.vsmShadowMapHorizontal !== null ) {
  30743. this.vsmShadowMapHorizontal.dispose();
  30744. this.vsmShadowMapHorizontal = null;
  30745. this.vsmMaterialHorizontal.dispose();
  30746. this.vsmMaterialHorizontal = null;
  30747. }
  30748. }
  30749. /**
  30750. * The implementation performs the update of the shadow map if necessary.
  30751. *
  30752. * @param {NodeFrame} frame - A reference to the current node frame.
  30753. */
  30754. updateBefore( frame ) {
  30755. const { shadow } = this;
  30756. let needsUpdate = shadow.needsUpdate || shadow.autoUpdate;
  30757. if ( needsUpdate ) {
  30758. if ( this._cameraFrameId[ frame.camera ] === frame.frameId ) {
  30759. needsUpdate = false;
  30760. }
  30761. this._cameraFrameId[ frame.camera ] = frame.frameId;
  30762. }
  30763. if ( needsUpdate ) {
  30764. this.updateShadow( frame );
  30765. if ( this.shadowMap.depthTexture.version === this._depthVersionCached ) {
  30766. shadow.needsUpdate = false;
  30767. }
  30768. }
  30769. }
  30770. }
  30771. /**
  30772. * Shadow Render Object Function.
  30773. *
  30774. * @function shadowRenderObjectFunction
  30775. * @param {Object3D} object - The 3D object to render.
  30776. * @param {Scene} scene - The scene containing the object.
  30777. * @param {Camera} _camera - The camera used for rendering.
  30778. * @param {BufferGeometry} geometry - The geometry of the object.
  30779. * @param {Material} material - The material of the object.
  30780. * @param {Group} group - The group the object belongs to.
  30781. * @param {...any} params - Additional parameters for rendering.
  30782. */
  30783. /**
  30784. * TSL function for creating an instance of `ShadowNode`.
  30785. *
  30786. * @tsl
  30787. * @function
  30788. * @param {Light} light - The shadow casting light.
  30789. * @param {?LightShadow} [shadow] - The light shadow.
  30790. * @return {ShadowNode} The created shadow node.
  30791. */
  30792. const shadow = ( light, shadow ) => nodeObject( new ShadowNode( light, shadow ) );
  30793. const _clearColor$1 = /*@__PURE__*/ new Color();
  30794. // cubeToUV() maps a 3D direction vector suitable for cube texture mapping to a 2D
  30795. // vector suitable for 2D texture mapping. This code uses the following layout for the
  30796. // 2D texture:
  30797. //
  30798. // xzXZ
  30799. // y Y
  30800. //
  30801. // Y - Positive y direction
  30802. // y - Negative y direction
  30803. // X - Positive x direction
  30804. // x - Negative x direction
  30805. // Z - Positive z direction
  30806. // z - Negative z direction
  30807. //
  30808. // Source and test bed:
  30809. // https://gist.github.com/tschw/da10c43c467ce8afd0c4
  30810. const cubeToUV = /*@__PURE__*/ Fn( ( [ pos, texelSizeY ] ) => {
  30811. const v = pos.toVar();
  30812. // Number of texels to avoid at the edge of each square
  30813. const absV = abs( v );
  30814. // Intersect unit cube
  30815. const scaleToCube = div( 1.0, max$1( absV.x, max$1( absV.y, absV.z ) ) );
  30816. absV.mulAssign( scaleToCube );
  30817. // Apply scale to avoid seams
  30818. // two texels less per square (one texel will do for NEAREST)
  30819. v.mulAssign( scaleToCube.mul( texelSizeY.mul( 2 ).oneMinus() ) );
  30820. // Unwrap
  30821. // space: -1 ... 1 range for each square
  30822. //
  30823. // #X## dim := ( 4 , 2 )
  30824. // # # center := ( 1 , 1 )
  30825. const planar = vec2( v.xy ).toVar();
  30826. const almostATexel = texelSizeY.mul( 1.5 );
  30827. const almostOne = almostATexel.oneMinus();
  30828. If( absV.z.greaterThanEqual( almostOne ), () => {
  30829. If( v.z.greaterThan( 0.0 ), () => {
  30830. planar.x.assign( sub( 4.0, v.x ) );
  30831. } );
  30832. } ).ElseIf( absV.x.greaterThanEqual( almostOne ), () => {
  30833. const signX = sign( v.x );
  30834. planar.x.assign( v.z.mul( signX ).add( signX.mul( 2.0 ) ) );
  30835. } ).ElseIf( absV.y.greaterThanEqual( almostOne ), () => {
  30836. const signY = sign( v.y );
  30837. planar.x.assign( v.x.add( signY.mul( 2.0 ) ).add( 2.0 ) );
  30838. planar.y.assign( v.z.mul( signY ).sub( 2.0 ) );
  30839. } );
  30840. // Transform to UV space
  30841. // scale := 0.5 / dim
  30842. // translate := ( center + 0.5 ) / dim
  30843. return vec2( 0.125, 0.25 ).mul( planar ).add( vec2( 0.375, 0.75 ) ).flipY();
  30844. } ).setLayout( {
  30845. name: 'cubeToUV',
  30846. type: 'vec2',
  30847. inputs: [
  30848. { name: 'pos', type: 'vec3' },
  30849. { name: 'texelSizeY', type: 'float' }
  30850. ]
  30851. } );
  30852. const BasicPointShadowFilter = /*@__PURE__*/ Fn( ( { depthTexture, bd3D, dp, texelSize } ) => {
  30853. return texture( depthTexture, cubeToUV( bd3D, texelSize.y ) ).compare( dp );
  30854. } );
  30855. const PointShadowFilter = /*@__PURE__*/ Fn( ( { depthTexture, bd3D, dp, texelSize, shadow } ) => {
  30856. const radius = reference( 'radius', 'float', shadow ).setGroup( renderGroup );
  30857. const offset = vec2( -1, 1.0 ).mul( radius ).mul( texelSize.y );
  30858. return texture( depthTexture, cubeToUV( bd3D.add( offset.xyy ), texelSize.y ) ).compare( dp )
  30859. .add( texture( depthTexture, cubeToUV( bd3D.add( offset.yyy ), texelSize.y ) ).compare( dp ) )
  30860. .add( texture( depthTexture, cubeToUV( bd3D.add( offset.xyx ), texelSize.y ) ).compare( dp ) )
  30861. .add( texture( depthTexture, cubeToUV( bd3D.add( offset.yyx ), texelSize.y ) ).compare( dp ) )
  30862. .add( texture( depthTexture, cubeToUV( bd3D, texelSize.y ) ).compare( dp ) )
  30863. .add( texture( depthTexture, cubeToUV( bd3D.add( offset.xxy ), texelSize.y ) ).compare( dp ) )
  30864. .add( texture( depthTexture, cubeToUV( bd3D.add( offset.yxy ), texelSize.y ) ).compare( dp ) )
  30865. .add( texture( depthTexture, cubeToUV( bd3D.add( offset.xxx ), texelSize.y ) ).compare( dp ) )
  30866. .add( texture( depthTexture, cubeToUV( bd3D.add( offset.yxx ), texelSize.y ) ).compare( dp ) )
  30867. .mul( 1.0 / 9.0 );
  30868. } );
  30869. const pointShadowFilter = /*@__PURE__*/ Fn( ( { filterFn, depthTexture, shadowCoord, shadow } ) => {
  30870. // for point lights, the uniform @vShadowCoord is re-purposed to hold
  30871. // the vector from the light to the world-space position of the fragment.
  30872. const lightToPosition = shadowCoord.xyz.toVar();
  30873. const lightToPositionLength = lightToPosition.length();
  30874. const cameraNearLocal = uniform( 'float' ).setGroup( renderGroup ).onRenderUpdate( () => shadow.camera.near );
  30875. const cameraFarLocal = uniform( 'float' ).setGroup( renderGroup ).onRenderUpdate( () => shadow.camera.far );
  30876. const bias = reference( 'bias', 'float', shadow ).setGroup( renderGroup );
  30877. const mapSize = uniform( shadow.mapSize ).setGroup( renderGroup );
  30878. const result = float( 1.0 ).toVar();
  30879. If( lightToPositionLength.sub( cameraFarLocal ).lessThanEqual( 0.0 ).and( lightToPositionLength.sub( cameraNearLocal ).greaterThanEqual( 0.0 ) ), () => {
  30880. // dp = normalized distance from light to fragment position
  30881. const dp = lightToPositionLength.sub( cameraNearLocal ).div( cameraFarLocal.sub( cameraNearLocal ) ).toVar(); // need to clamp?
  30882. dp.addAssign( bias );
  30883. // bd3D = base direction 3D
  30884. const bd3D = lightToPosition.normalize();
  30885. const texelSize = vec2( 1.0 ).div( mapSize.mul( vec2( 4.0, 2.0 ) ) );
  30886. // percentage-closer filtering
  30887. result.assign( filterFn( { depthTexture, bd3D, dp, texelSize, shadow } ) );
  30888. } );
  30889. return result;
  30890. } );
  30891. const _viewport = /*@__PURE__*/ new Vector4();
  30892. const _viewportSize = /*@__PURE__*/ new Vector2();
  30893. const _shadowMapSize = /*@__PURE__*/ new Vector2();
  30894. /**
  30895. * Represents the shadow implementation for point light nodes.
  30896. *
  30897. * @augments ShadowNode
  30898. */
  30899. class PointShadowNode extends ShadowNode {
  30900. static get type() {
  30901. return 'PointShadowNode';
  30902. }
  30903. /**
  30904. * Constructs a new point shadow node.
  30905. *
  30906. * @param {PointLight} light - The shadow casting point light.
  30907. * @param {?PointLightShadow} [shadow=null] - An optional point light shadow.
  30908. */
  30909. constructor( light, shadow = null ) {
  30910. super( light, shadow );
  30911. }
  30912. /**
  30913. * Overwrites the default implementation to return point light shadow specific
  30914. * filtering functions.
  30915. *
  30916. * @param {number} type - The shadow type.
  30917. * @return {Function} The filtering function.
  30918. */
  30919. getShadowFilterFn( type ) {
  30920. return type === BasicShadowMap ? BasicPointShadowFilter : PointShadowFilter;
  30921. }
  30922. /**
  30923. * Overwrites the default implementation so the unaltered shadow position is used.
  30924. *
  30925. * @param {NodeBuilder} builder - A reference to the current node builder.
  30926. * @param {Node<vec3>} shadowPosition - A node representing the shadow position.
  30927. * @return {Node<vec3>} The shadow coordinates.
  30928. */
  30929. setupShadowCoord( builder, shadowPosition ) {
  30930. return shadowPosition;
  30931. }
  30932. /**
  30933. * Overwrites the default implementation to only use point light specific
  30934. * shadow filter functions.
  30935. *
  30936. * @param {NodeBuilder} builder - A reference to the current node builder.
  30937. * @param {Object} inputs - A configuration object that defines the shadow filtering.
  30938. * @param {Function} inputs.filterFn - This function defines the filtering type of the shadow map e.g. PCF.
  30939. * @param {Texture} inputs.shadowTexture - A reference to the shadow map's texture.
  30940. * @param {DepthTexture} inputs.depthTexture - A reference to the shadow map's texture data.
  30941. * @param {Node<vec3>} inputs.shadowCoord - Shadow coordinates which are used to sample from the shadow map.
  30942. * @param {LightShadow} inputs.shadow - The light shadow.
  30943. * @return {Node<float>} The result node of the shadow filtering.
  30944. */
  30945. setupShadowFilter( builder, { filterFn, shadowTexture, depthTexture, shadowCoord, shadow } ) {
  30946. return pointShadowFilter( { filterFn, shadowTexture, depthTexture, shadowCoord, shadow } );
  30947. }
  30948. /**
  30949. * Overwrites the default implementation with point light specific
  30950. * rendering code.
  30951. *
  30952. * @param {NodeFrame} frame - A reference to the current node frame.
  30953. */
  30954. renderShadow( frame ) {
  30955. const { shadow, shadowMap, light } = this;
  30956. const { renderer, scene } = frame;
  30957. const shadowFrameExtents = shadow.getFrameExtents();
  30958. _shadowMapSize.copy( shadow.mapSize );
  30959. _shadowMapSize.multiply( shadowFrameExtents );
  30960. shadowMap.setSize( _shadowMapSize.width, _shadowMapSize.height );
  30961. _viewportSize.copy( shadow.mapSize );
  30962. //
  30963. const previousAutoClear = renderer.autoClear;
  30964. const previousClearColor = renderer.getClearColor( _clearColor$1 );
  30965. const previousClearAlpha = renderer.getClearAlpha();
  30966. renderer.autoClear = false;
  30967. renderer.setClearColor( shadow.clearColor, shadow.clearAlpha );
  30968. renderer.clear();
  30969. const viewportCount = shadow.getViewportCount();
  30970. for ( let vp = 0; vp < viewportCount; vp ++ ) {
  30971. const viewport = shadow.getViewport( vp );
  30972. const x = _viewportSize.x * viewport.x;
  30973. const y = _shadowMapSize.y - _viewportSize.y - ( _viewportSize.y * viewport.y );
  30974. _viewport.set(
  30975. x,
  30976. y,
  30977. _viewportSize.x * viewport.z,
  30978. _viewportSize.y * viewport.w
  30979. );
  30980. shadowMap.viewport.copy( _viewport );
  30981. shadow.updateMatrices( light, vp );
  30982. const currentSceneName = scene.name;
  30983. scene.name = `Point Light Shadow [ ${ light.name || 'ID: ' + light.id } ] - Face ${ vp + 1 }`;
  30984. renderer.render( scene, shadow.camera );
  30985. scene.name = currentSceneName;
  30986. }
  30987. //
  30988. renderer.autoClear = previousAutoClear;
  30989. renderer.setClearColor( previousClearColor, previousClearAlpha );
  30990. }
  30991. }
  30992. /**
  30993. * TSL function for creating an instance of `PointShadowNode`.
  30994. *
  30995. * @tsl
  30996. * @function
  30997. * @param {PointLight} light - The shadow casting point light.
  30998. * @param {?PointLightShadow} [shadow=null] - An optional point light shadow.
  30999. * @return {PointShadowNode} The created point shadow node.
  31000. */
  31001. const pointShadow = ( light, shadow ) => nodeObject( new PointShadowNode( light, shadow ) );
  31002. /**
  31003. * Base class for analytic light nodes.
  31004. *
  31005. * @augments LightingNode
  31006. */
  31007. class AnalyticLightNode extends LightingNode {
  31008. static get type() {
  31009. return 'AnalyticLightNode';
  31010. }
  31011. /**
  31012. * Constructs a new analytic light node.
  31013. *
  31014. * @param {?Light} [light=null] - The light source.
  31015. */
  31016. constructor( light = null ) {
  31017. super();
  31018. /**
  31019. * The light source.
  31020. *
  31021. * @type {?Light}
  31022. * @default null
  31023. */
  31024. this.light = light;
  31025. /**
  31026. * The light's color value.
  31027. *
  31028. * @type {Color}
  31029. */
  31030. this.color = new Color();
  31031. /**
  31032. * The light's color node. Points to `colorNode` of the light source, if set. Otherwise
  31033. * it creates a uniform node based on {@link AnalyticLightNode#color}.
  31034. *
  31035. * @type {Node}
  31036. */
  31037. this.colorNode = ( light && light.colorNode ) || uniform( this.color ).setGroup( renderGroup );
  31038. /**
  31039. * This property is used to retain a reference to the original value of {@link AnalyticLightNode#colorNode}.
  31040. * The final color node is represented by a different node when using shadows.
  31041. *
  31042. * @type {?Node}
  31043. * @default null
  31044. */
  31045. this.baseColorNode = null;
  31046. /**
  31047. * Represents the light's shadow.
  31048. *
  31049. * @type {?ShadowNode}
  31050. * @default null
  31051. */
  31052. this.shadowNode = null;
  31053. /**
  31054. * Represents the light's shadow color.
  31055. *
  31056. * @type {?Node}
  31057. * @default null
  31058. */
  31059. this.shadowColorNode = null;
  31060. /**
  31061. * This flag can be used for type testing.
  31062. *
  31063. * @type {boolean}
  31064. * @readonly
  31065. * @default true
  31066. */
  31067. this.isAnalyticLightNode = true;
  31068. /**
  31069. * Overwritten since analytic light nodes are updated
  31070. * once per frame.
  31071. *
  31072. * @type {string}
  31073. * @default 'frame'
  31074. */
  31075. this.updateType = NodeUpdateType.FRAME;
  31076. }
  31077. getHash() {
  31078. return this.light.uuid;
  31079. }
  31080. /**
  31081. * Returns a node representing a direction vector which points from the current
  31082. * position in view space to the light's position in view space.
  31083. *
  31084. * @param {NodeBuilder} builder - The builder object used for setting up the light.
  31085. * @return {Node<vec3>} The light vector node.
  31086. */
  31087. getLightVector( builder ) {
  31088. return lightViewPosition( this.light ).sub( builder.context.positionView || positionView );
  31089. }
  31090. /**
  31091. * Sets up the direct lighting for the analytic light node.
  31092. *
  31093. * @abstract
  31094. * @param {NodeBuilder} builder - The builder object used for setting up the light.
  31095. * @return {Object|undefined} The direct light data (color and direction).
  31096. */
  31097. setupDirect( /*builder*/ ) { }
  31098. /**
  31099. * Sets up the direct rect area lighting for the analytic light node.
  31100. *
  31101. * @abstract
  31102. * @param {NodeBuilder} builder - The builder object used for setting up the light.
  31103. * @return {Object|undefined} The direct rect area light data.
  31104. */
  31105. setupDirectRectArea( /*builder*/ ) { }
  31106. /**
  31107. * Setups the shadow node for this light. The method exists so concrete light classes
  31108. * can setup different types of shadow nodes.
  31109. *
  31110. * @return {ShadowNode} The created shadow node.
  31111. */
  31112. setupShadowNode() {
  31113. return shadow( this.light );
  31114. }
  31115. /**
  31116. * Setups the shadow for this light. This method is only executed if the light
  31117. * cast shadows and the current build object receives shadows. It incorporates
  31118. * shadows into the lighting computation.
  31119. *
  31120. * @param {NodeBuilder} builder - The current node builder.
  31121. */
  31122. setupShadow( builder ) {
  31123. const { renderer } = builder;
  31124. if ( renderer.shadowMap.enabled === false ) return;
  31125. let shadowColorNode = this.shadowColorNode;
  31126. if ( shadowColorNode === null ) {
  31127. const customShadowNode = this.light.shadow.shadowNode;
  31128. let shadowNode;
  31129. if ( customShadowNode !== undefined ) {
  31130. shadowNode = nodeObject( customShadowNode );
  31131. } else {
  31132. shadowNode = this.setupShadowNode();
  31133. }
  31134. this.shadowNode = shadowNode;
  31135. this.shadowColorNode = shadowColorNode = this.colorNode.mul( shadowNode );
  31136. this.baseColorNode = this.colorNode;
  31137. }
  31138. //
  31139. this.colorNode = shadowColorNode;
  31140. }
  31141. /**
  31142. * Unlike most other nodes, lighting nodes do not return a output node in {@link Node#setup}.
  31143. * The main purpose of lighting nodes is to configure the current {@link LightingModel} and/or
  31144. * invocate the respective interface methods.
  31145. *
  31146. * @param {NodeBuilder} builder - The current node builder.
  31147. */
  31148. setup( builder ) {
  31149. this.colorNode = this.baseColorNode || this.colorNode;
  31150. if ( this.light.castShadow ) {
  31151. if ( builder.object.receiveShadow ) {
  31152. this.setupShadow( builder );
  31153. }
  31154. } else if ( this.shadowNode !== null ) {
  31155. this.shadowNode.dispose();
  31156. this.shadowNode = null;
  31157. this.shadowColorNode = null;
  31158. }
  31159. const directLightData = this.setupDirect( builder );
  31160. const directRectAreaLightData = this.setupDirectRectArea( builder );
  31161. if ( directLightData ) {
  31162. builder.lightsNode.setupDirectLight( builder, this, directLightData );
  31163. }
  31164. if ( directRectAreaLightData ) {
  31165. builder.lightsNode.setupDirectRectAreaLight( builder, this, directRectAreaLightData );
  31166. }
  31167. }
  31168. /**
  31169. * The update method is used to update light uniforms per frame.
  31170. * Potentially overwritten in concrete light nodes to update light
  31171. * specific uniforms.
  31172. *
  31173. * @param {NodeFrame} frame - A reference to the current node frame.
  31174. */
  31175. update( /*frame*/ ) {
  31176. const { light } = this;
  31177. this.color.copy( light.color ).multiplyScalar( light.intensity );
  31178. }
  31179. }
  31180. /**
  31181. * Represents a `discard` shader operation in TSL.
  31182. *
  31183. * @method
  31184. * @param {Object} inputs - The input parameter object.
  31185. * @param {Node<float>} inputs.lightDistance - The distance of the light's position to the current fragment position.
  31186. * @param {Node<float>} inputs.cutoffDistance - The light's cutoff distance.
  31187. * @param {Node<float>} inputs.decayExponent - The light's decay exponent.
  31188. * @return {Node<float>} The distance falloff.
  31189. */
  31190. const getDistanceAttenuation = /*@__PURE__*/ Fn( ( { lightDistance, cutoffDistance, decayExponent } ) => {
  31191. // based upon Frostbite 3 Moving to Physically-based Rendering
  31192. // page 32, equation 26: E[window1]
  31193. // https://seblagarde.files.wordpress.com/2015/07/course_notes_moving_frostbite_to_pbr_v32.pdf
  31194. const distanceFalloff = lightDistance.pow( decayExponent ).max( 0.01 ).reciprocal();
  31195. return cutoffDistance.greaterThan( 0 ).select(
  31196. distanceFalloff.mul( lightDistance.div( cutoffDistance ).pow4().oneMinus().clamp().pow2() ),
  31197. distanceFalloff
  31198. );
  31199. } ); // validated
  31200. const directPointLight = ( { color, lightVector, cutoffDistance, decayExponent } ) => {
  31201. const lightDirection = lightVector.normalize();
  31202. const lightDistance = lightVector.length();
  31203. const attenuation = getDistanceAttenuation( {
  31204. lightDistance,
  31205. cutoffDistance,
  31206. decayExponent
  31207. } );
  31208. const lightColor = color.mul( attenuation );
  31209. return { lightDirection, lightColor };
  31210. };
  31211. /**
  31212. * Module for representing point lights as nodes.
  31213. *
  31214. * @augments AnalyticLightNode
  31215. */
  31216. class PointLightNode extends AnalyticLightNode {
  31217. static get type() {
  31218. return 'PointLightNode';
  31219. }
  31220. /**
  31221. * Constructs a new point light node.
  31222. *
  31223. * @param {?PointLight} [light=null] - The point light source.
  31224. */
  31225. constructor( light = null ) {
  31226. super( light );
  31227. /**
  31228. * Uniform node representing the cutoff distance.
  31229. *
  31230. * @type {UniformNode<float>}
  31231. */
  31232. this.cutoffDistanceNode = uniform( 0 ).setGroup( renderGroup );
  31233. /**
  31234. * Uniform node representing the decay exponent.
  31235. *
  31236. * @type {UniformNode<float>}
  31237. */
  31238. this.decayExponentNode = uniform( 2 ).setGroup( renderGroup );
  31239. }
  31240. /**
  31241. * Overwritten to updated point light specific uniforms.
  31242. *
  31243. * @param {NodeFrame} frame - A reference to the current node frame.
  31244. */
  31245. update( frame ) {
  31246. const { light } = this;
  31247. super.update( frame );
  31248. this.cutoffDistanceNode.value = light.distance;
  31249. this.decayExponentNode.value = light.decay;
  31250. }
  31251. /**
  31252. * Overwritten to setup point light specific shadow.
  31253. *
  31254. * @return {PointShadowNode}
  31255. */
  31256. setupShadowNode() {
  31257. return pointShadow( this.light );
  31258. }
  31259. setupDirect( builder ) {
  31260. return directPointLight( {
  31261. color: this.colorNode,
  31262. lightVector: this.getLightVector( builder ),
  31263. cutoffDistance: this.cutoffDistanceNode,
  31264. decayExponent: this.decayExponentNode
  31265. } );
  31266. }
  31267. }
  31268. /**
  31269. * Creates a 2x2 checkerboard pattern that can be used as procedural texture data.
  31270. *
  31271. * @tsl
  31272. * @function
  31273. * @param {Node<vec2>} coord - The uv coordinates.
  31274. * @return {Node<float>} The result data.
  31275. */
  31276. const checker = /*@__PURE__*/ Fn( ( [ coord = uv$1() ] ) => {
  31277. const uv = coord.mul( 2.0 );
  31278. const cx = uv.x.floor();
  31279. const cy = uv.y.floor();
  31280. const result = cx.add( cy ).mod( 2.0 );
  31281. return result.sign();
  31282. } );
  31283. /**
  31284. * Generates a circle based on the uv coordinates.
  31285. *
  31286. * @tsl
  31287. * @function
  31288. * @param {Node<vec2>} coord - The uv to generate the circle.
  31289. * @return {Node<float>} The circle shape.
  31290. */
  31291. const shapeCircle = Fn( ( [ coord = uv$1() ], { renderer, material } ) => {
  31292. const len2 = lengthSq( coord.mul( 2 ).sub( 1 ) );
  31293. let alpha;
  31294. if ( material.alphaToCoverage && renderer.currentSamples > 0 ) {
  31295. const dlen = float( len2.fwidth() ).toVar();
  31296. alpha = smoothstep( dlen.oneMinus(), dlen.add( 1 ), len2 ).oneMinus();
  31297. } else {
  31298. alpha = select( len2.greaterThan( 1.0 ), 0, 1 );
  31299. }
  31300. return alpha;
  31301. } );
  31302. // Three.js Transpiler
  31303. // https://raw.githubusercontent.com/AcademySoftwareFoundation/MaterialX/main/libraries/stdlib/genglsl/lib/mx_noise.glsl
  31304. const mx_select = /*@__PURE__*/ Fn( ( [ b_immutable, t_immutable, f_immutable ] ) => {
  31305. const f = float( f_immutable ).toVar();
  31306. const t = float( t_immutable ).toVar();
  31307. const b = bool( b_immutable ).toVar();
  31308. return select( b, t, f );
  31309. } ).setLayout( {
  31310. name: 'mx_select',
  31311. type: 'float',
  31312. inputs: [
  31313. { name: 'b', type: 'bool' },
  31314. { name: 't', type: 'float' },
  31315. { name: 'f', type: 'float' }
  31316. ]
  31317. } );
  31318. const mx_negate_if = /*@__PURE__*/ Fn( ( [ val_immutable, b_immutable ] ) => {
  31319. const b = bool( b_immutable ).toVar();
  31320. const val = float( val_immutable ).toVar();
  31321. return select( b, val.negate(), val );
  31322. } ).setLayout( {
  31323. name: 'mx_negate_if',
  31324. type: 'float',
  31325. inputs: [
  31326. { name: 'val', type: 'float' },
  31327. { name: 'b', type: 'bool' }
  31328. ]
  31329. } );
  31330. const mx_floor = /*@__PURE__*/ Fn( ( [ x_immutable ] ) => {
  31331. const x = float( x_immutable ).toVar();
  31332. return int( floor( x ) );
  31333. } ).setLayout( {
  31334. name: 'mx_floor',
  31335. type: 'int',
  31336. inputs: [
  31337. { name: 'x', type: 'float' }
  31338. ]
  31339. } );
  31340. const mx_floorfrac = /*@__PURE__*/ Fn( ( [ x_immutable, i ] ) => {
  31341. const x = float( x_immutable ).toVar();
  31342. i.assign( mx_floor( x ) );
  31343. return x.sub( float( i ) );
  31344. } );
  31345. const mx_bilerp_0 = /*@__PURE__*/ Fn( ( [ v0_immutable, v1_immutable, v2_immutable, v3_immutable, s_immutable, t_immutable ] ) => {
  31346. const t = float( t_immutable ).toVar();
  31347. const s = float( s_immutable ).toVar();
  31348. const v3 = float( v3_immutable ).toVar();
  31349. const v2 = float( v2_immutable ).toVar();
  31350. const v1 = float( v1_immutable ).toVar();
  31351. const v0 = float( v0_immutable ).toVar();
  31352. const s1 = float( sub( 1.0, s ) ).toVar();
  31353. return sub( 1.0, t ).mul( v0.mul( s1 ).add( v1.mul( s ) ) ).add( t.mul( v2.mul( s1 ).add( v3.mul( s ) ) ) );
  31354. } ).setLayout( {
  31355. name: 'mx_bilerp_0',
  31356. type: 'float',
  31357. inputs: [
  31358. { name: 'v0', type: 'float' },
  31359. { name: 'v1', type: 'float' },
  31360. { name: 'v2', type: 'float' },
  31361. { name: 'v3', type: 'float' },
  31362. { name: 's', type: 'float' },
  31363. { name: 't', type: 'float' }
  31364. ]
  31365. } );
  31366. const mx_bilerp_1 = /*@__PURE__*/ Fn( ( [ v0_immutable, v1_immutable, v2_immutable, v3_immutable, s_immutable, t_immutable ] ) => {
  31367. const t = float( t_immutable ).toVar();
  31368. const s = float( s_immutable ).toVar();
  31369. const v3 = vec3( v3_immutable ).toVar();
  31370. const v2 = vec3( v2_immutable ).toVar();
  31371. const v1 = vec3( v1_immutable ).toVar();
  31372. const v0 = vec3( v0_immutable ).toVar();
  31373. const s1 = float( sub( 1.0, s ) ).toVar();
  31374. return sub( 1.0, t ).mul( v0.mul( s1 ).add( v1.mul( s ) ) ).add( t.mul( v2.mul( s1 ).add( v3.mul( s ) ) ) );
  31375. } ).setLayout( {
  31376. name: 'mx_bilerp_1',
  31377. type: 'vec3',
  31378. inputs: [
  31379. { name: 'v0', type: 'vec3' },
  31380. { name: 'v1', type: 'vec3' },
  31381. { name: 'v2', type: 'vec3' },
  31382. { name: 'v3', type: 'vec3' },
  31383. { name: 's', type: 'float' },
  31384. { name: 't', type: 'float' }
  31385. ]
  31386. } );
  31387. const mx_bilerp = /*@__PURE__*/ overloadingFn( [ mx_bilerp_0, mx_bilerp_1 ] );
  31388. 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 ] ) => {
  31389. const r = float( r_immutable ).toVar();
  31390. const t = float( t_immutable ).toVar();
  31391. const s = float( s_immutable ).toVar();
  31392. const v7 = float( v7_immutable ).toVar();
  31393. const v6 = float( v6_immutable ).toVar();
  31394. const v5 = float( v5_immutable ).toVar();
  31395. const v4 = float( v4_immutable ).toVar();
  31396. const v3 = float( v3_immutable ).toVar();
  31397. const v2 = float( v2_immutable ).toVar();
  31398. const v1 = float( v1_immutable ).toVar();
  31399. const v0 = float( v0_immutable ).toVar();
  31400. const s1 = float( sub( 1.0, s ) ).toVar();
  31401. const t1 = float( sub( 1.0, t ) ).toVar();
  31402. const r1 = float( sub( 1.0, r ) ).toVar();
  31403. 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 ) ) ) ) ) );
  31404. } ).setLayout( {
  31405. name: 'mx_trilerp_0',
  31406. type: 'float',
  31407. inputs: [
  31408. { name: 'v0', type: 'float' },
  31409. { name: 'v1', type: 'float' },
  31410. { name: 'v2', type: 'float' },
  31411. { name: 'v3', type: 'float' },
  31412. { name: 'v4', type: 'float' },
  31413. { name: 'v5', type: 'float' },
  31414. { name: 'v6', type: 'float' },
  31415. { name: 'v7', type: 'float' },
  31416. { name: 's', type: 'float' },
  31417. { name: 't', type: 'float' },
  31418. { name: 'r', type: 'float' }
  31419. ]
  31420. } );
  31421. 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 ] ) => {
  31422. const r = float( r_immutable ).toVar();
  31423. const t = float( t_immutable ).toVar();
  31424. const s = float( s_immutable ).toVar();
  31425. const v7 = vec3( v7_immutable ).toVar();
  31426. const v6 = vec3( v6_immutable ).toVar();
  31427. const v5 = vec3( v5_immutable ).toVar();
  31428. const v4 = vec3( v4_immutable ).toVar();
  31429. const v3 = vec3( v3_immutable ).toVar();
  31430. const v2 = vec3( v2_immutable ).toVar();
  31431. const v1 = vec3( v1_immutable ).toVar();
  31432. const v0 = vec3( v0_immutable ).toVar();
  31433. const s1 = float( sub( 1.0, s ) ).toVar();
  31434. const t1 = float( sub( 1.0, t ) ).toVar();
  31435. const r1 = float( sub( 1.0, r ) ).toVar();
  31436. 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 ) ) ) ) ) );
  31437. } ).setLayout( {
  31438. name: 'mx_trilerp_1',
  31439. type: 'vec3',
  31440. inputs: [
  31441. { name: 'v0', type: 'vec3' },
  31442. { name: 'v1', type: 'vec3' },
  31443. { name: 'v2', type: 'vec3' },
  31444. { name: 'v3', type: 'vec3' },
  31445. { name: 'v4', type: 'vec3' },
  31446. { name: 'v5', type: 'vec3' },
  31447. { name: 'v6', type: 'vec3' },
  31448. { name: 'v7', type: 'vec3' },
  31449. { name: 's', type: 'float' },
  31450. { name: 't', type: 'float' },
  31451. { name: 'r', type: 'float' }
  31452. ]
  31453. } );
  31454. const mx_trilerp = /*@__PURE__*/ overloadingFn( [ mx_trilerp_0, mx_trilerp_1 ] );
  31455. const mx_gradient_float_0 = /*@__PURE__*/ Fn( ( [ hash_immutable, x_immutable, y_immutable ] ) => {
  31456. const y = float( y_immutable ).toVar();
  31457. const x = float( x_immutable ).toVar();
  31458. const hash = uint( hash_immutable ).toVar();
  31459. const h = uint( hash.bitAnd( uint( 7 ) ) ).toVar();
  31460. const u = float( mx_select( h.lessThan( uint( 4 ) ), x, y ) ).toVar();
  31461. const v = float( mul( 2.0, mx_select( h.lessThan( uint( 4 ) ), y, x ) ) ).toVar();
  31462. return mx_negate_if( u, bool( h.bitAnd( uint( 1 ) ) ) ).add( mx_negate_if( v, bool( h.bitAnd( uint( 2 ) ) ) ) );
  31463. } ).setLayout( {
  31464. name: 'mx_gradient_float_0',
  31465. type: 'float',
  31466. inputs: [
  31467. { name: 'hash', type: 'uint' },
  31468. { name: 'x', type: 'float' },
  31469. { name: 'y', type: 'float' }
  31470. ]
  31471. } );
  31472. const mx_gradient_float_1 = /*@__PURE__*/ Fn( ( [ hash_immutable, x_immutable, y_immutable, z_immutable ] ) => {
  31473. const z = float( z_immutable ).toVar();
  31474. const y = float( y_immutable ).toVar();
  31475. const x = float( x_immutable ).toVar();
  31476. const hash = uint( hash_immutable ).toVar();
  31477. const h = uint( hash.bitAnd( uint( 15 ) ) ).toVar();
  31478. const u = float( mx_select( h.lessThan( uint( 8 ) ), x, y ) ).toVar();
  31479. const v = float( mx_select( h.lessThan( uint( 4 ) ), y, mx_select( h.equal( uint( 12 ) ).or( h.equal( uint( 14 ) ) ), x, z ) ) ).toVar();
  31480. return mx_negate_if( u, bool( h.bitAnd( uint( 1 ) ) ) ).add( mx_negate_if( v, bool( h.bitAnd( uint( 2 ) ) ) ) );
  31481. } ).setLayout( {
  31482. name: 'mx_gradient_float_1',
  31483. type: 'float',
  31484. inputs: [
  31485. { name: 'hash', type: 'uint' },
  31486. { name: 'x', type: 'float' },
  31487. { name: 'y', type: 'float' },
  31488. { name: 'z', type: 'float' }
  31489. ]
  31490. } );
  31491. const mx_gradient_float = /*@__PURE__*/ overloadingFn( [ mx_gradient_float_0, mx_gradient_float_1 ] );
  31492. const mx_gradient_vec3_0 = /*@__PURE__*/ Fn( ( [ hash_immutable, x_immutable, y_immutable ] ) => {
  31493. const y = float( y_immutable ).toVar();
  31494. const x = float( x_immutable ).toVar();
  31495. const hash = uvec3( hash_immutable ).toVar();
  31496. return vec3( mx_gradient_float( hash.x, x, y ), mx_gradient_float( hash.y, x, y ), mx_gradient_float( hash.z, x, y ) );
  31497. } ).setLayout( {
  31498. name: 'mx_gradient_vec3_0',
  31499. type: 'vec3',
  31500. inputs: [
  31501. { name: 'hash', type: 'uvec3' },
  31502. { name: 'x', type: 'float' },
  31503. { name: 'y', type: 'float' }
  31504. ]
  31505. } );
  31506. const mx_gradient_vec3_1 = /*@__PURE__*/ Fn( ( [ hash_immutable, x_immutable, y_immutable, z_immutable ] ) => {
  31507. const z = float( z_immutable ).toVar();
  31508. const y = float( y_immutable ).toVar();
  31509. const x = float( x_immutable ).toVar();
  31510. const hash = uvec3( hash_immutable ).toVar();
  31511. 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 ) );
  31512. } ).setLayout( {
  31513. name: 'mx_gradient_vec3_1',
  31514. type: 'vec3',
  31515. inputs: [
  31516. { name: 'hash', type: 'uvec3' },
  31517. { name: 'x', type: 'float' },
  31518. { name: 'y', type: 'float' },
  31519. { name: 'z', type: 'float' }
  31520. ]
  31521. } );
  31522. const mx_gradient_vec3 = /*@__PURE__*/ overloadingFn( [ mx_gradient_vec3_0, mx_gradient_vec3_1 ] );
  31523. const mx_gradient_scale2d_0 = /*@__PURE__*/ Fn( ( [ v_immutable ] ) => {
  31524. const v = float( v_immutable ).toVar();
  31525. return mul( 0.6616, v );
  31526. } ).setLayout( {
  31527. name: 'mx_gradient_scale2d_0',
  31528. type: 'float',
  31529. inputs: [
  31530. { name: 'v', type: 'float' }
  31531. ]
  31532. } );
  31533. const mx_gradient_scale3d_0 = /*@__PURE__*/ Fn( ( [ v_immutable ] ) => {
  31534. const v = float( v_immutable ).toVar();
  31535. return mul( 0.9820, v );
  31536. } ).setLayout( {
  31537. name: 'mx_gradient_scale3d_0',
  31538. type: 'float',
  31539. inputs: [
  31540. { name: 'v', type: 'float' }
  31541. ]
  31542. } );
  31543. const mx_gradient_scale2d_1 = /*@__PURE__*/ Fn( ( [ v_immutable ] ) => {
  31544. const v = vec3( v_immutable ).toVar();
  31545. return mul( 0.6616, v );
  31546. } ).setLayout( {
  31547. name: 'mx_gradient_scale2d_1',
  31548. type: 'vec3',
  31549. inputs: [
  31550. { name: 'v', type: 'vec3' }
  31551. ]
  31552. } );
  31553. const mx_gradient_scale2d = /*@__PURE__*/ overloadingFn( [ mx_gradient_scale2d_0, mx_gradient_scale2d_1 ] );
  31554. const mx_gradient_scale3d_1 = /*@__PURE__*/ Fn( ( [ v_immutable ] ) => {
  31555. const v = vec3( v_immutable ).toVar();
  31556. return mul( 0.9820, v );
  31557. } ).setLayout( {
  31558. name: 'mx_gradient_scale3d_1',
  31559. type: 'vec3',
  31560. inputs: [
  31561. { name: 'v', type: 'vec3' }
  31562. ]
  31563. } );
  31564. const mx_gradient_scale3d = /*@__PURE__*/ overloadingFn( [ mx_gradient_scale3d_0, mx_gradient_scale3d_1 ] );
  31565. const mx_rotl32 = /*@__PURE__*/ Fn( ( [ x_immutable, k_immutable ] ) => {
  31566. const k = int( k_immutable ).toVar();
  31567. const x = uint( x_immutable ).toVar();
  31568. return x.shiftLeft( k ).bitOr( x.shiftRight( int( 32 ).sub( k ) ) );
  31569. } ).setLayout( {
  31570. name: 'mx_rotl32',
  31571. type: 'uint',
  31572. inputs: [
  31573. { name: 'x', type: 'uint' },
  31574. { name: 'k', type: 'int' }
  31575. ]
  31576. } );
  31577. const mx_bjmix = /*@__PURE__*/ Fn( ( [ a, b, c ] ) => {
  31578. a.subAssign( c );
  31579. a.bitXorAssign( mx_rotl32( c, int( 4 ) ) );
  31580. c.addAssign( b );
  31581. b.subAssign( a );
  31582. b.bitXorAssign( mx_rotl32( a, int( 6 ) ) );
  31583. a.addAssign( c );
  31584. c.subAssign( b );
  31585. c.bitXorAssign( mx_rotl32( b, int( 8 ) ) );
  31586. b.addAssign( a );
  31587. a.subAssign( c );
  31588. a.bitXorAssign( mx_rotl32( c, int( 16 ) ) );
  31589. c.addAssign( b );
  31590. b.subAssign( a );
  31591. b.bitXorAssign( mx_rotl32( a, int( 19 ) ) );
  31592. a.addAssign( c );
  31593. c.subAssign( b );
  31594. c.bitXorAssign( mx_rotl32( b, int( 4 ) ) );
  31595. b.addAssign( a );
  31596. } );
  31597. const mx_bjfinal = /*@__PURE__*/ Fn( ( [ a_immutable, b_immutable, c_immutable ] ) => {
  31598. const c = uint( c_immutable ).toVar();
  31599. const b = uint( b_immutable ).toVar();
  31600. const a = uint( a_immutable ).toVar();
  31601. c.bitXorAssign( b );
  31602. c.subAssign( mx_rotl32( b, int( 14 ) ) );
  31603. a.bitXorAssign( c );
  31604. a.subAssign( mx_rotl32( c, int( 11 ) ) );
  31605. b.bitXorAssign( a );
  31606. b.subAssign( mx_rotl32( a, int( 25 ) ) );
  31607. c.bitXorAssign( b );
  31608. c.subAssign( mx_rotl32( b, int( 16 ) ) );
  31609. a.bitXorAssign( c );
  31610. a.subAssign( mx_rotl32( c, int( 4 ) ) );
  31611. b.bitXorAssign( a );
  31612. b.subAssign( mx_rotl32( a, int( 14 ) ) );
  31613. c.bitXorAssign( b );
  31614. c.subAssign( mx_rotl32( b, int( 24 ) ) );
  31615. return c;
  31616. } ).setLayout( {
  31617. name: 'mx_bjfinal',
  31618. type: 'uint',
  31619. inputs: [
  31620. { name: 'a', type: 'uint' },
  31621. { name: 'b', type: 'uint' },
  31622. { name: 'c', type: 'uint' }
  31623. ]
  31624. } );
  31625. const mx_bits_to_01 = /*@__PURE__*/ Fn( ( [ bits_immutable ] ) => {
  31626. const bits = uint( bits_immutable ).toVar();
  31627. return float( bits ).div( float( uint( int( 0xffffffff ) ) ) );
  31628. } ).setLayout( {
  31629. name: 'mx_bits_to_01',
  31630. type: 'float',
  31631. inputs: [
  31632. { name: 'bits', type: 'uint' }
  31633. ]
  31634. } );
  31635. const mx_fade = /*@__PURE__*/ Fn( ( [ t_immutable ] ) => {
  31636. const t = float( t_immutable ).toVar();
  31637. return t.mul( t ).mul( t ).mul( t.mul( t.mul( 6.0 ).sub( 15.0 ) ).add( 10.0 ) );
  31638. } ).setLayout( {
  31639. name: 'mx_fade',
  31640. type: 'float',
  31641. inputs: [
  31642. { name: 't', type: 'float' }
  31643. ]
  31644. } );
  31645. const mx_hash_int_0 = /*@__PURE__*/ Fn( ( [ x_immutable ] ) => {
  31646. const x = int( x_immutable ).toVar();
  31647. const len = uint( uint( 1 ) ).toVar();
  31648. const seed = uint( uint( int( 0xdeadbeef ) ).add( len.shiftLeft( uint( 2 ) ) ).add( uint( 13 ) ) ).toVar();
  31649. return mx_bjfinal( seed.add( uint( x ) ), seed, seed );
  31650. } ).setLayout( {
  31651. name: 'mx_hash_int_0',
  31652. type: 'uint',
  31653. inputs: [
  31654. { name: 'x', type: 'int' }
  31655. ]
  31656. } );
  31657. const mx_hash_int_1 = /*@__PURE__*/ Fn( ( [ x_immutable, y_immutable ] ) => {
  31658. const y = int( y_immutable ).toVar();
  31659. const x = int( x_immutable ).toVar();
  31660. const len = uint( uint( 2 ) ).toVar();
  31661. const a = uint().toVar(), b = uint().toVar(), c = uint().toVar();
  31662. a.assign( b.assign( c.assign( uint( int( 0xdeadbeef ) ).add( len.shiftLeft( uint( 2 ) ) ).add( uint( 13 ) ) ) ) );
  31663. a.addAssign( uint( x ) );
  31664. b.addAssign( uint( y ) );
  31665. return mx_bjfinal( a, b, c );
  31666. } ).setLayout( {
  31667. name: 'mx_hash_int_1',
  31668. type: 'uint',
  31669. inputs: [
  31670. { name: 'x', type: 'int' },
  31671. { name: 'y', type: 'int' }
  31672. ]
  31673. } );
  31674. const mx_hash_int_2 = /*@__PURE__*/ Fn( ( [ x_immutable, y_immutable, z_immutable ] ) => {
  31675. const z = int( z_immutable ).toVar();
  31676. const y = int( y_immutable ).toVar();
  31677. const x = int( x_immutable ).toVar();
  31678. const len = uint( uint( 3 ) ).toVar();
  31679. const a = uint().toVar(), b = uint().toVar(), c = uint().toVar();
  31680. a.assign( b.assign( c.assign( uint( int( 0xdeadbeef ) ).add( len.shiftLeft( uint( 2 ) ) ).add( uint( 13 ) ) ) ) );
  31681. a.addAssign( uint( x ) );
  31682. b.addAssign( uint( y ) );
  31683. c.addAssign( uint( z ) );
  31684. return mx_bjfinal( a, b, c );
  31685. } ).setLayout( {
  31686. name: 'mx_hash_int_2',
  31687. type: 'uint',
  31688. inputs: [
  31689. { name: 'x', type: 'int' },
  31690. { name: 'y', type: 'int' },
  31691. { name: 'z', type: 'int' }
  31692. ]
  31693. } );
  31694. const mx_hash_int_3 = /*@__PURE__*/ Fn( ( [ x_immutable, y_immutable, z_immutable, xx_immutable ] ) => {
  31695. const xx = int( xx_immutable ).toVar();
  31696. const z = int( z_immutable ).toVar();
  31697. const y = int( y_immutable ).toVar();
  31698. const x = int( x_immutable ).toVar();
  31699. const len = uint( uint( 4 ) ).toVar();
  31700. const a = uint().toVar(), b = uint().toVar(), c = uint().toVar();
  31701. a.assign( b.assign( c.assign( uint( int( 0xdeadbeef ) ).add( len.shiftLeft( uint( 2 ) ) ).add( uint( 13 ) ) ) ) );
  31702. a.addAssign( uint( x ) );
  31703. b.addAssign( uint( y ) );
  31704. c.addAssign( uint( z ) );
  31705. mx_bjmix( a, b, c );
  31706. a.addAssign( uint( xx ) );
  31707. return mx_bjfinal( a, b, c );
  31708. } ).setLayout( {
  31709. name: 'mx_hash_int_3',
  31710. type: 'uint',
  31711. inputs: [
  31712. { name: 'x', type: 'int' },
  31713. { name: 'y', type: 'int' },
  31714. { name: 'z', type: 'int' },
  31715. { name: 'xx', type: 'int' }
  31716. ]
  31717. } );
  31718. const mx_hash_int_4 = /*@__PURE__*/ Fn( ( [ x_immutable, y_immutable, z_immutable, xx_immutable, yy_immutable ] ) => {
  31719. const yy = int( yy_immutable ).toVar();
  31720. const xx = int( xx_immutable ).toVar();
  31721. const z = int( z_immutable ).toVar();
  31722. const y = int( y_immutable ).toVar();
  31723. const x = int( x_immutable ).toVar();
  31724. const len = uint( uint( 5 ) ).toVar();
  31725. const a = uint().toVar(), b = uint().toVar(), c = uint().toVar();
  31726. a.assign( b.assign( c.assign( uint( int( 0xdeadbeef ) ).add( len.shiftLeft( uint( 2 ) ) ).add( uint( 13 ) ) ) ) );
  31727. a.addAssign( uint( x ) );
  31728. b.addAssign( uint( y ) );
  31729. c.addAssign( uint( z ) );
  31730. mx_bjmix( a, b, c );
  31731. a.addAssign( uint( xx ) );
  31732. b.addAssign( uint( yy ) );
  31733. return mx_bjfinal( a, b, c );
  31734. } ).setLayout( {
  31735. name: 'mx_hash_int_4',
  31736. type: 'uint',
  31737. inputs: [
  31738. { name: 'x', type: 'int' },
  31739. { name: 'y', type: 'int' },
  31740. { name: 'z', type: 'int' },
  31741. { name: 'xx', type: 'int' },
  31742. { name: 'yy', type: 'int' }
  31743. ]
  31744. } );
  31745. 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 ] );
  31746. const mx_hash_vec3_0 = /*@__PURE__*/ Fn( ( [ x_immutable, y_immutable ] ) => {
  31747. const y = int( y_immutable ).toVar();
  31748. const x = int( x_immutable ).toVar();
  31749. const h = uint( mx_hash_int( x, y ) ).toVar();
  31750. const result = uvec3().toVar();
  31751. result.x.assign( h.bitAnd( int( 0xFF ) ) );
  31752. result.y.assign( h.shiftRight( int( 8 ) ).bitAnd( int( 0xFF ) ) );
  31753. result.z.assign( h.shiftRight( int( 16 ) ).bitAnd( int( 0xFF ) ) );
  31754. return result;
  31755. } ).setLayout( {
  31756. name: 'mx_hash_vec3_0',
  31757. type: 'uvec3',
  31758. inputs: [
  31759. { name: 'x', type: 'int' },
  31760. { name: 'y', type: 'int' }
  31761. ]
  31762. } );
  31763. const mx_hash_vec3_1 = /*@__PURE__*/ Fn( ( [ x_immutable, y_immutable, z_immutable ] ) => {
  31764. const z = int( z_immutable ).toVar();
  31765. const y = int( y_immutable ).toVar();
  31766. const x = int( x_immutable ).toVar();
  31767. const h = uint( mx_hash_int( x, y, z ) ).toVar();
  31768. const result = uvec3().toVar();
  31769. result.x.assign( h.bitAnd( int( 0xFF ) ) );
  31770. result.y.assign( h.shiftRight( int( 8 ) ).bitAnd( int( 0xFF ) ) );
  31771. result.z.assign( h.shiftRight( int( 16 ) ).bitAnd( int( 0xFF ) ) );
  31772. return result;
  31773. } ).setLayout( {
  31774. name: 'mx_hash_vec3_1',
  31775. type: 'uvec3',
  31776. inputs: [
  31777. { name: 'x', type: 'int' },
  31778. { name: 'y', type: 'int' },
  31779. { name: 'z', type: 'int' }
  31780. ]
  31781. } );
  31782. const mx_hash_vec3 = /*@__PURE__*/ overloadingFn( [ mx_hash_vec3_0, mx_hash_vec3_1 ] );
  31783. const mx_perlin_noise_float_0 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  31784. const p = vec2( p_immutable ).toVar();
  31785. const X = int().toVar(), Y = int().toVar();
  31786. const fx = float( mx_floorfrac( p.x, X ) ).toVar();
  31787. const fy = float( mx_floorfrac( p.y, Y ) ).toVar();
  31788. const u = float( mx_fade( fx ) ).toVar();
  31789. const v = float( mx_fade( fy ) ).toVar();
  31790. 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();
  31791. return mx_gradient_scale2d( result );
  31792. } ).setLayout( {
  31793. name: 'mx_perlin_noise_float_0',
  31794. type: 'float',
  31795. inputs: [
  31796. { name: 'p', type: 'vec2' }
  31797. ]
  31798. } );
  31799. const mx_perlin_noise_float_1 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  31800. const p = vec3( p_immutable ).toVar();
  31801. const X = int().toVar(), Y = int().toVar(), Z = int().toVar();
  31802. const fx = float( mx_floorfrac( p.x, X ) ).toVar();
  31803. const fy = float( mx_floorfrac( p.y, Y ) ).toVar();
  31804. const fz = float( mx_floorfrac( p.z, Z ) ).toVar();
  31805. const u = float( mx_fade( fx ) ).toVar();
  31806. const v = float( mx_fade( fy ) ).toVar();
  31807. const w = float( mx_fade( fz ) ).toVar();
  31808. 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();
  31809. return mx_gradient_scale3d( result );
  31810. } ).setLayout( {
  31811. name: 'mx_perlin_noise_float_1',
  31812. type: 'float',
  31813. inputs: [
  31814. { name: 'p', type: 'vec3' }
  31815. ]
  31816. } );
  31817. const mx_perlin_noise_float = /*@__PURE__*/ overloadingFn( [ mx_perlin_noise_float_0, mx_perlin_noise_float_1 ] );
  31818. const mx_perlin_noise_vec3_0 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  31819. const p = vec2( p_immutable ).toVar();
  31820. const X = int().toVar(), Y = int().toVar();
  31821. const fx = float( mx_floorfrac( p.x, X ) ).toVar();
  31822. const fy = float( mx_floorfrac( p.y, Y ) ).toVar();
  31823. const u = float( mx_fade( fx ) ).toVar();
  31824. const v = float( mx_fade( fy ) ).toVar();
  31825. 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();
  31826. return mx_gradient_scale2d( result );
  31827. } ).setLayout( {
  31828. name: 'mx_perlin_noise_vec3_0',
  31829. type: 'vec3',
  31830. inputs: [
  31831. { name: 'p', type: 'vec2' }
  31832. ]
  31833. } );
  31834. const mx_perlin_noise_vec3_1 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  31835. const p = vec3( p_immutable ).toVar();
  31836. const X = int().toVar(), Y = int().toVar(), Z = int().toVar();
  31837. const fx = float( mx_floorfrac( p.x, X ) ).toVar();
  31838. const fy = float( mx_floorfrac( p.y, Y ) ).toVar();
  31839. const fz = float( mx_floorfrac( p.z, Z ) ).toVar();
  31840. const u = float( mx_fade( fx ) ).toVar();
  31841. const v = float( mx_fade( fy ) ).toVar();
  31842. const w = float( mx_fade( fz ) ).toVar();
  31843. 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();
  31844. return mx_gradient_scale3d( result );
  31845. } ).setLayout( {
  31846. name: 'mx_perlin_noise_vec3_1',
  31847. type: 'vec3',
  31848. inputs: [
  31849. { name: 'p', type: 'vec3' }
  31850. ]
  31851. } );
  31852. const mx_perlin_noise_vec3 = /*@__PURE__*/ overloadingFn( [ mx_perlin_noise_vec3_0, mx_perlin_noise_vec3_1 ] );
  31853. const mx_cell_noise_float_0 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  31854. const p = float( p_immutable ).toVar();
  31855. const ix = int( mx_floor( p ) ).toVar();
  31856. return mx_bits_to_01( mx_hash_int( ix ) );
  31857. } ).setLayout( {
  31858. name: 'mx_cell_noise_float_0',
  31859. type: 'float',
  31860. inputs: [
  31861. { name: 'p', type: 'float' }
  31862. ]
  31863. } );
  31864. const mx_cell_noise_float_1 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  31865. const p = vec2( p_immutable ).toVar();
  31866. const ix = int( mx_floor( p.x ) ).toVar();
  31867. const iy = int( mx_floor( p.y ) ).toVar();
  31868. return mx_bits_to_01( mx_hash_int( ix, iy ) );
  31869. } ).setLayout( {
  31870. name: 'mx_cell_noise_float_1',
  31871. type: 'float',
  31872. inputs: [
  31873. { name: 'p', type: 'vec2' }
  31874. ]
  31875. } );
  31876. const mx_cell_noise_float_2 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  31877. const p = vec3( p_immutable ).toVar();
  31878. const ix = int( mx_floor( p.x ) ).toVar();
  31879. const iy = int( mx_floor( p.y ) ).toVar();
  31880. const iz = int( mx_floor( p.z ) ).toVar();
  31881. return mx_bits_to_01( mx_hash_int( ix, iy, iz ) );
  31882. } ).setLayout( {
  31883. name: 'mx_cell_noise_float_2',
  31884. type: 'float',
  31885. inputs: [
  31886. { name: 'p', type: 'vec3' }
  31887. ]
  31888. } );
  31889. const mx_cell_noise_float_3 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  31890. const p = vec4( p_immutable ).toVar();
  31891. const ix = int( mx_floor( p.x ) ).toVar();
  31892. const iy = int( mx_floor( p.y ) ).toVar();
  31893. const iz = int( mx_floor( p.z ) ).toVar();
  31894. const iw = int( mx_floor( p.w ) ).toVar();
  31895. return mx_bits_to_01( mx_hash_int( ix, iy, iz, iw ) );
  31896. } ).setLayout( {
  31897. name: 'mx_cell_noise_float_3',
  31898. type: 'float',
  31899. inputs: [
  31900. { name: 'p', type: 'vec4' }
  31901. ]
  31902. } );
  31903. 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 ] );
  31904. const mx_cell_noise_vec3_0 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  31905. const p = float( p_immutable ).toVar();
  31906. const ix = int( mx_floor( p ) ).toVar();
  31907. 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 ) ) ) );
  31908. } ).setLayout( {
  31909. name: 'mx_cell_noise_vec3_0',
  31910. type: 'vec3',
  31911. inputs: [
  31912. { name: 'p', type: 'float' }
  31913. ]
  31914. } );
  31915. const mx_cell_noise_vec3_1 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  31916. const p = vec2( p_immutable ).toVar();
  31917. const ix = int( mx_floor( p.x ) ).toVar();
  31918. const iy = int( mx_floor( p.y ) ).toVar();
  31919. 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 ) ) ) );
  31920. } ).setLayout( {
  31921. name: 'mx_cell_noise_vec3_1',
  31922. type: 'vec3',
  31923. inputs: [
  31924. { name: 'p', type: 'vec2' }
  31925. ]
  31926. } );
  31927. const mx_cell_noise_vec3_2 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  31928. const p = vec3( p_immutable ).toVar();
  31929. const ix = int( mx_floor( p.x ) ).toVar();
  31930. const iy = int( mx_floor( p.y ) ).toVar();
  31931. const iz = int( mx_floor( p.z ) ).toVar();
  31932. 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 ) ) ) );
  31933. } ).setLayout( {
  31934. name: 'mx_cell_noise_vec3_2',
  31935. type: 'vec3',
  31936. inputs: [
  31937. { name: 'p', type: 'vec3' }
  31938. ]
  31939. } );
  31940. const mx_cell_noise_vec3_3 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  31941. const p = vec4( p_immutable ).toVar();
  31942. const ix = int( mx_floor( p.x ) ).toVar();
  31943. const iy = int( mx_floor( p.y ) ).toVar();
  31944. const iz = int( mx_floor( p.z ) ).toVar();
  31945. const iw = int( mx_floor( p.w ) ).toVar();
  31946. 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 ) ) ) );
  31947. } ).setLayout( {
  31948. name: 'mx_cell_noise_vec3_3',
  31949. type: 'vec3',
  31950. inputs: [
  31951. { name: 'p', type: 'vec4' }
  31952. ]
  31953. } );
  31954. 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 ] );
  31955. const mx_fractal_noise_float$1 = /*@__PURE__*/ Fn( ( [ p_immutable, octaves_immutable, lacunarity_immutable, diminish_immutable ] ) => {
  31956. const diminish = float( diminish_immutable ).toVar();
  31957. const lacunarity = float( lacunarity_immutable ).toVar();
  31958. const octaves = int( octaves_immutable ).toVar();
  31959. const p = vec3( p_immutable ).toVar();
  31960. const result = float( 0.0 ).toVar();
  31961. const amplitude = float( 1.0 ).toVar();
  31962. Loop( octaves, () => {
  31963. result.addAssign( amplitude.mul( mx_perlin_noise_float( p ) ) );
  31964. amplitude.mulAssign( diminish );
  31965. p.mulAssign( lacunarity );
  31966. } );
  31967. return result;
  31968. } ).setLayout( {
  31969. name: 'mx_fractal_noise_float',
  31970. type: 'float',
  31971. inputs: [
  31972. { name: 'p', type: 'vec3' },
  31973. { name: 'octaves', type: 'int' },
  31974. { name: 'lacunarity', type: 'float' },
  31975. { name: 'diminish', type: 'float' }
  31976. ]
  31977. } );
  31978. const mx_fractal_noise_vec3$1 = /*@__PURE__*/ Fn( ( [ p_immutable, octaves_immutable, lacunarity_immutable, diminish_immutable ] ) => {
  31979. const diminish = float( diminish_immutable ).toVar();
  31980. const lacunarity = float( lacunarity_immutable ).toVar();
  31981. const octaves = int( octaves_immutable ).toVar();
  31982. const p = vec3( p_immutable ).toVar();
  31983. const result = vec3( 0.0 ).toVar();
  31984. const amplitude = float( 1.0 ).toVar();
  31985. Loop( octaves, () => {
  31986. result.addAssign( amplitude.mul( mx_perlin_noise_vec3( p ) ) );
  31987. amplitude.mulAssign( diminish );
  31988. p.mulAssign( lacunarity );
  31989. } );
  31990. return result;
  31991. } ).setLayout( {
  31992. name: 'mx_fractal_noise_vec3',
  31993. type: 'vec3',
  31994. inputs: [
  31995. { name: 'p', type: 'vec3' },
  31996. { name: 'octaves', type: 'int' },
  31997. { name: 'lacunarity', type: 'float' },
  31998. { name: 'diminish', type: 'float' }
  31999. ]
  32000. } );
  32001. const mx_fractal_noise_vec2$1 = /*@__PURE__*/ Fn( ( [ p_immutable, octaves_immutable, lacunarity_immutable, diminish_immutable ] ) => {
  32002. const diminish = float( diminish_immutable ).toVar();
  32003. const lacunarity = float( lacunarity_immutable ).toVar();
  32004. const octaves = int( octaves_immutable ).toVar();
  32005. const p = vec3( p_immutable ).toVar();
  32006. 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 ) );
  32007. } ).setLayout( {
  32008. name: 'mx_fractal_noise_vec2',
  32009. type: 'vec2',
  32010. inputs: [
  32011. { name: 'p', type: 'vec3' },
  32012. { name: 'octaves', type: 'int' },
  32013. { name: 'lacunarity', type: 'float' },
  32014. { name: 'diminish', type: 'float' }
  32015. ]
  32016. } );
  32017. const mx_fractal_noise_vec4$1 = /*@__PURE__*/ Fn( ( [ p_immutable, octaves_immutable, lacunarity_immutable, diminish_immutable ] ) => {
  32018. const diminish = float( diminish_immutable ).toVar();
  32019. const lacunarity = float( lacunarity_immutable ).toVar();
  32020. const octaves = int( octaves_immutable ).toVar();
  32021. const p = vec3( p_immutable ).toVar();
  32022. const c = vec3( mx_fractal_noise_vec3$1( p, octaves, lacunarity, diminish ) ).toVar();
  32023. const f = float( mx_fractal_noise_float$1( p.add( vec3( int( 19 ), int( 193 ), int( 17 ) ) ), octaves, lacunarity, diminish ) ).toVar();
  32024. return vec4( c, f );
  32025. } ).setLayout( {
  32026. name: 'mx_fractal_noise_vec4',
  32027. type: 'vec4',
  32028. inputs: [
  32029. { name: 'p', type: 'vec3' },
  32030. { name: 'octaves', type: 'int' },
  32031. { name: 'lacunarity', type: 'float' },
  32032. { name: 'diminish', type: 'float' }
  32033. ]
  32034. } );
  32035. const mx_worley_distance_0 = /*@__PURE__*/ Fn( ( [ p_immutable, x_immutable, y_immutable, xoff_immutable, yoff_immutable, jitter_immutable, metric_immutable ] ) => {
  32036. const metric = int( metric_immutable ).toVar();
  32037. const jitter = float( jitter_immutable ).toVar();
  32038. const yoff = int( yoff_immutable ).toVar();
  32039. const xoff = int( xoff_immutable ).toVar();
  32040. const y = int( y_immutable ).toVar();
  32041. const x = int( x_immutable ).toVar();
  32042. const p = vec2( p_immutable ).toVar();
  32043. const tmp = vec3( mx_cell_noise_vec3( vec2( x.add( xoff ), y.add( yoff ) ) ) ).toVar();
  32044. const off = vec2( tmp.x, tmp.y ).toVar();
  32045. off.subAssign( 0.5 );
  32046. off.mulAssign( jitter );
  32047. off.addAssign( 0.5 );
  32048. const cellpos = vec2( vec2( float( x ), float( y ) ).add( off ) ).toVar();
  32049. const diff = vec2( cellpos.sub( p ) ).toVar();
  32050. If( metric.equal( int( 2 ) ), () => {
  32051. return abs( diff.x ).add( abs( diff.y ) );
  32052. } );
  32053. If( metric.equal( int( 3 ) ), () => {
  32054. return max$1( abs( diff.x ), abs( diff.y ) );
  32055. } );
  32056. return dot( diff, diff );
  32057. } ).setLayout( {
  32058. name: 'mx_worley_distance_0',
  32059. type: 'float',
  32060. inputs: [
  32061. { name: 'p', type: 'vec2' },
  32062. { name: 'x', type: 'int' },
  32063. { name: 'y', type: 'int' },
  32064. { name: 'xoff', type: 'int' },
  32065. { name: 'yoff', type: 'int' },
  32066. { name: 'jitter', type: 'float' },
  32067. { name: 'metric', type: 'int' }
  32068. ]
  32069. } );
  32070. 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 ] ) => {
  32071. const metric = int( metric_immutable ).toVar();
  32072. const jitter = float( jitter_immutable ).toVar();
  32073. const zoff = int( zoff_immutable ).toVar();
  32074. const yoff = int( yoff_immutable ).toVar();
  32075. const xoff = int( xoff_immutable ).toVar();
  32076. const z = int( z_immutable ).toVar();
  32077. const y = int( y_immutable ).toVar();
  32078. const x = int( x_immutable ).toVar();
  32079. const p = vec3( p_immutable ).toVar();
  32080. const off = vec3( mx_cell_noise_vec3( vec3( x.add( xoff ), y.add( yoff ), z.add( zoff ) ) ) ).toVar();
  32081. off.subAssign( 0.5 );
  32082. off.mulAssign( jitter );
  32083. off.addAssign( 0.5 );
  32084. const cellpos = vec3( vec3( float( x ), float( y ), float( z ) ).add( off ) ).toVar();
  32085. const diff = vec3( cellpos.sub( p ) ).toVar();
  32086. If( metric.equal( int( 2 ) ), () => {
  32087. return abs( diff.x ).add( abs( diff.y ) ).add( abs( diff.z ) );
  32088. } );
  32089. If( metric.equal( int( 3 ) ), () => {
  32090. return max$1( abs( diff.x ), abs( diff.y ), abs( diff.z ) );
  32091. } );
  32092. return dot( diff, diff );
  32093. } ).setLayout( {
  32094. name: 'mx_worley_distance_1',
  32095. type: 'float',
  32096. inputs: [
  32097. { name: 'p', type: 'vec3' },
  32098. { name: 'x', type: 'int' },
  32099. { name: 'y', type: 'int' },
  32100. { name: 'z', type: 'int' },
  32101. { name: 'xoff', type: 'int' },
  32102. { name: 'yoff', type: 'int' },
  32103. { name: 'zoff', type: 'int' },
  32104. { name: 'jitter', type: 'float' },
  32105. { name: 'metric', type: 'int' }
  32106. ]
  32107. } );
  32108. const mx_worley_distance = /*@__PURE__*/ overloadingFn( [ mx_worley_distance_0, mx_worley_distance_1 ] );
  32109. const mx_worley_noise_float_0 = /*@__PURE__*/ Fn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  32110. const metric = int( metric_immutable ).toVar();
  32111. const jitter = float( jitter_immutable ).toVar();
  32112. const p = vec2( p_immutable ).toVar();
  32113. const X = int().toVar(), Y = int().toVar();
  32114. const localpos = vec2( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ) ).toVar();
  32115. const sqdist = float( 1e6 ).toVar();
  32116. Loop( { start: -1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  32117. Loop( { start: -1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  32118. const dist = float( mx_worley_distance( localpos, x, y, X, Y, jitter, metric ) ).toVar();
  32119. sqdist.assign( min$1( sqdist, dist ) );
  32120. } );
  32121. } );
  32122. If( metric.equal( int( 0 ) ), () => {
  32123. sqdist.assign( sqrt( sqdist ) );
  32124. } );
  32125. return sqdist;
  32126. } ).setLayout( {
  32127. name: 'mx_worley_noise_float_0',
  32128. type: 'float',
  32129. inputs: [
  32130. { name: 'p', type: 'vec2' },
  32131. { name: 'jitter', type: 'float' },
  32132. { name: 'metric', type: 'int' }
  32133. ]
  32134. } );
  32135. const mx_worley_noise_vec2_0 = /*@__PURE__*/ Fn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  32136. const metric = int( metric_immutable ).toVar();
  32137. const jitter = float( jitter_immutable ).toVar();
  32138. const p = vec2( p_immutable ).toVar();
  32139. const X = int().toVar(), Y = int().toVar();
  32140. const localpos = vec2( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ) ).toVar();
  32141. const sqdist = vec2( 1e6, 1e6 ).toVar();
  32142. Loop( { start: -1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  32143. Loop( { start: -1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  32144. const dist = float( mx_worley_distance( localpos, x, y, X, Y, jitter, metric ) ).toVar();
  32145. If( dist.lessThan( sqdist.x ), () => {
  32146. sqdist.y.assign( sqdist.x );
  32147. sqdist.x.assign( dist );
  32148. } ).ElseIf( dist.lessThan( sqdist.y ), () => {
  32149. sqdist.y.assign( dist );
  32150. } );
  32151. } );
  32152. } );
  32153. If( metric.equal( int( 0 ) ), () => {
  32154. sqdist.assign( sqrt( sqdist ) );
  32155. } );
  32156. return sqdist;
  32157. } ).setLayout( {
  32158. name: 'mx_worley_noise_vec2_0',
  32159. type: 'vec2',
  32160. inputs: [
  32161. { name: 'p', type: 'vec2' },
  32162. { name: 'jitter', type: 'float' },
  32163. { name: 'metric', type: 'int' }
  32164. ]
  32165. } );
  32166. const mx_worley_noise_vec3_0 = /*@__PURE__*/ Fn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  32167. const metric = int( metric_immutable ).toVar();
  32168. const jitter = float( jitter_immutable ).toVar();
  32169. const p = vec2( p_immutable ).toVar();
  32170. const X = int().toVar(), Y = int().toVar();
  32171. const localpos = vec2( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ) ).toVar();
  32172. const sqdist = vec3( 1e6, 1e6, 1e6 ).toVar();
  32173. Loop( { start: -1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  32174. Loop( { start: -1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  32175. const dist = float( mx_worley_distance( localpos, x, y, X, Y, jitter, metric ) ).toVar();
  32176. If( dist.lessThan( sqdist.x ), () => {
  32177. sqdist.z.assign( sqdist.y );
  32178. sqdist.y.assign( sqdist.x );
  32179. sqdist.x.assign( dist );
  32180. } ).ElseIf( dist.lessThan( sqdist.y ), () => {
  32181. sqdist.z.assign( sqdist.y );
  32182. sqdist.y.assign( dist );
  32183. } ).ElseIf( dist.lessThan( sqdist.z ), () => {
  32184. sqdist.z.assign( dist );
  32185. } );
  32186. } );
  32187. } );
  32188. If( metric.equal( int( 0 ) ), () => {
  32189. sqdist.assign( sqrt( sqdist ) );
  32190. } );
  32191. return sqdist;
  32192. } ).setLayout( {
  32193. name: 'mx_worley_noise_vec3_0',
  32194. type: 'vec3',
  32195. inputs: [
  32196. { name: 'p', type: 'vec2' },
  32197. { name: 'jitter', type: 'float' },
  32198. { name: 'metric', type: 'int' }
  32199. ]
  32200. } );
  32201. const mx_worley_noise_float_1 = /*@__PURE__*/ Fn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  32202. const metric = int( metric_immutable ).toVar();
  32203. const jitter = float( jitter_immutable ).toVar();
  32204. const p = vec3( p_immutable ).toVar();
  32205. const X = int().toVar(), Y = int().toVar(), Z = int().toVar();
  32206. const localpos = vec3( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ), mx_floorfrac( p.z, Z ) ).toVar();
  32207. const sqdist = float( 1e6 ).toVar();
  32208. Loop( { start: -1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  32209. Loop( { start: -1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  32210. Loop( { start: -1, end: int( 1 ), name: 'z', condition: '<=' }, ( { z } ) => {
  32211. const dist = float( mx_worley_distance( localpos, x, y, z, X, Y, Z, jitter, metric ) ).toVar();
  32212. sqdist.assign( min$1( sqdist, dist ) );
  32213. } );
  32214. } );
  32215. } );
  32216. If( metric.equal( int( 0 ) ), () => {
  32217. sqdist.assign( sqrt( sqdist ) );
  32218. } );
  32219. return sqdist;
  32220. } ).setLayout( {
  32221. name: 'mx_worley_noise_float_1',
  32222. type: 'float',
  32223. inputs: [
  32224. { name: 'p', type: 'vec3' },
  32225. { name: 'jitter', type: 'float' },
  32226. { name: 'metric', type: 'int' }
  32227. ]
  32228. } );
  32229. const mx_worley_noise_float$1 = /*@__PURE__*/ overloadingFn( [ mx_worley_noise_float_0, mx_worley_noise_float_1 ] );
  32230. const mx_worley_noise_vec2_1 = /*@__PURE__*/ Fn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  32231. const metric = int( metric_immutable ).toVar();
  32232. const jitter = float( jitter_immutable ).toVar();
  32233. const p = vec3( p_immutable ).toVar();
  32234. const X = int().toVar(), Y = int().toVar(), Z = int().toVar();
  32235. const localpos = vec3( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ), mx_floorfrac( p.z, Z ) ).toVar();
  32236. const sqdist = vec2( 1e6, 1e6 ).toVar();
  32237. Loop( { start: -1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  32238. Loop( { start: -1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  32239. Loop( { start: -1, end: int( 1 ), name: 'z', condition: '<=' }, ( { z } ) => {
  32240. const dist = float( mx_worley_distance( localpos, x, y, z, X, Y, Z, jitter, metric ) ).toVar();
  32241. If( dist.lessThan( sqdist.x ), () => {
  32242. sqdist.y.assign( sqdist.x );
  32243. sqdist.x.assign( dist );
  32244. } ).ElseIf( dist.lessThan( sqdist.y ), () => {
  32245. sqdist.y.assign( dist );
  32246. } );
  32247. } );
  32248. } );
  32249. } );
  32250. If( metric.equal( int( 0 ) ), () => {
  32251. sqdist.assign( sqrt( sqdist ) );
  32252. } );
  32253. return sqdist;
  32254. } ).setLayout( {
  32255. name: 'mx_worley_noise_vec2_1',
  32256. type: 'vec2',
  32257. inputs: [
  32258. { name: 'p', type: 'vec3' },
  32259. { name: 'jitter', type: 'float' },
  32260. { name: 'metric', type: 'int' }
  32261. ]
  32262. } );
  32263. const mx_worley_noise_vec2$1 = /*@__PURE__*/ overloadingFn( [ mx_worley_noise_vec2_0, mx_worley_noise_vec2_1 ] );
  32264. const mx_worley_noise_vec3_1 = /*@__PURE__*/ Fn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  32265. const metric = int( metric_immutable ).toVar();
  32266. const jitter = float( jitter_immutable ).toVar();
  32267. const p = vec3( p_immutable ).toVar();
  32268. const X = int().toVar(), Y = int().toVar(), Z = int().toVar();
  32269. const localpos = vec3( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ), mx_floorfrac( p.z, Z ) ).toVar();
  32270. const sqdist = vec3( 1e6, 1e6, 1e6 ).toVar();
  32271. Loop( { start: -1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  32272. Loop( { start: -1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  32273. Loop( { start: -1, end: int( 1 ), name: 'z', condition: '<=' }, ( { z } ) => {
  32274. const dist = float( mx_worley_distance( localpos, x, y, z, X, Y, Z, jitter, metric ) ).toVar();
  32275. If( dist.lessThan( sqdist.x ), () => {
  32276. sqdist.z.assign( sqdist.y );
  32277. sqdist.y.assign( sqdist.x );
  32278. sqdist.x.assign( dist );
  32279. } ).ElseIf( dist.lessThan( sqdist.y ), () => {
  32280. sqdist.z.assign( sqdist.y );
  32281. sqdist.y.assign( dist );
  32282. } ).ElseIf( dist.lessThan( sqdist.z ), () => {
  32283. sqdist.z.assign( dist );
  32284. } );
  32285. } );
  32286. } );
  32287. } );
  32288. If( metric.equal( int( 0 ) ), () => {
  32289. sqdist.assign( sqrt( sqdist ) );
  32290. } );
  32291. return sqdist;
  32292. } ).setLayout( {
  32293. name: 'mx_worley_noise_vec3_1',
  32294. type: 'vec3',
  32295. inputs: [
  32296. { name: 'p', type: 'vec3' },
  32297. { name: 'jitter', type: 'float' },
  32298. { name: 'metric', type: 'int' }
  32299. ]
  32300. } );
  32301. const mx_worley_noise_vec3$1 = /*@__PURE__*/ overloadingFn( [ mx_worley_noise_vec3_0, mx_worley_noise_vec3_1 ] );
  32302. // Unified Noise 2D
  32303. const mx_unifiednoise2d$1 = /*@__PURE__*/ Fn( ( [
  32304. noiseType_immutable, texcoord_immutable, freq_immutable, offset_immutable,
  32305. jitter_immutable, outmin_immutable, outmax_immutable, clampoutput_immutable,
  32306. octaves_immutable, lacunarity_immutable, diminish_immutable
  32307. ] ) => {
  32308. const noiseType = int( noiseType_immutable ).toVar();
  32309. const texcoord = vec2( texcoord_immutable ).toVar();
  32310. const freq = vec2( freq_immutable ).toVar();
  32311. const offset = vec2( offset_immutable ).toVar();
  32312. const jitter = float( jitter_immutable ).toVar();
  32313. const outmin = float( outmin_immutable ).toVar();
  32314. const outmax = float( outmax_immutable ).toVar();
  32315. const clampoutput = bool( clampoutput_immutable ).toVar();
  32316. const octaves = int( octaves_immutable ).toVar();
  32317. const lacunarity = float( lacunarity_immutable ).toVar();
  32318. const diminish = float( diminish_immutable ).toVar();
  32319. // Compute input position
  32320. const p = texcoord.mul( freq ).add( offset );
  32321. const result = float( 0.0 ).toVar();
  32322. // Perlin
  32323. If( noiseType.equal( int( 0 ) ), () => {
  32324. result.assign( mx_perlin_noise_vec3( p ) );
  32325. } );
  32326. // Cell
  32327. If( noiseType.equal( int( 1 ) ), () => {
  32328. result.assign( mx_cell_noise_vec3( p ) );
  32329. } );
  32330. // Worley (metric=0 = euclidean)
  32331. If( noiseType.equal( int( 2 ) ), () => {
  32332. result.assign( mx_worley_noise_vec3$1( p, jitter, int( 0 ) ) );
  32333. } );
  32334. // Fractal (use vec3(p, 0.0) for 2D input)
  32335. If( noiseType.equal( int( 3 ) ), () => {
  32336. result.assign( mx_fractal_noise_vec3$1( vec3( p, 0.0 ), octaves, lacunarity, diminish ) );
  32337. } );
  32338. // Remap output to [outmin, outmax]
  32339. result.assign( result.mul( outmax.sub( outmin ) ).add( outmin ) );
  32340. // Clamp if requested
  32341. If( clampoutput, () => {
  32342. result.assign( clamp( result, outmin, outmax ) );
  32343. } );
  32344. return result;
  32345. } ).setLayout( {
  32346. name: 'mx_unifiednoise2d',
  32347. type: 'float',
  32348. inputs: [
  32349. { name: 'noiseType', type: 'int' },
  32350. { name: 'texcoord', type: 'vec2' },
  32351. { name: 'freq', type: 'vec2' },
  32352. { name: 'offset', type: 'vec2' },
  32353. { name: 'jitter', type: 'float' },
  32354. { name: 'outmin', type: 'float' },
  32355. { name: 'outmax', type: 'float' },
  32356. { name: 'clampoutput', type: 'bool' },
  32357. { name: 'octaves', type: 'int' },
  32358. { name: 'lacunarity', type: 'float' },
  32359. { name: 'diminish', type: 'float' }
  32360. ]
  32361. } );
  32362. // Unified Noise 3D
  32363. const mx_unifiednoise3d$1 = /*@__PURE__*/ Fn( ( [
  32364. noiseType_immutable, position_immutable, freq_immutable, offset_immutable,
  32365. jitter_immutable, outmin_immutable, outmax_immutable, clampoutput_immutable,
  32366. octaves_immutable, lacunarity_immutable, diminish_immutable
  32367. ] ) => {
  32368. const noiseType = int( noiseType_immutable ).toVar();
  32369. const position = vec3( position_immutable ).toVar();
  32370. const freq = vec3( freq_immutable ).toVar();
  32371. const offset = vec3( offset_immutable ).toVar();
  32372. const jitter = float( jitter_immutable ).toVar();
  32373. const outmin = float( outmin_immutable ).toVar();
  32374. const outmax = float( outmax_immutable ).toVar();
  32375. const clampoutput = bool( clampoutput_immutable ).toVar();
  32376. const octaves = int( octaves_immutable ).toVar();
  32377. const lacunarity = float( lacunarity_immutable ).toVar();
  32378. const diminish = float( diminish_immutable ).toVar();
  32379. // Compute input position
  32380. const p = position.mul( freq ).add( offset );
  32381. const result = float( 0.0 ).toVar();
  32382. // Perlin
  32383. If( noiseType.equal( int( 0 ) ), () => {
  32384. result.assign( mx_perlin_noise_vec3( p ) );
  32385. } );
  32386. // Cell
  32387. If( noiseType.equal( int( 1 ) ), () => {
  32388. result.assign( mx_cell_noise_vec3( p ) );
  32389. } );
  32390. // Worley (metric=0 = euclidean)
  32391. If( noiseType.equal( int( 2 ) ), () => {
  32392. result.assign( mx_worley_noise_vec3$1( p, jitter, int( 0 ) ) );
  32393. } );
  32394. // Fractal
  32395. If( noiseType.equal( int( 3 ) ), () => {
  32396. result.assign( mx_fractal_noise_vec3$1( p, octaves, lacunarity, diminish ) );
  32397. } );
  32398. // Remap output to [outmin, outmax]
  32399. result.assign( result.mul( outmax.sub( outmin ) ).add( outmin ) );
  32400. // Clamp if requested
  32401. If( clampoutput, () => {
  32402. result.assign( clamp( result, outmin, outmax ) );
  32403. } );
  32404. return result;
  32405. } ).setLayout( {
  32406. name: 'mx_unifiednoise3d',
  32407. type: 'float',
  32408. inputs: [
  32409. { name: 'noiseType', type: 'int' },
  32410. { name: 'position', type: 'vec3' },
  32411. { name: 'freq', type: 'vec3' },
  32412. { name: 'offset', type: 'vec3' },
  32413. { name: 'jitter', type: 'float' },
  32414. { name: 'outmin', type: 'float' },
  32415. { name: 'outmax', type: 'float' },
  32416. { name: 'clampoutput', type: 'bool' },
  32417. { name: 'octaves', type: 'int' },
  32418. { name: 'lacunarity', type: 'float' },
  32419. { name: 'diminish', type: 'float' }
  32420. ]
  32421. } );
  32422. // Three.js Transpiler
  32423. // https://github.com/AcademySoftwareFoundation/MaterialX/blob/main/libraries/stdlib/genglsl/lib/mx_hsv.glsl
  32424. const mx_hsvtorgb = /*@__PURE__*/ Fn( ( [ hsv ] ) => {
  32425. const s = hsv.y;
  32426. const v = hsv.z;
  32427. const result = vec3().toVar();
  32428. If( s.lessThan( 0.0001 ), () => {
  32429. result.assign( vec3( v, v, v ) );
  32430. } ).Else( () => {
  32431. let h = hsv.x;
  32432. h = h.sub( floor( h ) ).mul( 6.0 ).toVar(); // TODO: check what .toVar() is needed in node system cache
  32433. const hi = int( trunc( h ) );
  32434. const f = h.sub( float( hi ) );
  32435. const p = v.mul( s.oneMinus() );
  32436. const q = v.mul( s.mul( f ).oneMinus() );
  32437. const t = v.mul( s.mul( f.oneMinus() ).oneMinus() );
  32438. If( hi.equal( int( 0 ) ), () => {
  32439. result.assign( vec3( v, t, p ) );
  32440. } ).ElseIf( hi.equal( int( 1 ) ), () => {
  32441. result.assign( vec3( q, v, p ) );
  32442. } ).ElseIf( hi.equal( int( 2 ) ), () => {
  32443. result.assign( vec3( p, v, t ) );
  32444. } ).ElseIf( hi.equal( int( 3 ) ), () => {
  32445. result.assign( vec3( p, q, v ) );
  32446. } ).ElseIf( hi.equal( int( 4 ) ), () => {
  32447. result.assign( vec3( t, p, v ) );
  32448. } ).Else( () => {
  32449. result.assign( vec3( v, p, q ) );
  32450. } );
  32451. } );
  32452. return result;
  32453. } ).setLayout( {
  32454. name: 'mx_hsvtorgb',
  32455. type: 'vec3',
  32456. inputs: [
  32457. { name: 'hsv', type: 'vec3' }
  32458. ]
  32459. } );
  32460. const mx_rgbtohsv = /*@__PURE__*/ Fn( ( [ c_immutable ] ) => {
  32461. const c = vec3( c_immutable ).toVar();
  32462. const r = float( c.x ).toVar();
  32463. const g = float( c.y ).toVar();
  32464. const b = float( c.z ).toVar();
  32465. const mincomp = float( min$1( r, min$1( g, b ) ) ).toVar();
  32466. const maxcomp = float( max$1( r, max$1( g, b ) ) ).toVar();
  32467. const delta = float( maxcomp.sub( mincomp ) ).toVar();
  32468. const h = float().toVar(), s = float().toVar(), v = float().toVar();
  32469. v.assign( maxcomp );
  32470. If( maxcomp.greaterThan( 0.0 ), () => {
  32471. s.assign( delta.div( maxcomp ) );
  32472. } ).Else( () => {
  32473. s.assign( 0.0 );
  32474. } );
  32475. If( s.lessThanEqual( 0.0 ), () => {
  32476. h.assign( 0.0 );
  32477. } ).Else( () => {
  32478. If( r.greaterThanEqual( maxcomp ), () => {
  32479. h.assign( g.sub( b ).div( delta ) );
  32480. } ).ElseIf( g.greaterThanEqual( maxcomp ), () => {
  32481. h.assign( add( 2.0, b.sub( r ).div( delta ) ) );
  32482. } ).Else( () => {
  32483. h.assign( add( 4.0, r.sub( g ).div( delta ) ) );
  32484. } );
  32485. h.mulAssign( 1.0 / 6.0 );
  32486. If( h.lessThan( 0.0 ), () => {
  32487. h.addAssign( 1.0 );
  32488. } );
  32489. } );
  32490. return vec3( h, s, v );
  32491. } ).setLayout( {
  32492. name: 'mx_rgbtohsv',
  32493. type: 'vec3',
  32494. inputs: [
  32495. { name: 'c', type: 'vec3' }
  32496. ]
  32497. } );
  32498. // Three.js Transpiler
  32499. // https://github.com/AcademySoftwareFoundation/MaterialX/blob/main/libraries/stdlib/genglsl/lib/mx_transform_color.glsl
  32500. const mx_srgb_texture_to_lin_rec709 = /*@__PURE__*/ Fn( ( [ color_immutable ] ) => {
  32501. const color = vec3( color_immutable ).toVar();
  32502. const isAbove = bvec3( greaterThan( color, vec3( 0.04045 ) ) ).toVar();
  32503. const linSeg = vec3( color.div( 12.92 ) ).toVar();
  32504. const powSeg = vec3( pow( max$1( color.add( vec3( 0.055 ) ), vec3( 0.0 ) ).div( 1.055 ), vec3( 2.4 ) ) ).toVar();
  32505. return mix( linSeg, powSeg, isAbove );
  32506. } ).setLayout( {
  32507. name: 'mx_srgb_texture_to_lin_rec709',
  32508. type: 'vec3',
  32509. inputs: [
  32510. { name: 'color', type: 'vec3' }
  32511. ]
  32512. } );
  32513. const mx_aastep = ( threshold, value ) => {
  32514. threshold = float( threshold );
  32515. value = float( value );
  32516. const afwidth = vec2( value.dFdx(), value.dFdy() ).length().mul( 0.70710678118654757 );
  32517. return smoothstep( threshold.sub( afwidth ), threshold.add( afwidth ), value );
  32518. };
  32519. const _ramp = ( a, b, uv, p ) => mix( a, b, uv[ p ].clamp() );
  32520. const mx_ramplr = ( valuel, valuer, texcoord = uv$1() ) => _ramp( valuel, valuer, texcoord, 'x' );
  32521. const mx_ramptb = ( valuet, valueb, texcoord = uv$1() ) => _ramp( valuet, valueb, texcoord, 'y' );
  32522. // Bilinear ramp: interpolate between four corners (tl, tr, bl, br) using texcoord.x and texcoord.y
  32523. const mx_ramp4 = (
  32524. valuetl, valuetr, valuebl, valuebr, texcoord = uv$1()
  32525. ) => {
  32526. const u = texcoord.x.clamp();
  32527. const v = texcoord.y.clamp();
  32528. const top = mix( valuetl, valuetr, u );
  32529. const bottom = mix( valuebl, valuebr, u );
  32530. return mix( top, bottom, v );
  32531. };
  32532. const _split = ( a, b, center, uv, p ) => mix( a, b, mx_aastep( center, uv[ p ] ) );
  32533. const mx_splitlr = ( valuel, valuer, center, texcoord = uv$1() ) => _split( valuel, valuer, center, texcoord, 'x' );
  32534. const mx_splittb = ( valuet, valueb, center, texcoord = uv$1() ) => _split( valuet, valueb, center, texcoord, 'y' );
  32535. const mx_transform_uv = ( uv_scale = 1, uv_offset = 0, uv_geo = uv$1() ) => uv_geo.mul( uv_scale ).add( uv_offset );
  32536. const mx_safepower = ( in1, in2 = 1 ) => {
  32537. in1 = float( in1 );
  32538. return in1.abs().pow( in2 ).mul( in1.sign() );
  32539. };
  32540. const mx_contrast = ( input, amount = 1, pivot = .5 ) => float( input ).sub( pivot ).mul( amount ).add( pivot );
  32541. const mx_noise_float = ( texcoord = uv$1(), amplitude = 1, pivot = 0 ) => mx_perlin_noise_float( texcoord.convert( 'vec2|vec3' ) ).mul( amplitude ).add( pivot );
  32542. //export const mx_noise_vec2 = ( texcoord = uv(), amplitude = 1, pivot = 0 ) => mx_perlin_noise_vec3( texcoord.convert( 'vec2|vec3' ) ).mul( amplitude ).add( pivot );
  32543. const mx_noise_vec3 = ( texcoord = uv$1(), amplitude = 1, pivot = 0 ) => mx_perlin_noise_vec3( texcoord.convert( 'vec2|vec3' ) ).mul( amplitude ).add( pivot );
  32544. const mx_noise_vec4 = ( texcoord = uv$1(), amplitude = 1, pivot = 0 ) => {
  32545. texcoord = texcoord.convert( 'vec2|vec3' ); // overloading type
  32546. const noise_vec4 = vec4( mx_perlin_noise_vec3( texcoord ), mx_perlin_noise_float( texcoord.add( vec2( 19, 73 ) ) ) );
  32547. return noise_vec4.mul( amplitude ).add( pivot );
  32548. };
  32549. const mx_unifiednoise2d = ( noiseType, texcoord = uv$1(), freq = vec2( 1, 1 ), offset = vec2( 0, 0 ), jitter = 1, outmin = 0, outmax = 1, clampoutput = false, octaves = 1, lacunarity = 2, diminish = .5 ) => mx_unifiednoise2d$1( noiseType, texcoord.convert( 'vec2|vec3' ), freq, offset, jitter, outmin, outmax, clampoutput, octaves, lacunarity, diminish );
  32550. const mx_unifiednoise3d = ( noiseType, texcoord = uv$1(), freq = vec2( 1, 1 ), offset = vec2( 0, 0 ), jitter = 1, outmin = 0, outmax = 1, clampoutput = false, octaves = 1, lacunarity = 2, diminish = .5 ) => mx_unifiednoise3d$1( noiseType, texcoord.convert( 'vec2|vec3' ), freq, offset, jitter, outmin, outmax, clampoutput, octaves, lacunarity, diminish );
  32551. const mx_worley_noise_float = ( texcoord = uv$1(), jitter = 1 ) => mx_worley_noise_float$1( texcoord.convert( 'vec2|vec3' ), jitter, int( 1 ) );
  32552. const mx_worley_noise_vec2 = ( texcoord = uv$1(), jitter = 1 ) => mx_worley_noise_vec2$1( texcoord.convert( 'vec2|vec3' ), jitter, int( 1 ) );
  32553. const mx_worley_noise_vec3 = ( texcoord = uv$1(), jitter = 1 ) => mx_worley_noise_vec3$1( texcoord.convert( 'vec2|vec3' ), jitter, int( 1 ) );
  32554. const mx_cell_noise_float = ( texcoord = uv$1() ) => mx_cell_noise_float$1( texcoord.convert( 'vec2|vec3' ) );
  32555. const mx_fractal_noise_float = ( position = uv$1(), octaves = 3, lacunarity = 2, diminish = .5, amplitude = 1 ) => mx_fractal_noise_float$1( position, int( octaves ), lacunarity, diminish ).mul( amplitude );
  32556. const mx_fractal_noise_vec2 = ( position = uv$1(), octaves = 3, lacunarity = 2, diminish = .5, amplitude = 1 ) => mx_fractal_noise_vec2$1( position, int( octaves ), lacunarity, diminish ).mul( amplitude );
  32557. const mx_fractal_noise_vec3 = ( position = uv$1(), octaves = 3, lacunarity = 2, diminish = .5, amplitude = 1 ) => mx_fractal_noise_vec3$1( position, int( octaves ), lacunarity, diminish ).mul( amplitude );
  32558. const mx_fractal_noise_vec4 = ( position = uv$1(), octaves = 3, lacunarity = 2, diminish = .5, amplitude = 1 ) => mx_fractal_noise_vec4$1( position, int( octaves ), lacunarity, diminish ).mul( amplitude );
  32559. // === Moved from MaterialXLoader.js ===
  32560. // Math ops
  32561. const mx_add = ( in1, in2 = float( 0 ) ) => add( in1, in2 );
  32562. const mx_subtract = ( in1, in2 = float( 0 ) ) => sub( in1, in2 );
  32563. const mx_multiply = ( in1, in2 = float( 1 ) ) => mul( in1, in2 );
  32564. const mx_divide = ( in1, in2 = float( 1 ) ) => div( in1, in2 );
  32565. const mx_modulo = ( in1, in2 = float( 1 ) ) => mod( in1, in2 );
  32566. const mx_power = ( in1, in2 = float( 1 ) ) => pow( in1, in2 );
  32567. const mx_atan2 = ( in1 = float( 0 ), in2 = float( 1 ) ) => atan( in1, in2 );
  32568. const mx_timer = () => time;
  32569. const mx_frame = () => frameId;
  32570. const mx_invert = ( in1, amount = float( 1 ) ) => sub( amount, in1 );
  32571. const mx_ifgreater = ( value1, value2, in1, in2 ) => value1.greaterThan( value2 ).mix( in1, in2 );
  32572. const mx_ifgreatereq = ( value1, value2, in1, in2 ) => value1.greaterThanEqual( value2 ).mix( in1, in2 );
  32573. const mx_ifequal = ( value1, value2, in1, in2 ) => value1.equal( value2 ).mix( in1, in2 );
  32574. // Enhanced separate node to support multi-output referencing (outx, outy, outz, outw)
  32575. const mx_separate = ( in1, channelOrOut = null ) => {
  32576. if ( typeof channelOrOut === 'string' ) {
  32577. const map = { x: 0, r: 0, y: 1, g: 1, z: 2, b: 2, w: 3, a: 3 };
  32578. const c = channelOrOut.replace( /^out/, '' ).toLowerCase();
  32579. if ( map[ c ] !== undefined ) return in1.element( map[ c ] );
  32580. }
  32581. if ( typeof channelOrOut === 'number' ) {
  32582. return in1.element( channelOrOut );
  32583. }
  32584. if ( typeof channelOrOut === 'string' && channelOrOut.length === 1 ) {
  32585. const map = { x: 0, r: 0, y: 1, g: 1, z: 2, b: 2, w: 3, a: 3 };
  32586. if ( map[ channelOrOut ] !== undefined ) return in1.element( map[ channelOrOut ] );
  32587. }
  32588. return in1;
  32589. };
  32590. const mx_place2d = (
  32591. texcoord, pivot = vec2( 0.5, 0.5 ), scale = vec2( 1, 1 ), rotate = float( 0 ), offset = vec2( 0, 0 )/*, operationorder = int( 0 )*/
  32592. ) => {
  32593. let uv = texcoord;
  32594. if ( pivot ) uv = uv.sub( pivot );
  32595. if ( scale ) uv = uv.mul( scale );
  32596. if ( rotate ) {
  32597. const rad = rotate.mul( Math.PI / 180.0 );
  32598. const cosR = rad.cos();
  32599. const sinR = rad.sin();
  32600. uv = vec2(
  32601. uv.x.mul( cosR ).sub( uv.y.mul( sinR ) ),
  32602. uv.x.mul( sinR ).add( uv.y.mul( cosR ) )
  32603. );
  32604. }
  32605. if ( pivot ) uv = uv.add( pivot );
  32606. if ( offset ) uv = uv.add( offset );
  32607. return uv;
  32608. };
  32609. const mx_rotate2d = ( input, amount ) => {
  32610. input = vec2( input );
  32611. amount = float( amount );
  32612. const radians = amount.mul( Math.PI / 180.0 );
  32613. return rotate( input, radians );
  32614. };
  32615. const mx_rotate3d = ( input, amount, axis ) => {
  32616. input = vec3( input );
  32617. amount = float( amount );
  32618. axis = vec3( axis );
  32619. const radians = amount.mul( Math.PI / 180.0 );
  32620. const nAxis = axis.normalize();
  32621. const cosA = radians.cos();
  32622. const sinA = radians.sin();
  32623. const oneMinusCosA = float( 1 ).sub( cosA );
  32624. const rot =
  32625. input.mul( cosA )
  32626. .add( nAxis.cross( input ).mul( sinA ) )
  32627. .add( nAxis.mul( nAxis.dot( input ) ).mul( oneMinusCosA ) );
  32628. return rot;
  32629. };
  32630. const mx_heighttonormal = ( input, scale/*, texcoord*/ ) => {
  32631. input = vec3( input );
  32632. scale = float( scale );
  32633. return bumpMap( input, scale );
  32634. };
  32635. /**
  32636. * This computes a parallax corrected normal which is used for box-projected cube mapping (BPCEM).
  32637. *
  32638. * Reference: {@link https://devlog-martinsh.blogspot.com/2011/09/box-projected-cube-environment-mapping.html}
  32639. *
  32640. * ```js
  32641. * const uvNode = getParallaxCorrectNormal( reflectVector, vec3( 200, 100, 100 ), vec3( 0, - 50, 0 ) );
  32642. * material.envNode = pmremTexture( renderTarget.texture, uvNode );
  32643. * ```
  32644. *
  32645. * @tsl
  32646. * @function
  32647. * @param {Node<vec3>} normal - The normal to correct.
  32648. * @param {Node<vec3>} cubeSize - The cube size should reflect the size of the environment (BPCEM is usually applied in closed environments like rooms).
  32649. * @param {Node<vec3>} cubePos - The cube position.
  32650. * @return {Node<vec3>} The parallax corrected normal.
  32651. */
  32652. const getParallaxCorrectNormal = /*@__PURE__*/ Fn( ( [ normal, cubeSize, cubePos ] ) => {
  32653. const nDir = normalize( normal ).toVar();
  32654. const rbmax = sub( float( 0.5 ).mul( cubeSize.sub( cubePos ) ), positionWorld ).div( nDir ).toVar();
  32655. const rbmin = sub( float( -0.5 ).mul( cubeSize.sub( cubePos ) ), positionWorld ).div( nDir ).toVar();
  32656. const rbminmax = vec3().toVar();
  32657. rbminmax.x = nDir.x.greaterThan( float( 0 ) ).select( rbmax.x, rbmin.x );
  32658. rbminmax.y = nDir.y.greaterThan( float( 0 ) ).select( rbmax.y, rbmin.y );
  32659. rbminmax.z = nDir.z.greaterThan( float( 0 ) ).select( rbmax.z, rbmin.z );
  32660. const correction = min$1( rbminmax.x, rbminmax.y, rbminmax.z ).toVar();
  32661. const boxIntersection = positionWorld.add( nDir.mul( correction ) ).toVar();
  32662. return boxIntersection.sub( cubePos );
  32663. } );
  32664. const getShIrradianceAt = /*@__PURE__*/ Fn( ( [ normal, shCoefficients ] ) => {
  32665. // normal is assumed to have unit length
  32666. const x = normal.x, y = normal.y, z = normal.z;
  32667. // band 0
  32668. let result = shCoefficients.element( 0 ).mul( 0.886227 );
  32669. // band 1
  32670. result = result.add( shCoefficients.element( 1 ).mul( 2.0 * 0.511664 ).mul( y ) );
  32671. result = result.add( shCoefficients.element( 2 ).mul( 2.0 * 0.511664 ).mul( z ) );
  32672. result = result.add( shCoefficients.element( 3 ).mul( 2.0 * 0.511664 ).mul( x ) );
  32673. // band 2
  32674. result = result.add( shCoefficients.element( 4 ).mul( 2.0 * 0.429043 ).mul( x ).mul( y ) );
  32675. result = result.add( shCoefficients.element( 5 ).mul( 2.0 * 0.429043 ).mul( y ).mul( z ) );
  32676. result = result.add( shCoefficients.element( 6 ).mul( z.mul( z ).mul( 0.743125 ).sub( 0.247708 ) ) );
  32677. result = result.add( shCoefficients.element( 7 ).mul( 2.0 * 0.429043 ).mul( x ).mul( z ) );
  32678. result = result.add( shCoefficients.element( 8 ).mul( 0.429043 ).mul( mul( x, x ).sub( mul( y, y ) ) ) );
  32679. return result;
  32680. } );
  32681. // constants
  32682. var TSL = /*#__PURE__*/Object.freeze({
  32683. __proto__: null,
  32684. BRDF_GGX: BRDF_GGX,
  32685. BRDF_Lambert: BRDF_Lambert,
  32686. BasicPointShadowFilter: BasicPointShadowFilter,
  32687. BasicShadowFilter: BasicShadowFilter,
  32688. Break: Break,
  32689. Const: Const,
  32690. Continue: Continue,
  32691. DFGApprox: DFGApprox,
  32692. D_GGX: D_GGX,
  32693. Discard: Discard,
  32694. EPSILON: EPSILON,
  32695. F_Schlick: F_Schlick,
  32696. Fn: Fn,
  32697. HALF_PI: HALF_PI,
  32698. INFINITY: INFINITY,
  32699. If: If,
  32700. Loop: Loop,
  32701. NodeAccess: NodeAccess,
  32702. NodeShaderStage: NodeShaderStage,
  32703. NodeType: NodeType,
  32704. NodeUpdateType: NodeUpdateType,
  32705. OnBeforeMaterialUpdate: OnBeforeMaterialUpdate,
  32706. OnBeforeObjectUpdate: OnBeforeObjectUpdate,
  32707. OnMaterialUpdate: OnMaterialUpdate,
  32708. OnObjectUpdate: OnObjectUpdate,
  32709. PCFShadowFilter: PCFShadowFilter,
  32710. PCFSoftShadowFilter: PCFSoftShadowFilter,
  32711. PI: PI,
  32712. PI2: PI2,
  32713. PointShadowFilter: PointShadowFilter,
  32714. Return: Return,
  32715. Schlick_to_F0: Schlick_to_F0,
  32716. ScriptableNodeResources: ScriptableNodeResources,
  32717. ShaderNode: ShaderNode,
  32718. Stack: Stack,
  32719. Switch: Switch,
  32720. TBNViewMatrix: TBNViewMatrix,
  32721. TWO_PI: TWO_PI,
  32722. VSMShadowFilter: VSMShadowFilter,
  32723. V_GGX_SmithCorrelated: V_GGX_SmithCorrelated,
  32724. Var: Var,
  32725. VarIntent: VarIntent,
  32726. abs: abs,
  32727. acesFilmicToneMapping: acesFilmicToneMapping,
  32728. acos: acos,
  32729. add: add,
  32730. addMethodChaining: addMethodChaining,
  32731. addNodeElement: addNodeElement,
  32732. agxToneMapping: agxToneMapping,
  32733. all: all,
  32734. alphaT: alphaT,
  32735. and: and,
  32736. anisotropy: anisotropy,
  32737. anisotropyB: anisotropyB,
  32738. anisotropyT: anisotropyT,
  32739. any: any,
  32740. append: append,
  32741. array: array,
  32742. arrayBuffer: arrayBuffer,
  32743. asin: asin,
  32744. assign: assign,
  32745. atan: atan,
  32746. atan2: atan2,
  32747. atomicAdd: atomicAdd,
  32748. atomicAnd: atomicAnd,
  32749. atomicFunc: atomicFunc,
  32750. atomicLoad: atomicLoad,
  32751. atomicMax: atomicMax,
  32752. atomicMin: atomicMin,
  32753. atomicOr: atomicOr,
  32754. atomicStore: atomicStore,
  32755. atomicSub: atomicSub,
  32756. atomicXor: atomicXor,
  32757. attenuationColor: attenuationColor,
  32758. attenuationDistance: attenuationDistance,
  32759. attribute: attribute,
  32760. attributeArray: attributeArray,
  32761. backgroundBlurriness: backgroundBlurriness,
  32762. backgroundIntensity: backgroundIntensity,
  32763. backgroundRotation: backgroundRotation,
  32764. batch: batch,
  32765. bentNormalView: bentNormalView,
  32766. billboarding: billboarding,
  32767. bitAnd: bitAnd,
  32768. bitNot: bitNot,
  32769. bitOr: bitOr,
  32770. bitXor: bitXor,
  32771. bitangentGeometry: bitangentGeometry,
  32772. bitangentLocal: bitangentLocal,
  32773. bitangentView: bitangentView,
  32774. bitangentWorld: bitangentWorld,
  32775. bitcast: bitcast,
  32776. blendBurn: blendBurn,
  32777. blendColor: blendColor,
  32778. blendDodge: blendDodge,
  32779. blendOverlay: blendOverlay,
  32780. blendScreen: blendScreen,
  32781. blur: blur,
  32782. bool: bool,
  32783. buffer: buffer,
  32784. bufferAttribute: bufferAttribute,
  32785. builtin: builtin,
  32786. bumpMap: bumpMap,
  32787. burn: burn,
  32788. bvec2: bvec2,
  32789. bvec3: bvec3,
  32790. bvec4: bvec4,
  32791. bypass: bypass,
  32792. cache: cache,
  32793. call: call,
  32794. cameraFar: cameraFar,
  32795. cameraIndex: cameraIndex,
  32796. cameraNear: cameraNear,
  32797. cameraNormalMatrix: cameraNormalMatrix,
  32798. cameraPosition: cameraPosition,
  32799. cameraProjectionMatrix: cameraProjectionMatrix,
  32800. cameraProjectionMatrixInverse: cameraProjectionMatrixInverse,
  32801. cameraViewMatrix: cameraViewMatrix,
  32802. cameraViewport: cameraViewport,
  32803. cameraWorldMatrix: cameraWorldMatrix,
  32804. cbrt: cbrt,
  32805. cdl: cdl,
  32806. ceil: ceil,
  32807. checker: checker,
  32808. cineonToneMapping: cineonToneMapping,
  32809. clamp: clamp,
  32810. clearcoat: clearcoat,
  32811. clearcoatNormalView: clearcoatNormalView,
  32812. clearcoatRoughness: clearcoatRoughness,
  32813. code: code,
  32814. color: color,
  32815. colorSpaceToWorking: colorSpaceToWorking,
  32816. colorToDirection: colorToDirection,
  32817. compute: compute,
  32818. computeKernel: computeKernel,
  32819. computeSkinning: computeSkinning,
  32820. context: context,
  32821. convert: convert,
  32822. convertColorSpace: convertColorSpace,
  32823. convertToTexture: convertToTexture,
  32824. cos: cos,
  32825. cross: cross,
  32826. cubeTexture: cubeTexture,
  32827. cubeTextureBase: cubeTextureBase,
  32828. cubeToUV: cubeToUV,
  32829. dFdx: dFdx,
  32830. dFdy: dFdy,
  32831. dashSize: dashSize,
  32832. debug: debug,
  32833. decrement: decrement,
  32834. decrementBefore: decrementBefore,
  32835. defaultBuildStages: defaultBuildStages,
  32836. defaultShaderStages: defaultShaderStages,
  32837. defined: defined,
  32838. degrees: degrees,
  32839. deltaTime: deltaTime,
  32840. densityFog: densityFog,
  32841. densityFogFactor: densityFogFactor,
  32842. depth: depth,
  32843. depthPass: depthPass,
  32844. determinant: determinant,
  32845. difference: difference,
  32846. diffuseColor: diffuseColor,
  32847. diffuseContribution: diffuseContribution,
  32848. directPointLight: directPointLight,
  32849. directionToColor: directionToColor,
  32850. directionToFaceDirection: directionToFaceDirection,
  32851. dispersion: dispersion,
  32852. distance: distance,
  32853. div: div,
  32854. dodge: dodge,
  32855. dot: dot,
  32856. drawIndex: drawIndex,
  32857. dynamicBufferAttribute: dynamicBufferAttribute,
  32858. element: element,
  32859. emissive: emissive,
  32860. equal: equal,
  32861. equals: equals,
  32862. equirectUV: equirectUV,
  32863. exp: exp,
  32864. exp2: exp2,
  32865. expression: expression,
  32866. faceDirection: faceDirection,
  32867. faceForward: faceForward,
  32868. faceforward: faceforward,
  32869. float: float,
  32870. floatBitsToInt: floatBitsToInt,
  32871. floatBitsToUint: floatBitsToUint,
  32872. floor: floor,
  32873. fog: fog,
  32874. fract: fract,
  32875. frameGroup: frameGroup,
  32876. frameId: frameId,
  32877. frontFacing: frontFacing,
  32878. fwidth: fwidth,
  32879. gain: gain,
  32880. gapSize: gapSize,
  32881. getConstNodeType: getConstNodeType,
  32882. getCurrentStack: getCurrentStack,
  32883. getDirection: getDirection,
  32884. getDistanceAttenuation: getDistanceAttenuation,
  32885. getGeometryRoughness: getGeometryRoughness,
  32886. getNormalFromDepth: getNormalFromDepth,
  32887. getParallaxCorrectNormal: getParallaxCorrectNormal,
  32888. getRoughness: getRoughness,
  32889. getScreenPosition: getScreenPosition,
  32890. getShIrradianceAt: getShIrradianceAt,
  32891. getShadowMaterial: getShadowMaterial,
  32892. getShadowRenderObjectFunction: getShadowRenderObjectFunction,
  32893. getTextureIndex: getTextureIndex,
  32894. getViewPosition: getViewPosition,
  32895. ggxConvolution: ggxConvolution,
  32896. globalId: globalId,
  32897. glsl: glsl,
  32898. glslFn: glslFn,
  32899. grayscale: grayscale,
  32900. greaterThan: greaterThan,
  32901. greaterThanEqual: greaterThanEqual,
  32902. hash: hash,
  32903. highpModelNormalViewMatrix: highpModelNormalViewMatrix,
  32904. highpModelViewMatrix: highpModelViewMatrix,
  32905. hue: hue,
  32906. increment: increment,
  32907. incrementBefore: incrementBefore,
  32908. inspector: inspector,
  32909. instance: instance,
  32910. instanceIndex: instanceIndex,
  32911. instancedArray: instancedArray,
  32912. instancedBufferAttribute: instancedBufferAttribute,
  32913. instancedDynamicBufferAttribute: instancedDynamicBufferAttribute,
  32914. instancedMesh: instancedMesh,
  32915. int: int,
  32916. intBitsToFloat: intBitsToFloat,
  32917. interleavedGradientNoise: interleavedGradientNoise,
  32918. inverse: inverse,
  32919. inverseSqrt: inverseSqrt,
  32920. inversesqrt: inversesqrt,
  32921. invocationLocalIndex: invocationLocalIndex,
  32922. invocationSubgroupIndex: invocationSubgroupIndex,
  32923. ior: ior,
  32924. iridescence: iridescence,
  32925. iridescenceIOR: iridescenceIOR,
  32926. iridescenceThickness: iridescenceThickness,
  32927. isolate: isolate,
  32928. ivec2: ivec2,
  32929. ivec3: ivec3,
  32930. ivec4: ivec4,
  32931. js: js,
  32932. label: label,
  32933. length: length,
  32934. lengthSq: lengthSq,
  32935. lessThan: lessThan,
  32936. lessThanEqual: lessThanEqual,
  32937. lightPosition: lightPosition,
  32938. lightProjectionUV: lightProjectionUV,
  32939. lightShadowMatrix: lightShadowMatrix,
  32940. lightTargetDirection: lightTargetDirection,
  32941. lightTargetPosition: lightTargetPosition,
  32942. lightViewPosition: lightViewPosition,
  32943. lightingContext: lightingContext,
  32944. lights: lights,
  32945. linearDepth: linearDepth,
  32946. linearToneMapping: linearToneMapping,
  32947. localId: localId,
  32948. log: log,
  32949. log2: log2,
  32950. logarithmicDepthToViewZ: logarithmicDepthToViewZ,
  32951. luminance: luminance,
  32952. mat2: mat2,
  32953. mat3: mat3,
  32954. mat4: mat4,
  32955. matcapUV: matcapUV,
  32956. materialAO: materialAO,
  32957. materialAlphaTest: materialAlphaTest,
  32958. materialAnisotropy: materialAnisotropy,
  32959. materialAnisotropyVector: materialAnisotropyVector,
  32960. materialAttenuationColor: materialAttenuationColor,
  32961. materialAttenuationDistance: materialAttenuationDistance,
  32962. materialClearcoat: materialClearcoat,
  32963. materialClearcoatNormal: materialClearcoatNormal,
  32964. materialClearcoatRoughness: materialClearcoatRoughness,
  32965. materialColor: materialColor,
  32966. materialDispersion: materialDispersion,
  32967. materialEmissive: materialEmissive,
  32968. materialEnvIntensity: materialEnvIntensity,
  32969. materialEnvRotation: materialEnvRotation,
  32970. materialIOR: materialIOR,
  32971. materialIridescence: materialIridescence,
  32972. materialIridescenceIOR: materialIridescenceIOR,
  32973. materialIridescenceThickness: materialIridescenceThickness,
  32974. materialLightMap: materialLightMap,
  32975. materialLineDashOffset: materialLineDashOffset,
  32976. materialLineDashSize: materialLineDashSize,
  32977. materialLineGapSize: materialLineGapSize,
  32978. materialLineScale: materialLineScale,
  32979. materialLineWidth: materialLineWidth,
  32980. materialMetalness: materialMetalness,
  32981. materialNormal: materialNormal,
  32982. materialOpacity: materialOpacity,
  32983. materialPointSize: materialPointSize,
  32984. materialReference: materialReference,
  32985. materialReflectivity: materialReflectivity,
  32986. materialRefractionRatio: materialRefractionRatio,
  32987. materialRotation: materialRotation,
  32988. materialRoughness: materialRoughness,
  32989. materialSheen: materialSheen,
  32990. materialSheenRoughness: materialSheenRoughness,
  32991. materialShininess: materialShininess,
  32992. materialSpecular: materialSpecular,
  32993. materialSpecularColor: materialSpecularColor,
  32994. materialSpecularIntensity: materialSpecularIntensity,
  32995. materialSpecularStrength: materialSpecularStrength,
  32996. materialThickness: materialThickness,
  32997. materialTransmission: materialTransmission,
  32998. max: max$1,
  32999. maxMipLevel: maxMipLevel,
  33000. mediumpModelViewMatrix: mediumpModelViewMatrix,
  33001. metalness: metalness,
  33002. min: min$1,
  33003. mix: mix,
  33004. mixElement: mixElement,
  33005. mod: mod,
  33006. modInt: modInt,
  33007. modelDirection: modelDirection,
  33008. modelNormalMatrix: modelNormalMatrix,
  33009. modelPosition: modelPosition,
  33010. modelRadius: modelRadius,
  33011. modelScale: modelScale,
  33012. modelViewMatrix: modelViewMatrix,
  33013. modelViewPosition: modelViewPosition,
  33014. modelViewProjection: modelViewProjection,
  33015. modelWorldMatrix: modelWorldMatrix,
  33016. modelWorldMatrixInverse: modelWorldMatrixInverse,
  33017. morphReference: morphReference,
  33018. mrt: mrt,
  33019. mul: mul,
  33020. mx_aastep: mx_aastep,
  33021. mx_add: mx_add,
  33022. mx_atan2: mx_atan2,
  33023. mx_cell_noise_float: mx_cell_noise_float,
  33024. mx_contrast: mx_contrast,
  33025. mx_divide: mx_divide,
  33026. mx_fractal_noise_float: mx_fractal_noise_float,
  33027. mx_fractal_noise_vec2: mx_fractal_noise_vec2,
  33028. mx_fractal_noise_vec3: mx_fractal_noise_vec3,
  33029. mx_fractal_noise_vec4: mx_fractal_noise_vec4,
  33030. mx_frame: mx_frame,
  33031. mx_heighttonormal: mx_heighttonormal,
  33032. mx_hsvtorgb: mx_hsvtorgb,
  33033. mx_ifequal: mx_ifequal,
  33034. mx_ifgreater: mx_ifgreater,
  33035. mx_ifgreatereq: mx_ifgreatereq,
  33036. mx_invert: mx_invert,
  33037. mx_modulo: mx_modulo,
  33038. mx_multiply: mx_multiply,
  33039. mx_noise_float: mx_noise_float,
  33040. mx_noise_vec3: mx_noise_vec3,
  33041. mx_noise_vec4: mx_noise_vec4,
  33042. mx_place2d: mx_place2d,
  33043. mx_power: mx_power,
  33044. mx_ramp4: mx_ramp4,
  33045. mx_ramplr: mx_ramplr,
  33046. mx_ramptb: mx_ramptb,
  33047. mx_rgbtohsv: mx_rgbtohsv,
  33048. mx_rotate2d: mx_rotate2d,
  33049. mx_rotate3d: mx_rotate3d,
  33050. mx_safepower: mx_safepower,
  33051. mx_separate: mx_separate,
  33052. mx_splitlr: mx_splitlr,
  33053. mx_splittb: mx_splittb,
  33054. mx_srgb_texture_to_lin_rec709: mx_srgb_texture_to_lin_rec709,
  33055. mx_subtract: mx_subtract,
  33056. mx_timer: mx_timer,
  33057. mx_transform_uv: mx_transform_uv,
  33058. mx_unifiednoise2d: mx_unifiednoise2d,
  33059. mx_unifiednoise3d: mx_unifiednoise3d,
  33060. mx_worley_noise_float: mx_worley_noise_float,
  33061. mx_worley_noise_vec2: mx_worley_noise_vec2,
  33062. mx_worley_noise_vec3: mx_worley_noise_vec3,
  33063. negate: negate,
  33064. neutralToneMapping: neutralToneMapping,
  33065. nodeArray: nodeArray,
  33066. nodeImmutable: nodeImmutable,
  33067. nodeObject: nodeObject,
  33068. nodeObjectIntent: nodeObjectIntent,
  33069. nodeObjects: nodeObjects,
  33070. nodeProxy: nodeProxy,
  33071. nodeProxyIntent: nodeProxyIntent,
  33072. normalFlat: normalFlat,
  33073. normalGeometry: normalGeometry,
  33074. normalLocal: normalLocal,
  33075. normalMap: normalMap,
  33076. normalView: normalView,
  33077. normalViewGeometry: normalViewGeometry,
  33078. normalWorld: normalWorld,
  33079. normalWorldGeometry: normalWorldGeometry,
  33080. normalize: normalize,
  33081. not: not,
  33082. notEqual: notEqual,
  33083. numWorkgroups: numWorkgroups,
  33084. objectDirection: objectDirection,
  33085. objectGroup: objectGroup,
  33086. objectPosition: objectPosition,
  33087. objectRadius: objectRadius,
  33088. objectScale: objectScale,
  33089. objectViewPosition: objectViewPosition,
  33090. objectWorldMatrix: objectWorldMatrix,
  33091. oneMinus: oneMinus,
  33092. or: or,
  33093. orthographicDepthToViewZ: orthographicDepthToViewZ,
  33094. oscSawtooth: oscSawtooth,
  33095. oscSine: oscSine,
  33096. oscSquare: oscSquare,
  33097. oscTriangle: oscTriangle,
  33098. output: output,
  33099. outputStruct: outputStruct,
  33100. overlay: overlay,
  33101. overloadingFn: overloadingFn,
  33102. parabola: parabola,
  33103. parallaxDirection: parallaxDirection,
  33104. parallaxUV: parallaxUV,
  33105. parameter: parameter,
  33106. pass: pass,
  33107. passTexture: passTexture,
  33108. pcurve: pcurve,
  33109. perspectiveDepthToViewZ: perspectiveDepthToViewZ,
  33110. pmremTexture: pmremTexture,
  33111. pointShadow: pointShadow,
  33112. pointUV: pointUV,
  33113. pointWidth: pointWidth,
  33114. positionGeometry: positionGeometry,
  33115. positionLocal: positionLocal,
  33116. positionPrevious: positionPrevious,
  33117. positionView: positionView,
  33118. positionViewDirection: positionViewDirection,
  33119. positionWorld: positionWorld,
  33120. positionWorldDirection: positionWorldDirection,
  33121. posterize: posterize,
  33122. pow: pow,
  33123. pow2: pow2,
  33124. pow3: pow3,
  33125. pow4: pow4,
  33126. premultiplyAlpha: premultiplyAlpha,
  33127. property: property,
  33128. quadBroadcast: quadBroadcast,
  33129. quadSwapDiagonal: quadSwapDiagonal,
  33130. quadSwapX: quadSwapX,
  33131. quadSwapY: quadSwapY,
  33132. radians: radians,
  33133. rand: rand,
  33134. range: range,
  33135. rangeFog: rangeFog,
  33136. rangeFogFactor: rangeFogFactor,
  33137. reciprocal: reciprocal,
  33138. reference: reference,
  33139. referenceBuffer: referenceBuffer,
  33140. reflect: reflect,
  33141. reflectVector: reflectVector,
  33142. reflectView: reflectView,
  33143. reflector: reflector,
  33144. refract: refract,
  33145. refractVector: refractVector,
  33146. refractView: refractView,
  33147. reinhardToneMapping: reinhardToneMapping,
  33148. remap: remap,
  33149. remapClamp: remapClamp,
  33150. renderGroup: renderGroup,
  33151. renderOutput: renderOutput,
  33152. rendererReference: rendererReference,
  33153. rotate: rotate,
  33154. rotateUV: rotateUV,
  33155. roughness: roughness,
  33156. round: round,
  33157. rtt: rtt,
  33158. sRGBTransferEOTF: sRGBTransferEOTF,
  33159. sRGBTransferOETF: sRGBTransferOETF,
  33160. sample: sample,
  33161. sampler: sampler,
  33162. samplerComparison: samplerComparison,
  33163. saturate: saturate,
  33164. saturation: saturation,
  33165. screen: screen,
  33166. screenCoordinate: screenCoordinate,
  33167. screenDPR: screenDPR,
  33168. screenSize: screenSize,
  33169. screenUV: screenUV,
  33170. scriptable: scriptable,
  33171. scriptableValue: scriptableValue,
  33172. select: select,
  33173. setCurrentStack: setCurrentStack,
  33174. setName: setName,
  33175. shaderStages: shaderStages,
  33176. shadow: shadow,
  33177. shadowPositionWorld: shadowPositionWorld,
  33178. shapeCircle: shapeCircle,
  33179. sharedUniformGroup: sharedUniformGroup,
  33180. sheen: sheen,
  33181. sheenRoughness: sheenRoughness,
  33182. shiftLeft: shiftLeft,
  33183. shiftRight: shiftRight,
  33184. shininess: shininess,
  33185. sign: sign,
  33186. sin: sin,
  33187. sinc: sinc,
  33188. skinning: skinning,
  33189. smoothstep: smoothstep,
  33190. smoothstepElement: smoothstepElement,
  33191. specularColor: specularColor,
  33192. specularColorBlended: specularColorBlended,
  33193. specularF90: specularF90,
  33194. spherizeUV: spherizeUV,
  33195. split: split,
  33196. spritesheetUV: spritesheetUV,
  33197. sqrt: sqrt,
  33198. stack: stack,
  33199. step: step,
  33200. stepElement: stepElement,
  33201. storage: storage,
  33202. storageBarrier: storageBarrier,
  33203. storageObject: storageObject,
  33204. storageTexture: storageTexture,
  33205. string: string,
  33206. struct: struct,
  33207. sub: sub,
  33208. subBuild: subBuild,
  33209. subgroupAdd: subgroupAdd,
  33210. subgroupAll: subgroupAll,
  33211. subgroupAnd: subgroupAnd,
  33212. subgroupAny: subgroupAny,
  33213. subgroupBallot: subgroupBallot,
  33214. subgroupBroadcast: subgroupBroadcast,
  33215. subgroupBroadcastFirst: subgroupBroadcastFirst,
  33216. subgroupElect: subgroupElect,
  33217. subgroupExclusiveAdd: subgroupExclusiveAdd,
  33218. subgroupExclusiveMul: subgroupExclusiveMul,
  33219. subgroupInclusiveAdd: subgroupInclusiveAdd,
  33220. subgroupInclusiveMul: subgroupInclusiveMul,
  33221. subgroupIndex: subgroupIndex,
  33222. subgroupMax: subgroupMax,
  33223. subgroupMin: subgroupMin,
  33224. subgroupMul: subgroupMul,
  33225. subgroupOr: subgroupOr,
  33226. subgroupShuffle: subgroupShuffle,
  33227. subgroupShuffleDown: subgroupShuffleDown,
  33228. subgroupShuffleUp: subgroupShuffleUp,
  33229. subgroupShuffleXor: subgroupShuffleXor,
  33230. subgroupSize: subgroupSize,
  33231. subgroupXor: subgroupXor,
  33232. tan: tan,
  33233. tangentGeometry: tangentGeometry,
  33234. tangentLocal: tangentLocal,
  33235. tangentView: tangentView,
  33236. tangentWorld: tangentWorld,
  33237. texture: texture,
  33238. texture3D: texture3D,
  33239. texture3DLevel: texture3DLevel,
  33240. texture3DLoad: texture3DLoad,
  33241. textureBarrier: textureBarrier,
  33242. textureBicubic: textureBicubic,
  33243. textureBicubicLevel: textureBicubicLevel,
  33244. textureCubeUV: textureCubeUV,
  33245. textureLevel: textureLevel,
  33246. textureLoad: textureLoad,
  33247. textureSize: textureSize,
  33248. textureStore: textureStore,
  33249. thickness: thickness,
  33250. time: time,
  33251. toneMapping: toneMapping,
  33252. toneMappingExposure: toneMappingExposure,
  33253. toonOutlinePass: toonOutlinePass,
  33254. transformDirection: transformDirection,
  33255. transformNormal: transformNormal,
  33256. transformNormalToView: transformNormalToView,
  33257. transformedClearcoatNormalView: transformedClearcoatNormalView,
  33258. transformedNormalView: transformedNormalView,
  33259. transformedNormalWorld: transformedNormalWorld,
  33260. transmission: transmission,
  33261. transpose: transpose,
  33262. triNoise3D: triNoise3D,
  33263. triplanarTexture: triplanarTexture,
  33264. triplanarTextures: triplanarTextures,
  33265. trunc: trunc,
  33266. uint: uint,
  33267. uintBitsToFloat: uintBitsToFloat,
  33268. uniform: uniform,
  33269. uniformArray: uniformArray,
  33270. uniformCubeTexture: uniformCubeTexture,
  33271. uniformFlow: uniformFlow,
  33272. uniformGroup: uniformGroup,
  33273. uniformTexture: uniformTexture,
  33274. unpremultiplyAlpha: unpremultiplyAlpha,
  33275. userData: userData,
  33276. uv: uv$1,
  33277. uvec2: uvec2,
  33278. uvec3: uvec3,
  33279. uvec4: uvec4,
  33280. varying: varying,
  33281. varyingProperty: varyingProperty,
  33282. vec2: vec2,
  33283. vec3: vec3,
  33284. vec4: vec4,
  33285. vectorComponents: vectorComponents,
  33286. velocity: velocity,
  33287. vertexColor: vertexColor,
  33288. vertexIndex: vertexIndex,
  33289. vertexStage: vertexStage,
  33290. vibrance: vibrance,
  33291. viewZToLogarithmicDepth: viewZToLogarithmicDepth,
  33292. viewZToOrthographicDepth: viewZToOrthographicDepth,
  33293. viewZToPerspectiveDepth: viewZToPerspectiveDepth,
  33294. viewport: viewport,
  33295. viewportCoordinate: viewportCoordinate,
  33296. viewportDepthTexture: viewportDepthTexture,
  33297. viewportLinearDepth: viewportLinearDepth,
  33298. viewportMipTexture: viewportMipTexture,
  33299. viewportResolution: viewportResolution,
  33300. viewportSafeUV: viewportSafeUV,
  33301. viewportSharedTexture: viewportSharedTexture,
  33302. viewportSize: viewportSize,
  33303. viewportTexture: viewportTexture,
  33304. viewportUV: viewportUV,
  33305. wgsl: wgsl,
  33306. wgslFn: wgslFn,
  33307. workgroupArray: workgroupArray,
  33308. workgroupBarrier: workgroupBarrier,
  33309. workgroupId: workgroupId,
  33310. workingToColorSpace: workingToColorSpace,
  33311. xor: xor
  33312. });
  33313. const _clearColor = /*@__PURE__*/ new Color4();
  33314. /**
  33315. * This renderer module manages the background.
  33316. *
  33317. * @private
  33318. * @augments DataMap
  33319. */
  33320. class Background extends DataMap {
  33321. /**
  33322. * Constructs a new background management component.
  33323. *
  33324. * @param {Renderer} renderer - The renderer.
  33325. * @param {Nodes} nodes - Renderer component for managing nodes related logic.
  33326. */
  33327. constructor( renderer, nodes ) {
  33328. super();
  33329. /**
  33330. * The renderer.
  33331. *
  33332. * @type {Renderer}
  33333. */
  33334. this.renderer = renderer;
  33335. /**
  33336. * Renderer component for managing nodes related logic.
  33337. *
  33338. * @type {Nodes}
  33339. */
  33340. this.nodes = nodes;
  33341. }
  33342. /**
  33343. * Updates the background for the given scene. Depending on how `Scene.background`
  33344. * or `Scene.backgroundNode` are configured, this method might configure a simple clear
  33345. * or add a mesh to the render list for rendering the background as a textured plane
  33346. * or skybox.
  33347. *
  33348. * @param {Scene} scene - The scene.
  33349. * @param {RenderList} renderList - The current render list.
  33350. * @param {RenderContext} renderContext - The current render context.
  33351. */
  33352. update( scene, renderList, renderContext ) {
  33353. const renderer = this.renderer;
  33354. const background = this.nodes.getBackgroundNode( scene ) || scene.background;
  33355. let forceClear = false;
  33356. if ( background === null ) {
  33357. // no background settings, use clear color configuration from the renderer
  33358. renderer._clearColor.getRGB( _clearColor );
  33359. _clearColor.a = renderer._clearColor.a;
  33360. } else if ( background.isColor === true ) {
  33361. // background is an opaque color
  33362. background.getRGB( _clearColor );
  33363. _clearColor.a = 1;
  33364. forceClear = true;
  33365. } else if ( background.isNode === true ) {
  33366. const sceneData = this.get( scene );
  33367. const backgroundNode = background;
  33368. _clearColor.copy( renderer._clearColor );
  33369. let backgroundMesh = sceneData.backgroundMesh;
  33370. if ( backgroundMesh === undefined ) {
  33371. const backgroundMeshNode = context( vec4( backgroundNode ).mul( backgroundIntensity ), {
  33372. // @TODO: Add Texture2D support using node context
  33373. getUV: () => backgroundRotation.mul( normalWorldGeometry ),
  33374. getTextureLevel: () => backgroundBlurriness
  33375. } );
  33376. let viewProj = modelViewProjection;
  33377. viewProj = viewProj.setZ( viewProj.w );
  33378. const nodeMaterial = new NodeMaterial();
  33379. nodeMaterial.name = 'Background.material';
  33380. nodeMaterial.side = BackSide;
  33381. nodeMaterial.depthTest = false;
  33382. nodeMaterial.depthWrite = false;
  33383. nodeMaterial.allowOverride = false;
  33384. nodeMaterial.fog = false;
  33385. nodeMaterial.lights = false;
  33386. nodeMaterial.vertexNode = viewProj;
  33387. nodeMaterial.colorNode = backgroundMeshNode;
  33388. sceneData.backgroundMeshNode = backgroundMeshNode;
  33389. sceneData.backgroundMesh = backgroundMesh = new Mesh( new SphereGeometry( 1, 32, 32 ), nodeMaterial );
  33390. backgroundMesh.frustumCulled = false;
  33391. backgroundMesh.name = 'Background.mesh';
  33392. backgroundMesh.onBeforeRender = function ( renderer, scene, camera ) {
  33393. this.matrixWorld.copyPosition( camera.matrixWorld );
  33394. };
  33395. function onBackgroundDispose() {
  33396. background.removeEventListener( 'dispose', onBackgroundDispose );
  33397. backgroundMesh.material.dispose();
  33398. backgroundMesh.geometry.dispose();
  33399. }
  33400. background.addEventListener( 'dispose', onBackgroundDispose );
  33401. }
  33402. const backgroundCacheKey = backgroundNode.getCacheKey();
  33403. if ( sceneData.backgroundCacheKey !== backgroundCacheKey ) {
  33404. sceneData.backgroundMeshNode.node = vec4( backgroundNode ).mul( backgroundIntensity );
  33405. sceneData.backgroundMeshNode.needsUpdate = true;
  33406. backgroundMesh.material.needsUpdate = true;
  33407. sceneData.backgroundCacheKey = backgroundCacheKey;
  33408. }
  33409. renderList.unshift( backgroundMesh, backgroundMesh.geometry, backgroundMesh.material, 0, 0, null, null );
  33410. } else {
  33411. error( 'Renderer: Unsupported background configuration.', background );
  33412. }
  33413. //
  33414. const environmentBlendMode = renderer.xr.getEnvironmentBlendMode();
  33415. if ( environmentBlendMode === 'additive' ) {
  33416. _clearColor.set( 0, 0, 0, 1 );
  33417. } else if ( environmentBlendMode === 'alpha-blend' ) {
  33418. _clearColor.set( 0, 0, 0, 0 );
  33419. }
  33420. //
  33421. if ( renderer.autoClear === true || forceClear === true ) {
  33422. const clearColorValue = renderContext.clearColorValue;
  33423. clearColorValue.r = _clearColor.r;
  33424. clearColorValue.g = _clearColor.g;
  33425. clearColorValue.b = _clearColor.b;
  33426. clearColorValue.a = _clearColor.a;
  33427. // premultiply alpha
  33428. if ( renderer.backend.isWebGLBackend === true || renderer.alpha === true ) {
  33429. clearColorValue.r *= clearColorValue.a;
  33430. clearColorValue.g *= clearColorValue.a;
  33431. clearColorValue.b *= clearColorValue.a;
  33432. }
  33433. //
  33434. renderContext.depthClearValue = renderer._clearDepth;
  33435. renderContext.stencilClearValue = renderer._clearStencil;
  33436. renderContext.clearColor = renderer.autoClearColor === true;
  33437. renderContext.clearDepth = renderer.autoClearDepth === true;
  33438. renderContext.clearStencil = renderer.autoClearStencil === true;
  33439. } else {
  33440. renderContext.clearColor = false;
  33441. renderContext.clearDepth = false;
  33442. renderContext.clearStencil = false;
  33443. }
  33444. }
  33445. }
  33446. let _id$7 = 0;
  33447. /**
  33448. * A bind group represents a collection of bindings and thus a collection
  33449. * or resources. Bind groups are assigned to pipelines to provide them
  33450. * with the required resources (like uniform buffers or textures).
  33451. *
  33452. * @private
  33453. */
  33454. class BindGroup {
  33455. /**
  33456. * Constructs a new bind group.
  33457. *
  33458. * @param {string} name - The bind group's name.
  33459. * @param {Array<Binding>} bindings - An array of bindings.
  33460. * @param {number} index - The group index.
  33461. * @param {Array<Binding>} bindingsReference - An array of reference bindings.
  33462. */
  33463. constructor( name = '', bindings = [], index = 0, bindingsReference = [] ) {
  33464. /**
  33465. * The bind group's name.
  33466. *
  33467. * @type {string}
  33468. */
  33469. this.name = name;
  33470. /**
  33471. * An array of bindings.
  33472. *
  33473. * @type {Array<Binding>}
  33474. */
  33475. this.bindings = bindings;
  33476. /**
  33477. * The group index.
  33478. *
  33479. * @type {number}
  33480. */
  33481. this.index = index;
  33482. /**
  33483. * An array of reference bindings.
  33484. *
  33485. * @type {Array<Binding>}
  33486. */
  33487. this.bindingsReference = bindingsReference;
  33488. /**
  33489. * The group's ID.
  33490. *
  33491. * @type {number}
  33492. */
  33493. this.id = _id$7 ++;
  33494. }
  33495. }
  33496. /**
  33497. * This module represents the state of a node builder after it was
  33498. * used to build the nodes for a render object. The state holds the
  33499. * results of the build for further processing in the renderer.
  33500. *
  33501. * Render objects with identical cache keys share the same node builder state.
  33502. *
  33503. * @private
  33504. */
  33505. class NodeBuilderState {
  33506. /**
  33507. * Constructs a new node builder state.
  33508. *
  33509. * @param {string} vertexShader - The native vertex shader code.
  33510. * @param {string} fragmentShader - The native fragment shader code.
  33511. * @param {string} computeShader - The native compute shader code.
  33512. * @param {Array<NodeAttribute>} nodeAttributes - An array of node attributes.
  33513. * @param {Array<BindGroup>} bindings - An array of bind groups.
  33514. * @param {Array<Node>} updateNodes - An array of nodes that implement their `update()` method.
  33515. * @param {Array<Node>} updateBeforeNodes - An array of nodes that implement their `updateBefore()` method.
  33516. * @param {Array<Node>} updateAfterNodes - An array of nodes that implement their `updateAfter()` method.
  33517. * @param {NodeMaterialObserver} observer - A node material observer.
  33518. * @param {Array<Object>} transforms - An array with transform attribute objects. Only relevant when using compute shaders with WebGL 2.
  33519. */
  33520. constructor( vertexShader, fragmentShader, computeShader, nodeAttributes, bindings, updateNodes, updateBeforeNodes, updateAfterNodes, observer, transforms = [] ) {
  33521. /**
  33522. * The native vertex shader code.
  33523. *
  33524. * @type {string}
  33525. */
  33526. this.vertexShader = vertexShader;
  33527. /**
  33528. * The native fragment shader code.
  33529. *
  33530. * @type {string}
  33531. */
  33532. this.fragmentShader = fragmentShader;
  33533. /**
  33534. * The native compute shader code.
  33535. *
  33536. * @type {string}
  33537. */
  33538. this.computeShader = computeShader;
  33539. /**
  33540. * An array with transform attribute objects.
  33541. * Only relevant when using compute shaders with WebGL 2.
  33542. *
  33543. * @type {Array<Object>}
  33544. */
  33545. this.transforms = transforms;
  33546. /**
  33547. * An array of node attributes representing
  33548. * the attributes of the shaders.
  33549. *
  33550. * @type {Array<NodeAttribute>}
  33551. */
  33552. this.nodeAttributes = nodeAttributes;
  33553. /**
  33554. * An array of bind groups representing the uniform or storage
  33555. * buffers, texture or samplers of the shader.
  33556. *
  33557. * @type {Array<BindGroup>}
  33558. */
  33559. this.bindings = bindings;
  33560. /**
  33561. * An array of nodes that implement their `update()` method.
  33562. *
  33563. * @type {Array<Node>}
  33564. */
  33565. this.updateNodes = updateNodes;
  33566. /**
  33567. * An array of nodes that implement their `updateBefore()` method.
  33568. *
  33569. * @type {Array<Node>}
  33570. */
  33571. this.updateBeforeNodes = updateBeforeNodes;
  33572. /**
  33573. * An array of nodes that implement their `updateAfter()` method.
  33574. *
  33575. * @type {Array<Node>}
  33576. */
  33577. this.updateAfterNodes = updateAfterNodes;
  33578. /**
  33579. * A node material observer.
  33580. *
  33581. * @type {NodeMaterialObserver}
  33582. */
  33583. this.observer = observer;
  33584. /**
  33585. * How often this state is used by render objects.
  33586. *
  33587. * @type {number}
  33588. */
  33589. this.usedTimes = 0;
  33590. }
  33591. /**
  33592. * This method is used to create a array of bind groups based
  33593. * on the existing bind groups of this state. Shared groups are
  33594. * not cloned.
  33595. *
  33596. * @return {Array<BindGroup>} A array of bind groups.
  33597. */
  33598. createBindings() {
  33599. const bindings = [];
  33600. for ( const instanceGroup of this.bindings ) {
  33601. const shared = instanceGroup.bindings[ 0 ].groupNode.shared; // All bindings in the group must have the same groupNode.
  33602. if ( shared !== true ) {
  33603. const bindingsGroup = new BindGroup( instanceGroup.name, [], instanceGroup.index, instanceGroup.bindingsReference );
  33604. bindings.push( bindingsGroup );
  33605. for ( const instanceBinding of instanceGroup.bindings ) {
  33606. bindingsGroup.bindings.push( instanceBinding.clone() );
  33607. }
  33608. } else {
  33609. bindings.push( instanceGroup );
  33610. }
  33611. }
  33612. return bindings;
  33613. }
  33614. }
  33615. /**
  33616. * {@link NodeBuilder} is going to create instances of this class during the build process
  33617. * of nodes. They represent the final shader attributes that are going to be generated
  33618. * by the builder. Arrays of node attributes is maintained in {@link NodeBuilder#attributes}
  33619. * and {@link NodeBuilder#bufferAttributes} for this purpose.
  33620. */
  33621. class NodeAttribute {
  33622. /**
  33623. * Constructs a new node attribute.
  33624. *
  33625. * @param {string} name - The name of the attribute.
  33626. * @param {string} type - The type of the attribute.
  33627. * @param {?Node} node - An optional reference to the node.
  33628. */
  33629. constructor( name, type, node = null ) {
  33630. /**
  33631. * This flag can be used for type testing.
  33632. *
  33633. * @type {boolean}
  33634. * @readonly
  33635. * @default true
  33636. */
  33637. this.isNodeAttribute = true;
  33638. /**
  33639. * The name of the attribute.
  33640. *
  33641. * @type {string}
  33642. */
  33643. this.name = name;
  33644. /**
  33645. * The type of the attribute.
  33646. *
  33647. * @type {string}
  33648. */
  33649. this.type = type;
  33650. /**
  33651. * An optional reference to the node.
  33652. *
  33653. * @type {?Node}
  33654. * @default null
  33655. */
  33656. this.node = node;
  33657. }
  33658. }
  33659. /**
  33660. * {@link NodeBuilder} is going to create instances of this class during the build process
  33661. * of nodes. They represent the final shader uniforms that are going to be generated
  33662. * by the builder. A dictionary of node uniforms is maintained in {@link NodeBuilder#uniforms}
  33663. * for this purpose.
  33664. */
  33665. class NodeUniform {
  33666. /**
  33667. * Constructs a new node uniform.
  33668. *
  33669. * @param {string} name - The name of the uniform.
  33670. * @param {string} type - The type of the uniform.
  33671. * @param {UniformNode} node - An reference to the node.
  33672. */
  33673. constructor( name, type, node ) {
  33674. /**
  33675. * This flag can be used for type testing.
  33676. *
  33677. * @type {boolean}
  33678. * @readonly
  33679. * @default true
  33680. */
  33681. this.isNodeUniform = true;
  33682. /**
  33683. * The name of the uniform.
  33684. *
  33685. * @type {string}
  33686. */
  33687. this.name = name;
  33688. /**
  33689. * The type of the uniform.
  33690. *
  33691. * @type {string}
  33692. */
  33693. this.type = type;
  33694. /**
  33695. * An reference to the node.
  33696. *
  33697. * @type {UniformNode}
  33698. */
  33699. this.node = node;
  33700. }
  33701. /**
  33702. * The value of the uniform node.
  33703. *
  33704. * @type {any}
  33705. */
  33706. get value() {
  33707. return this.node.value;
  33708. }
  33709. set value( val ) {
  33710. this.node.value = val;
  33711. }
  33712. /**
  33713. * The id of the uniform node.
  33714. *
  33715. * @type {number}
  33716. */
  33717. get id() {
  33718. return this.node.id;
  33719. }
  33720. /**
  33721. * The uniform node's group.
  33722. *
  33723. * @type {UniformGroupNode}
  33724. */
  33725. get groupNode() {
  33726. return this.node.groupNode;
  33727. }
  33728. }
  33729. /**
  33730. * {@link NodeBuilder} is going to create instances of this class during the build process
  33731. * of nodes. They represent the final shader variables that are going to be generated
  33732. * by the builder. A dictionary of node variables is maintained in {@link NodeBuilder#vars} for
  33733. * this purpose.
  33734. */
  33735. class NodeVar {
  33736. /**
  33737. * Constructs a new node variable.
  33738. *
  33739. * @param {string} name - The name of the variable.
  33740. * @param {string} type - The type of the variable.
  33741. * @param {boolean} [readOnly=false] - The read-only flag.
  33742. * @param {?number} [count=null] - The size.
  33743. */
  33744. constructor( name, type, readOnly = false, count = null ) {
  33745. /**
  33746. * This flag can be used for type testing.
  33747. *
  33748. * @type {boolean}
  33749. * @readonly
  33750. * @default true
  33751. */
  33752. this.isNodeVar = true;
  33753. /**
  33754. * The name of the variable.
  33755. *
  33756. * @type {string}
  33757. */
  33758. this.name = name;
  33759. /**
  33760. * The type of the variable.
  33761. *
  33762. * @type {string}
  33763. */
  33764. this.type = type;
  33765. /**
  33766. * The read-only flag.
  33767. *
  33768. * @type {boolean}
  33769. */
  33770. this.readOnly = readOnly;
  33771. /**
  33772. * The size.
  33773. *
  33774. * @type {?number}
  33775. */
  33776. this.count = count;
  33777. }
  33778. }
  33779. /**
  33780. * {@link NodeBuilder} is going to create instances of this class during the build process
  33781. * of nodes. They represent the final shader varyings that are going to be generated
  33782. * by the builder. An array of node varyings is maintained in {@link NodeBuilder#varyings} for
  33783. * this purpose.
  33784. *
  33785. * @augments NodeVar
  33786. */
  33787. class NodeVarying extends NodeVar {
  33788. /**
  33789. * Constructs a new node varying.
  33790. *
  33791. * @param {string} name - The name of the varying.
  33792. * @param {string} type - The type of the varying.
  33793. * @param {?string} interpolationType - The interpolation type of the varying.
  33794. * @param {?string} interpolationSampling - The interpolation sampling type of the varying.
  33795. */
  33796. constructor( name, type, interpolationType = null, interpolationSampling = null ) {
  33797. super( name, type );
  33798. /**
  33799. * Whether this varying requires interpolation or not. This property can be used
  33800. * to check if the varying can be optimized for a variable.
  33801. *
  33802. * @type {boolean}
  33803. * @default false
  33804. */
  33805. this.needsInterpolation = false;
  33806. /**
  33807. * This flag can be used for type testing.
  33808. *
  33809. * @type {boolean}
  33810. * @readonly
  33811. * @default true
  33812. */
  33813. this.isNodeVarying = true;
  33814. /**
  33815. * The interpolation type of the varying data.
  33816. *
  33817. * @type {?string}
  33818. * @default null
  33819. */
  33820. this.interpolationType = interpolationType;
  33821. /**
  33822. * The interpolation sampling type of varying data.
  33823. *
  33824. * @type {?string}
  33825. * @default null
  33826. */
  33827. this.interpolationSampling = interpolationSampling;
  33828. }
  33829. }
  33830. /**
  33831. * {@link NodeBuilder} is going to create instances of this class during the build process
  33832. * of nodes. They represent user-defined, native shader code portions that are going to be
  33833. * injected by the builder. A dictionary of node codes is maintained in {@link NodeBuilder#codes}
  33834. * for this purpose.
  33835. */
  33836. class NodeCode {
  33837. /**
  33838. * Constructs a new code node.
  33839. *
  33840. * @param {string} name - The name of the code.
  33841. * @param {string} type - The node type.
  33842. * @param {string} [code=''] - The native shader code.
  33843. */
  33844. constructor( name, type, code = '' ) {
  33845. /**
  33846. * The name of the code.
  33847. *
  33848. * @type {string}
  33849. */
  33850. this.name = name;
  33851. /**
  33852. * The node type.
  33853. *
  33854. * @type {string}
  33855. */
  33856. this.type = type;
  33857. /**
  33858. * The native shader code.
  33859. *
  33860. * @type {string}
  33861. * @default ''
  33862. */
  33863. this.code = code;
  33864. Object.defineProperty( this, 'isNodeCode', { value: true } );
  33865. }
  33866. }
  33867. let _id$6 = 0;
  33868. /**
  33869. * This utility class is used in {@link NodeBuilder} as an internal
  33870. * cache data structure for node data.
  33871. */
  33872. class NodeCache {
  33873. /**
  33874. * Constructs a new node cache.
  33875. *
  33876. * @param {?NodeCache} parent - A reference to a parent cache.
  33877. */
  33878. constructor( parent = null ) {
  33879. /**
  33880. * The id of the cache.
  33881. *
  33882. * @type {number}
  33883. * @readonly
  33884. */
  33885. this.id = _id$6 ++;
  33886. /**
  33887. * A weak map for managing node data.
  33888. *
  33889. * @type {WeakMap<Node, Object>}
  33890. */
  33891. this.nodesData = new WeakMap();
  33892. /**
  33893. * Reference to a parent node cache.
  33894. *
  33895. * @type {?NodeCache}
  33896. * @default null
  33897. */
  33898. this.parent = parent;
  33899. }
  33900. /**
  33901. * Returns the data for the given node.
  33902. *
  33903. * @param {Node} node - The node.
  33904. * @return {?Object} The data for the node.
  33905. */
  33906. getData( node ) {
  33907. let data = this.nodesData.get( node );
  33908. if ( data === undefined && this.parent !== null ) {
  33909. data = this.parent.getData( node );
  33910. }
  33911. return data;
  33912. }
  33913. /**
  33914. * Sets the data for a given node.
  33915. *
  33916. * @param {Node} node - The node.
  33917. * @param {Object} data - The data that should be cached.
  33918. */
  33919. setData( node, data ) {
  33920. this.nodesData.set( node, data );
  33921. }
  33922. }
  33923. class StructType {
  33924. constructor( name, members ) {
  33925. this.name = name;
  33926. this.members = members;
  33927. this.output = false;
  33928. }
  33929. }
  33930. /**
  33931. * Abstract base class for uniforms.
  33932. *
  33933. * @abstract
  33934. * @private
  33935. */
  33936. class Uniform {
  33937. /**
  33938. * Constructs a new uniform.
  33939. *
  33940. * @param {string} name - The uniform's name.
  33941. * @param {any} value - The uniform's value.
  33942. */
  33943. constructor( name, value ) {
  33944. /**
  33945. * The uniform's name.
  33946. *
  33947. * @type {string}
  33948. */
  33949. this.name = name;
  33950. /**
  33951. * The uniform's value.
  33952. *
  33953. * @type {any}
  33954. */
  33955. this.value = value;
  33956. /**
  33957. * Used to build the uniform buffer according to the STD140 layout.
  33958. * Derived uniforms will set this property to a data type specific
  33959. * value.
  33960. *
  33961. * @type {number}
  33962. */
  33963. this.boundary = 0;
  33964. /**
  33965. * The item size. Derived uniforms will set this property to a data
  33966. * type specific value.
  33967. *
  33968. * @type {number}
  33969. */
  33970. this.itemSize = 0;
  33971. /**
  33972. * This property is set by {@link UniformsGroup} and marks
  33973. * the start position in the uniform buffer.
  33974. *
  33975. * @type {number}
  33976. */
  33977. this.offset = 0;
  33978. }
  33979. /**
  33980. * Sets the uniform's value.
  33981. *
  33982. * @param {any} value - The value to set.
  33983. */
  33984. setValue( value ) {
  33985. this.value = value;
  33986. }
  33987. /**
  33988. * Returns the uniform's value.
  33989. *
  33990. * @return {any} The value.
  33991. */
  33992. getValue() {
  33993. return this.value;
  33994. }
  33995. }
  33996. /**
  33997. * Represents a Number uniform.
  33998. *
  33999. * @private
  34000. * @augments Uniform
  34001. */
  34002. class NumberUniform extends Uniform {
  34003. /**
  34004. * Constructs a new Number uniform.
  34005. *
  34006. * @param {string} name - The uniform's name.
  34007. * @param {number} value - The uniform's value.
  34008. */
  34009. constructor( name, value = 0 ) {
  34010. super( name, value );
  34011. /**
  34012. * This flag can be used for type testing.
  34013. *
  34014. * @type {boolean}
  34015. * @readonly
  34016. * @default true
  34017. */
  34018. this.isNumberUniform = true;
  34019. this.boundary = 4;
  34020. this.itemSize = 1;
  34021. }
  34022. }
  34023. /**
  34024. * Represents a Vector2 uniform.
  34025. *
  34026. * @private
  34027. * @augments Uniform
  34028. */
  34029. class Vector2Uniform extends Uniform {
  34030. /**
  34031. * Constructs a new Number uniform.
  34032. *
  34033. * @param {string} name - The uniform's name.
  34034. * @param {Vector2} value - The uniform's value.
  34035. */
  34036. constructor( name, value = new Vector2() ) {
  34037. super( name, value );
  34038. /**
  34039. * This flag can be used for type testing.
  34040. *
  34041. * @type {boolean}
  34042. * @readonly
  34043. * @default true
  34044. */
  34045. this.isVector2Uniform = true;
  34046. this.boundary = 8;
  34047. this.itemSize = 2;
  34048. }
  34049. }
  34050. /**
  34051. * Represents a Vector3 uniform.
  34052. *
  34053. * @private
  34054. * @augments Uniform
  34055. */
  34056. class Vector3Uniform extends Uniform {
  34057. /**
  34058. * Constructs a new Number uniform.
  34059. *
  34060. * @param {string} name - The uniform's name.
  34061. * @param {Vector3} value - The uniform's value.
  34062. */
  34063. constructor( name, value = new Vector3() ) {
  34064. super( name, value );
  34065. /**
  34066. * This flag can be used for type testing.
  34067. *
  34068. * @type {boolean}
  34069. * @readonly
  34070. * @default true
  34071. */
  34072. this.isVector3Uniform = true;
  34073. this.boundary = 16;
  34074. this.itemSize = 3;
  34075. }
  34076. }
  34077. /**
  34078. * Represents a Vector4 uniform.
  34079. *
  34080. * @private
  34081. * @augments Uniform
  34082. */
  34083. class Vector4Uniform extends Uniform {
  34084. /**
  34085. * Constructs a new Number uniform.
  34086. *
  34087. * @param {string} name - The uniform's name.
  34088. * @param {Vector4} value - The uniform's value.
  34089. */
  34090. constructor( name, value = new Vector4() ) {
  34091. super( name, value );
  34092. /**
  34093. * This flag can be used for type testing.
  34094. *
  34095. * @type {boolean}
  34096. * @readonly
  34097. * @default true
  34098. */
  34099. this.isVector4Uniform = true;
  34100. this.boundary = 16;
  34101. this.itemSize = 4;
  34102. }
  34103. }
  34104. /**
  34105. * Represents a Color uniform.
  34106. *
  34107. * @private
  34108. * @augments Uniform
  34109. */
  34110. class ColorUniform extends Uniform {
  34111. /**
  34112. * Constructs a new Number uniform.
  34113. *
  34114. * @param {string} name - The uniform's name.
  34115. * @param {Color} value - The uniform's value.
  34116. */
  34117. constructor( name, value = new Color() ) {
  34118. super( name, value );
  34119. /**
  34120. * This flag can be used for type testing.
  34121. *
  34122. * @type {boolean}
  34123. * @readonly
  34124. * @default true
  34125. */
  34126. this.isColorUniform = true;
  34127. this.boundary = 16;
  34128. this.itemSize = 3;
  34129. }
  34130. }
  34131. /**
  34132. * Represents a Matrix2 uniform.
  34133. *
  34134. * @private
  34135. * @augments Uniform
  34136. */
  34137. class Matrix2Uniform extends Uniform {
  34138. /**
  34139. * Constructs a new Number uniform.
  34140. *
  34141. * @param {string} name - The uniform's name.
  34142. * @param {Matrix2} value - The uniform's value.
  34143. */
  34144. constructor( name, value = new Matrix2() ) {
  34145. super( name, value );
  34146. /**
  34147. * This flag can be used for type testing.
  34148. *
  34149. * @type {boolean}
  34150. * @readonly
  34151. * @default true
  34152. */
  34153. this.isMatrix2Uniform = true;
  34154. this.boundary = 8;
  34155. this.itemSize = 4;
  34156. }
  34157. }
  34158. /**
  34159. * Represents a Matrix3 uniform.
  34160. *
  34161. * @private
  34162. * @augments Uniform
  34163. */
  34164. class Matrix3Uniform extends Uniform {
  34165. /**
  34166. * Constructs a new Number uniform.
  34167. *
  34168. * @param {string} name - The uniform's name.
  34169. * @param {Matrix3} value - The uniform's value.
  34170. */
  34171. constructor( name, value = new Matrix3() ) {
  34172. super( name, value );
  34173. /**
  34174. * This flag can be used for type testing.
  34175. *
  34176. * @type {boolean}
  34177. * @readonly
  34178. * @default true
  34179. */
  34180. this.isMatrix3Uniform = true;
  34181. this.boundary = 48;
  34182. this.itemSize = 12;
  34183. }
  34184. }
  34185. /**
  34186. * Represents a Matrix4 uniform.
  34187. *
  34188. * @private
  34189. * @augments Uniform
  34190. */
  34191. class Matrix4Uniform extends Uniform {
  34192. /**
  34193. * Constructs a new Number uniform.
  34194. *
  34195. * @param {string} name - The uniform's name.
  34196. * @param {Matrix4} value - The uniform's value.
  34197. */
  34198. constructor( name, value = new Matrix4() ) {
  34199. super( name, value );
  34200. /**
  34201. * This flag can be used for type testing.
  34202. *
  34203. * @type {boolean}
  34204. * @readonly
  34205. * @default true
  34206. */
  34207. this.isMatrix4Uniform = true;
  34208. this.boundary = 64;
  34209. this.itemSize = 16;
  34210. }
  34211. }
  34212. /**
  34213. * A special form of Number uniform binding type.
  34214. * It's value is managed by a node object.
  34215. *
  34216. * @private
  34217. * @augments NumberUniform
  34218. */
  34219. class NumberNodeUniform extends NumberUniform {
  34220. /**
  34221. * Constructs a new node-based Number uniform.
  34222. *
  34223. * @param {NodeUniform} nodeUniform - The node uniform.
  34224. */
  34225. constructor( nodeUniform ) {
  34226. super( nodeUniform.name, nodeUniform.value );
  34227. /**
  34228. * The node uniform.
  34229. *
  34230. * @type {NodeUniform}
  34231. */
  34232. this.nodeUniform = nodeUniform;
  34233. }
  34234. /**
  34235. * Overwritten to return the value of the node uniform.
  34236. *
  34237. * @return {number} The value.
  34238. */
  34239. getValue() {
  34240. return this.nodeUniform.value;
  34241. }
  34242. /**
  34243. * Returns the node uniform data type.
  34244. *
  34245. * @return {string} The data type.
  34246. */
  34247. getType() {
  34248. return this.nodeUniform.type;
  34249. }
  34250. }
  34251. /**
  34252. * A special form of Vector2 uniform binding type.
  34253. * It's value is managed by a node object.
  34254. *
  34255. * @private
  34256. * @augments Vector2Uniform
  34257. */
  34258. class Vector2NodeUniform extends Vector2Uniform {
  34259. /**
  34260. * Constructs a new node-based Vector2 uniform.
  34261. *
  34262. * @param {NodeUniform} nodeUniform - The node uniform.
  34263. */
  34264. constructor( nodeUniform ) {
  34265. super( nodeUniform.name, nodeUniform.value );
  34266. /**
  34267. * The node uniform.
  34268. *
  34269. * @type {NodeUniform}
  34270. */
  34271. this.nodeUniform = nodeUniform;
  34272. }
  34273. /**
  34274. * Overwritten to return the value of the node uniform.
  34275. *
  34276. * @return {Vector2} The value.
  34277. */
  34278. getValue() {
  34279. return this.nodeUniform.value;
  34280. }
  34281. /**
  34282. * Returns the node uniform data type.
  34283. *
  34284. * @return {string} The data type.
  34285. */
  34286. getType() {
  34287. return this.nodeUniform.type;
  34288. }
  34289. }
  34290. /**
  34291. * A special form of Vector3 uniform binding type.
  34292. * It's value is managed by a node object.
  34293. *
  34294. * @private
  34295. * @augments Vector3Uniform
  34296. */
  34297. class Vector3NodeUniform extends Vector3Uniform {
  34298. /**
  34299. * Constructs a new node-based Vector3 uniform.
  34300. *
  34301. * @param {NodeUniform} nodeUniform - The node uniform.
  34302. */
  34303. constructor( nodeUniform ) {
  34304. super( nodeUniform.name, nodeUniform.value );
  34305. /**
  34306. * The node uniform.
  34307. *
  34308. * @type {NodeUniform}
  34309. */
  34310. this.nodeUniform = nodeUniform;
  34311. }
  34312. /**
  34313. * Overwritten to return the value of the node uniform.
  34314. *
  34315. * @return {Vector3} The value.
  34316. */
  34317. getValue() {
  34318. return this.nodeUniform.value;
  34319. }
  34320. /**
  34321. * Returns the node uniform data type.
  34322. *
  34323. * @return {string} The data type.
  34324. */
  34325. getType() {
  34326. return this.nodeUniform.type;
  34327. }
  34328. }
  34329. /**
  34330. * A special form of Vector4 uniform binding type.
  34331. * It's value is managed by a node object.
  34332. *
  34333. * @private
  34334. * @augments Vector4Uniform
  34335. */
  34336. class Vector4NodeUniform extends Vector4Uniform {
  34337. /**
  34338. * Constructs a new node-based Vector4 uniform.
  34339. *
  34340. * @param {NodeUniform} nodeUniform - The node uniform.
  34341. */
  34342. constructor( nodeUniform ) {
  34343. super( nodeUniform.name, nodeUniform.value );
  34344. /**
  34345. * The node uniform.
  34346. *
  34347. * @type {NodeUniform}
  34348. */
  34349. this.nodeUniform = nodeUniform;
  34350. }
  34351. /**
  34352. * Overwritten to return the value of the node uniform.
  34353. *
  34354. * @return {Vector4} The value.
  34355. */
  34356. getValue() {
  34357. return this.nodeUniform.value;
  34358. }
  34359. /**
  34360. * Returns the node uniform data type.
  34361. *
  34362. * @return {string} The data type.
  34363. */
  34364. getType() {
  34365. return this.nodeUniform.type;
  34366. }
  34367. }
  34368. /**
  34369. * A special form of Color uniform binding type.
  34370. * It's value is managed by a node object.
  34371. *
  34372. * @private
  34373. * @augments ColorUniform
  34374. */
  34375. class ColorNodeUniform extends ColorUniform {
  34376. /**
  34377. * Constructs a new node-based Color uniform.
  34378. *
  34379. * @param {NodeUniform} nodeUniform - The node uniform.
  34380. */
  34381. constructor( nodeUniform ) {
  34382. super( nodeUniform.name, nodeUniform.value );
  34383. /**
  34384. * The node uniform.
  34385. *
  34386. * @type {NodeUniform}
  34387. */
  34388. this.nodeUniform = nodeUniform;
  34389. }
  34390. /**
  34391. * Overwritten to return the value of the node uniform.
  34392. *
  34393. * @return {Color} The value.
  34394. */
  34395. getValue() {
  34396. return this.nodeUniform.value;
  34397. }
  34398. /**
  34399. * Returns the node uniform data type.
  34400. *
  34401. * @return {string} The data type.
  34402. */
  34403. getType() {
  34404. return this.nodeUniform.type;
  34405. }
  34406. }
  34407. /**
  34408. * A special form of Matrix2 uniform binding type.
  34409. * It's value is managed by a node object.
  34410. *
  34411. * @private
  34412. * @augments Matrix2Uniform
  34413. */
  34414. class Matrix2NodeUniform extends Matrix2Uniform {
  34415. /**
  34416. * Constructs a new node-based Matrix2 uniform.
  34417. *
  34418. * @param {NodeUniform} nodeUniform - The node uniform.
  34419. */
  34420. constructor( nodeUniform ) {
  34421. super( nodeUniform.name, nodeUniform.value );
  34422. /**
  34423. * The node uniform.
  34424. *
  34425. * @type {NodeUniform}
  34426. */
  34427. this.nodeUniform = nodeUniform;
  34428. }
  34429. /**
  34430. * Overwritten to return the value of the node uniform.
  34431. *
  34432. * @return {Matrix2} The value.
  34433. */
  34434. getValue() {
  34435. return this.nodeUniform.value;
  34436. }
  34437. /**
  34438. * Returns the node uniform data type.
  34439. *
  34440. * @return {string} The data type.
  34441. */
  34442. getType() {
  34443. return this.nodeUniform.type;
  34444. }
  34445. }
  34446. /**
  34447. * A special form of Matrix3 uniform binding type.
  34448. * It's value is managed by a node object.
  34449. *
  34450. * @private
  34451. * @augments Matrix3Uniform
  34452. */
  34453. class Matrix3NodeUniform extends Matrix3Uniform {
  34454. /**
  34455. * Constructs a new node-based Matrix3 uniform.
  34456. *
  34457. * @param {NodeUniform} nodeUniform - The node uniform.
  34458. */
  34459. constructor( nodeUniform ) {
  34460. super( nodeUniform.name, nodeUniform.value );
  34461. /**
  34462. * The node uniform.
  34463. *
  34464. * @type {NodeUniform}
  34465. */
  34466. this.nodeUniform = nodeUniform;
  34467. }
  34468. /**
  34469. * Overwritten to return the value of the node uniform.
  34470. *
  34471. * @return {Matrix3} The value.
  34472. */
  34473. getValue() {
  34474. return this.nodeUniform.value;
  34475. }
  34476. /**
  34477. * Returns the node uniform data type.
  34478. *
  34479. * @return {string} The data type.
  34480. */
  34481. getType() {
  34482. return this.nodeUniform.type;
  34483. }
  34484. }
  34485. /**
  34486. * A special form of Matrix4 uniform binding type.
  34487. * It's value is managed by a node object.
  34488. *
  34489. * @private
  34490. * @augments Matrix4Uniform
  34491. */
  34492. class Matrix4NodeUniform extends Matrix4Uniform {
  34493. /**
  34494. * Constructs a new node-based Matrix4 uniform.
  34495. *
  34496. * @param {NodeUniform} nodeUniform - The node uniform.
  34497. */
  34498. constructor( nodeUniform ) {
  34499. super( nodeUniform.name, nodeUniform.value );
  34500. /**
  34501. * The node uniform.
  34502. *
  34503. * @type {NodeUniform}
  34504. */
  34505. this.nodeUniform = nodeUniform;
  34506. }
  34507. /**
  34508. * Overwritten to return the value of the node uniform.
  34509. *
  34510. * @return {Matrix4} The value.
  34511. */
  34512. getValue() {
  34513. return this.nodeUniform.value;
  34514. }
  34515. /**
  34516. * Returns the node uniform data type.
  34517. *
  34518. * @return {string} The data type.
  34519. */
  34520. getType() {
  34521. return this.nodeUniform.type;
  34522. }
  34523. }
  34524. let _id$5 = 0;
  34525. const rendererCache = new WeakMap();
  34526. const typeFromArray = new Map( [
  34527. [ Int8Array, 'int' ],
  34528. [ Int16Array, 'int' ],
  34529. [ Int32Array, 'int' ],
  34530. [ Uint8Array, 'uint' ],
  34531. [ Uint16Array, 'uint' ],
  34532. [ Uint32Array, 'uint' ],
  34533. [ Float32Array, 'float' ]
  34534. ] );
  34535. const toFloat = ( value ) => {
  34536. if ( /e/g.test( value ) ) {
  34537. return String( value ).replace( /\+/g, '' );
  34538. } else {
  34539. value = Number( value );
  34540. return value + ( value % 1 ? '' : '.0' );
  34541. }
  34542. };
  34543. /**
  34544. * Base class for builders which generate a shader program based
  34545. * on a 3D object and its node material definition.
  34546. */
  34547. class NodeBuilder {
  34548. /**
  34549. * Constructs a new node builder.
  34550. *
  34551. * @param {Object3D} object - The 3D object.
  34552. * @param {Renderer} renderer - The current renderer.
  34553. * @param {NodeParser} parser - A reference to a node parser.
  34554. */
  34555. constructor( object, renderer, parser ) {
  34556. /**
  34557. * The 3D object.
  34558. *
  34559. * @type {Object3D}
  34560. */
  34561. this.object = object;
  34562. /**
  34563. * The material of the 3D object.
  34564. *
  34565. * @type {?Material}
  34566. */
  34567. this.material = ( object && object.material ) || null;
  34568. /**
  34569. * The geometry of the 3D object.
  34570. *
  34571. * @type {?BufferGeometry}
  34572. */
  34573. this.geometry = ( object && object.geometry ) || null;
  34574. /**
  34575. * The current renderer.
  34576. *
  34577. * @type {Renderer}
  34578. */
  34579. this.renderer = renderer;
  34580. /**
  34581. * A reference to a node parser.
  34582. *
  34583. * @type {NodeParser}
  34584. */
  34585. this.parser = parser;
  34586. /**
  34587. * The scene the 3D object belongs to.
  34588. *
  34589. * @type {?Scene}
  34590. * @default null
  34591. */
  34592. this.scene = null;
  34593. /**
  34594. * The camera the 3D object is rendered with.
  34595. *
  34596. * @type {?Camera}
  34597. * @default null
  34598. */
  34599. this.camera = null;
  34600. /**
  34601. * A list of all nodes the builder is processing
  34602. * for this 3D object.
  34603. *
  34604. * @type {Array<Node>}
  34605. */
  34606. this.nodes = [];
  34607. /**
  34608. * A list of all sequential nodes.
  34609. *
  34610. * @type {Array<Node>}
  34611. */
  34612. this.sequentialNodes = [];
  34613. /**
  34614. * A list of all nodes which {@link Node#update} method should be executed.
  34615. *
  34616. * @type {Array<Node>}
  34617. */
  34618. this.updateNodes = [];
  34619. /**
  34620. * A list of all nodes which {@link Node#updateBefore} method should be executed.
  34621. *
  34622. * @type {Array<Node>}
  34623. */
  34624. this.updateBeforeNodes = [];
  34625. /**
  34626. * A list of all nodes which {@link Node#updateAfter} method should be executed.
  34627. *
  34628. * @type {Array<Node>}
  34629. */
  34630. this.updateAfterNodes = [];
  34631. /**
  34632. * A dictionary that assigns each node to a unique hash.
  34633. *
  34634. * @type {Object<number,Node>}
  34635. */
  34636. this.hashNodes = {};
  34637. /**
  34638. * A reference to a node material observer.
  34639. *
  34640. * @type {?NodeMaterialObserver}
  34641. * @default null
  34642. */
  34643. this.observer = null;
  34644. /**
  34645. * A reference to the current lights node.
  34646. *
  34647. * @type {?LightsNode}
  34648. * @default null
  34649. */
  34650. this.lightsNode = null;
  34651. /**
  34652. * A reference to the current environment node.
  34653. *
  34654. * @type {?Node}
  34655. * @default null
  34656. */
  34657. this.environmentNode = null;
  34658. /**
  34659. * A reference to the current fog node.
  34660. *
  34661. * @type {?Node}
  34662. * @default null
  34663. */
  34664. this.fogNode = null;
  34665. /**
  34666. * The current clipping context.
  34667. *
  34668. * @type {?ClippingContext}
  34669. */
  34670. this.clippingContext = null;
  34671. /**
  34672. * The generated vertex shader.
  34673. *
  34674. * @type {?string}
  34675. */
  34676. this.vertexShader = null;
  34677. /**
  34678. * The generated fragment shader.
  34679. *
  34680. * @type {?string}
  34681. */
  34682. this.fragmentShader = null;
  34683. /**
  34684. * The generated compute shader.
  34685. *
  34686. * @type {?string}
  34687. */
  34688. this.computeShader = null;
  34689. /**
  34690. * Nodes used in the primary flow of code generation.
  34691. *
  34692. * @type {Object<string,Array<Node>>}
  34693. */
  34694. this.flowNodes = { vertex: [], fragment: [], compute: [] };
  34695. /**
  34696. * Nodes code from `.flowNodes`.
  34697. *
  34698. * @type {Object<string,string>}
  34699. */
  34700. this.flowCode = { vertex: '', fragment: '', compute: '' };
  34701. /**
  34702. * This dictionary holds the node uniforms of the builder.
  34703. * The uniforms are maintained in an array for each shader stage.
  34704. *
  34705. * @type {Object}
  34706. */
  34707. this.uniforms = { vertex: [], fragment: [], compute: [], index: 0 };
  34708. /**
  34709. * This dictionary holds the output structs of the builder.
  34710. * The structs are maintained in an array for each shader stage.
  34711. *
  34712. * @type {Object}
  34713. */
  34714. this.structs = { vertex: [], fragment: [], compute: [], index: 0 };
  34715. /**
  34716. * This dictionary holds the types of the builder.
  34717. *
  34718. * @type {Object}
  34719. */
  34720. this.types = { vertex: [], fragment: [], compute: [], index: 0 };
  34721. /**
  34722. * This dictionary holds the bindings for each shader stage.
  34723. *
  34724. * @type {Object}
  34725. */
  34726. this.bindings = { vertex: {}, fragment: {}, compute: {} };
  34727. /**
  34728. * This dictionary maintains the binding indices per bind group.
  34729. *
  34730. * @type {Object}
  34731. */
  34732. this.bindingsIndexes = {};
  34733. /**
  34734. * Reference to the array of bind groups.
  34735. *
  34736. * @type {?Array<BindGroup>}
  34737. */
  34738. this.bindGroups = null;
  34739. /**
  34740. * This array holds the node attributes of this builder
  34741. * created via {@link AttributeNode}.
  34742. *
  34743. * @type {Array<NodeAttribute>}
  34744. */
  34745. this.attributes = [];
  34746. /**
  34747. * This array holds the node attributes of this builder
  34748. * created via {@link BufferAttributeNode}.
  34749. *
  34750. * @type {Array<NodeAttribute>}
  34751. */
  34752. this.bufferAttributes = [];
  34753. /**
  34754. * This array holds the node varyings of this builder.
  34755. *
  34756. * @type {Array<NodeVarying>}
  34757. */
  34758. this.varyings = [];
  34759. /**
  34760. * This dictionary holds the (native) node codes of this builder.
  34761. * The codes are maintained in an array for each shader stage.
  34762. *
  34763. * @type {Object<string,Array<NodeCode>>}
  34764. */
  34765. this.codes = {};
  34766. /**
  34767. * This dictionary holds the node variables of this builder.
  34768. * The variables are maintained in an array for each shader stage.
  34769. * This dictionary is also used to count the number of variables
  34770. * according to their type (const, vars).
  34771. *
  34772. * @type {Object<string,Array<NodeVar>|number>}
  34773. */
  34774. this.vars = {};
  34775. /**
  34776. * This dictionary holds the declarations for each shader stage.
  34777. *
  34778. * @type {Object}
  34779. */
  34780. this.declarations = {};
  34781. /**
  34782. * Current code flow.
  34783. * All code generated in this stack will be stored in `.flow`.
  34784. *
  34785. * @type {{code: string}}
  34786. */
  34787. this.flow = { code: '' };
  34788. /**
  34789. * A chain of nodes.
  34790. * Used to check recursive calls in node-graph.
  34791. *
  34792. * @type {Array<Node>}
  34793. */
  34794. this.chaining = [];
  34795. /**
  34796. * The current stack.
  34797. * This reflects the current process in the code block hierarchy,
  34798. * it is useful to know if the current process is inside a conditional for example.
  34799. *
  34800. * @type {StackNode}
  34801. */
  34802. this.stack = stack();
  34803. /**
  34804. * List of stack nodes.
  34805. * The current stack hierarchy is stored in an array.
  34806. *
  34807. * @type {Array<StackNode>}
  34808. */
  34809. this.stacks = [];
  34810. /**
  34811. * A tab value. Used for shader string generation.
  34812. *
  34813. * @type {string}
  34814. * @default '\t'
  34815. */
  34816. this.tab = '\t';
  34817. /**
  34818. * Reference to the current function node.
  34819. *
  34820. * @type {?FunctionNode}
  34821. * @default null
  34822. */
  34823. this.currentFunctionNode = null;
  34824. /**
  34825. * The builder's context.
  34826. *
  34827. * @type {Object}
  34828. */
  34829. this.context = {
  34830. material: this.material
  34831. };
  34832. /**
  34833. * The builder's cache.
  34834. *
  34835. * @type {NodeCache}
  34836. */
  34837. this.cache = new NodeCache();
  34838. /**
  34839. * Since the {@link NodeBuilder#cache} might be temporarily
  34840. * overwritten by other caches, this member retains the reference
  34841. * to the builder's own cache.
  34842. *
  34843. * @type {NodeCache}
  34844. * @default this.cache
  34845. */
  34846. this.globalCache = this.cache;
  34847. this.flowsData = new WeakMap();
  34848. /**
  34849. * The current shader stage.
  34850. *
  34851. * @type {?('vertex'|'fragment'|'compute'|'any')}
  34852. */
  34853. this.shaderStage = null;
  34854. /**
  34855. * The current build stage.
  34856. *
  34857. * @type {?('setup'|'analyze'|'generate')}
  34858. */
  34859. this.buildStage = null;
  34860. /**
  34861. * The sub-build layers.
  34862. *
  34863. * @type {Array<SubBuildNode>}
  34864. * @default []
  34865. */
  34866. this.subBuildLayers = [];
  34867. /**
  34868. * The active stack nodes.
  34869. *
  34870. * @type {Array<StackNode>}
  34871. */
  34872. this.activeStacks = [];
  34873. /**
  34874. * The current sub-build TSL function(Fn).
  34875. *
  34876. * @type {?string}
  34877. * @default null
  34878. */
  34879. this.subBuildFn = null;
  34880. /**
  34881. * The current TSL function(Fn) call node.
  34882. *
  34883. * @type {?Node}
  34884. * @default null
  34885. */
  34886. this.fnCall = null;
  34887. Object.defineProperty( this, 'id', { value: _id$5 ++ } );
  34888. }
  34889. /**
  34890. * Whether the material is opaque or not.
  34891. *
  34892. * @return {boolean} Whether the material is opaque or not.
  34893. */
  34894. isOpaque() {
  34895. const material = this.material;
  34896. return material.transparent === false && material.blending === NormalBlending && material.alphaToCoverage === false;
  34897. }
  34898. /**
  34899. * Returns the bind groups of the current renderer.
  34900. *
  34901. * @return {ChainMap} The cache.
  34902. */
  34903. getBindGroupsCache() {
  34904. let bindGroupsCache = rendererCache.get( this.renderer );
  34905. if ( bindGroupsCache === undefined ) {
  34906. bindGroupsCache = new ChainMap();
  34907. rendererCache.set( this.renderer, bindGroupsCache );
  34908. }
  34909. return bindGroupsCache;
  34910. }
  34911. /**
  34912. * Factory method for creating an instance of {@link RenderTarget} with the given
  34913. * dimensions and options.
  34914. *
  34915. * @param {number} width - The width of the render target.
  34916. * @param {number} height - The height of the render target.
  34917. * @param {Object} options - The options of the render target.
  34918. * @return {RenderTarget} The render target.
  34919. */
  34920. createRenderTarget( width, height, options ) {
  34921. return new RenderTarget( width, height, options );
  34922. }
  34923. /**
  34924. * Factory method for creating an instance of {@link CubeRenderTarget} with the given
  34925. * dimensions and options.
  34926. *
  34927. * @param {number} size - The size of the cube render target.
  34928. * @param {Object} options - The options of the cube render target.
  34929. * @return {CubeRenderTarget} The cube render target.
  34930. */
  34931. createCubeRenderTarget( size, options ) {
  34932. return new CubeRenderTarget( size, options );
  34933. }
  34934. /**
  34935. * Whether the given node is included in the internal array of nodes or not.
  34936. *
  34937. * @param {Node} node - The node to test.
  34938. * @return {boolean} Whether the given node is included in the internal array of nodes or not.
  34939. */
  34940. includes( node ) {
  34941. return this.nodes.includes( node );
  34942. }
  34943. /**
  34944. * Returns the output struct name which is required by
  34945. * {@link OutputStructNode}.
  34946. *
  34947. * @abstract
  34948. * @return {string} The name of the output struct.
  34949. */
  34950. getOutputStructName() {}
  34951. /**
  34952. * Returns a bind group for the given group name and binding.
  34953. *
  34954. * @private
  34955. * @param {string} groupName - The group name.
  34956. * @param {Array<NodeUniformsGroup>} bindings - List of bindings.
  34957. * @return {BindGroup} The bind group
  34958. */
  34959. _getBindGroup( groupName, bindings ) {
  34960. const bindGroupsCache = this.getBindGroupsCache();
  34961. //
  34962. const bindingsArray = [];
  34963. let sharedGroup = true;
  34964. for ( const binding of bindings ) {
  34965. bindingsArray.push( binding );
  34966. sharedGroup = sharedGroup && binding.groupNode.shared !== true;
  34967. }
  34968. //
  34969. let bindGroup;
  34970. if ( sharedGroup ) {
  34971. bindGroup = bindGroupsCache.get( bindingsArray );
  34972. if ( bindGroup === undefined ) {
  34973. bindGroup = new BindGroup( groupName, bindingsArray, this.bindingsIndexes[ groupName ].group, bindingsArray );
  34974. bindGroupsCache.set( bindingsArray, bindGroup );
  34975. }
  34976. } else {
  34977. bindGroup = new BindGroup( groupName, bindingsArray, this.bindingsIndexes[ groupName ].group, bindingsArray );
  34978. }
  34979. return bindGroup;
  34980. }
  34981. /**
  34982. * Returns an array of node uniform groups for the given group name and shader stage.
  34983. *
  34984. * @param {string} groupName - The group name.
  34985. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  34986. * @return {Array<NodeUniformsGroup>} The array of node uniform groups.
  34987. */
  34988. getBindGroupArray( groupName, shaderStage ) {
  34989. const bindings = this.bindings[ shaderStage ];
  34990. let bindGroup = bindings[ groupName ];
  34991. if ( bindGroup === undefined ) {
  34992. if ( this.bindingsIndexes[ groupName ] === undefined ) {
  34993. this.bindingsIndexes[ groupName ] = { binding: 0, group: Object.keys( this.bindingsIndexes ).length };
  34994. }
  34995. bindings[ groupName ] = bindGroup = [];
  34996. }
  34997. return bindGroup;
  34998. }
  34999. /**
  35000. * Returns a list bindings of all shader stages separated by groups.
  35001. *
  35002. * @return {Array<BindGroup>} The list of bindings.
  35003. */
  35004. getBindings() {
  35005. let bindingsGroups = this.bindGroups;
  35006. if ( bindingsGroups === null ) {
  35007. const groups = {};
  35008. const bindings = this.bindings;
  35009. for ( const shaderStage of shaderStages ) {
  35010. for ( const groupName in bindings[ shaderStage ] ) {
  35011. const uniforms = bindings[ shaderStage ][ groupName ];
  35012. const groupUniforms = groups[ groupName ] || ( groups[ groupName ] = [] );
  35013. groupUniforms.push( ...uniforms );
  35014. }
  35015. }
  35016. bindingsGroups = [];
  35017. for ( const groupName in groups ) {
  35018. const group = groups[ groupName ];
  35019. const bindingsGroup = this._getBindGroup( groupName, group );
  35020. bindingsGroups.push( bindingsGroup );
  35021. }
  35022. this.bindGroups = bindingsGroups;
  35023. }
  35024. return bindingsGroups;
  35025. }
  35026. /**
  35027. * Sorts the bind groups and updates {@link NodeBuilder#bindingsIndexes}.
  35028. */
  35029. sortBindingGroups() {
  35030. const bindingsGroups = this.getBindings();
  35031. bindingsGroups.sort( ( a, b ) => ( a.bindings[ 0 ].groupNode.order - b.bindings[ 0 ].groupNode.order ) );
  35032. for ( let i = 0; i < bindingsGroups.length; i ++ ) {
  35033. const bindingGroup = bindingsGroups[ i ];
  35034. this.bindingsIndexes[ bindingGroup.name ].group = i;
  35035. bindingGroup.index = i;
  35036. }
  35037. }
  35038. /**
  35039. * The builder maintains each node in a hash-based dictionary.
  35040. * This method sets the given node (value) with the given hash (key) into this dictionary.
  35041. *
  35042. * @param {Node} node - The node to add.
  35043. * @param {number} hash - The hash of the node.
  35044. */
  35045. setHashNode( node, hash ) {
  35046. this.hashNodes[ hash ] = node;
  35047. }
  35048. /**
  35049. * Adds a node to this builder.
  35050. *
  35051. * @param {Node} node - The node to add.
  35052. */
  35053. addNode( node ) {
  35054. if ( this.nodes.includes( node ) === false ) {
  35055. this.nodes.push( node );
  35056. this.setHashNode( node, node.getHash( this ) );
  35057. }
  35058. }
  35059. /**
  35060. * It is used to add Nodes that will be used as FRAME and RENDER events,
  35061. * and need to follow a certain sequence in the calls to work correctly.
  35062. * This function should be called after 'setup()' in the 'build()' process to ensure that the child nodes are processed first.
  35063. *
  35064. * @param {Node} node - The node to add.
  35065. */
  35066. addSequentialNode( node ) {
  35067. if ( this.sequentialNodes.includes( node ) === false ) {
  35068. this.sequentialNodes.push( node );
  35069. }
  35070. }
  35071. /**
  35072. * Checks the update types of nodes
  35073. */
  35074. buildUpdateNodes() {
  35075. for ( const node of this.nodes ) {
  35076. const updateType = node.getUpdateType();
  35077. if ( updateType !== NodeUpdateType.NONE ) {
  35078. this.updateNodes.push( node );
  35079. }
  35080. }
  35081. for ( const node of this.sequentialNodes ) {
  35082. const updateBeforeType = node.getUpdateBeforeType();
  35083. const updateAfterType = node.getUpdateAfterType();
  35084. if ( updateBeforeType !== NodeUpdateType.NONE ) {
  35085. this.updateBeforeNodes.push( node );
  35086. }
  35087. if ( updateAfterType !== NodeUpdateType.NONE ) {
  35088. this.updateAfterNodes.push( node );
  35089. }
  35090. }
  35091. }
  35092. /**
  35093. * A reference the current node which is the
  35094. * last node in the chain of nodes.
  35095. *
  35096. * @type {Node}
  35097. */
  35098. get currentNode() {
  35099. return this.chaining[ this.chaining.length - 1 ];
  35100. }
  35101. /**
  35102. * Whether the given texture is filtered or not.
  35103. *
  35104. * @param {Texture} texture - The texture to check.
  35105. * @return {boolean} Whether the given texture is filtered or not.
  35106. */
  35107. isFilteredTexture( texture ) {
  35108. return ( texture.magFilter === LinearFilter || texture.magFilter === LinearMipmapNearestFilter || texture.magFilter === NearestMipmapLinearFilter || texture.magFilter === LinearMipmapLinearFilter ||
  35109. texture.minFilter === LinearFilter || texture.minFilter === LinearMipmapNearestFilter || texture.minFilter === NearestMipmapLinearFilter || texture.minFilter === LinearMipmapLinearFilter );
  35110. }
  35111. /**
  35112. * Adds the given node to the internal node chain.
  35113. * This is used to check recursive calls in node-graph.
  35114. *
  35115. * @param {Node} node - The node to add.
  35116. */
  35117. addChain( node ) {
  35118. /*
  35119. if ( this.chaining.indexOf( node ) !== - 1 ) {
  35120. warn( 'Recursive node: ', node );
  35121. }
  35122. */
  35123. this.chaining.push( node );
  35124. }
  35125. /**
  35126. * Removes the given node from the internal node chain.
  35127. *
  35128. * @param {Node} node - The node to remove.
  35129. */
  35130. removeChain( node ) {
  35131. const lastChain = this.chaining.pop();
  35132. if ( lastChain !== node ) {
  35133. throw new Error( 'NodeBuilder: Invalid node chaining!' );
  35134. }
  35135. }
  35136. /**
  35137. * Returns the native shader method name for a given generic name. E.g.
  35138. * the method name `textureDimensions` matches the WGSL name but must be
  35139. * resolved to `textureSize` in GLSL.
  35140. *
  35141. * @abstract
  35142. * @param {string} method - The method name to resolve.
  35143. * @return {string} The resolved method name.
  35144. */
  35145. getMethod( method ) {
  35146. return method;
  35147. }
  35148. /**
  35149. * Returns the native snippet for a ternary operation. E.g. GLSL would output
  35150. * a ternary op as `cond ? x : y` whereas WGSL would output it as `select(y, x, cond)`
  35151. *
  35152. * @abstract
  35153. * @param {string} condSnippet - The condition determining which expression gets resolved.
  35154. * @param {string} ifSnippet - The expression to resolve to if the condition is true.
  35155. * @param {string} elseSnippet - The expression to resolve to if the condition is false.
  35156. * @return {string} The resolved method name.
  35157. */
  35158. getTernary( /* condSnippet, ifSnippet, elseSnippet*/ ) {
  35159. return null;
  35160. }
  35161. /**
  35162. * Returns a node for the given hash, see {@link NodeBuilder#setHashNode}.
  35163. *
  35164. * @param {number} hash - The hash of the node.
  35165. * @return {Node} The found node.
  35166. */
  35167. getNodeFromHash( hash ) {
  35168. return this.hashNodes[ hash ];
  35169. }
  35170. /**
  35171. * Adds the Node to a target flow so that it can generate code in the 'generate' process.
  35172. *
  35173. * @param {('vertex'|'fragment'|'compute')} shaderStage - The shader stage.
  35174. * @param {Node} node - The node to add.
  35175. * @return {Node} The node.
  35176. */
  35177. addFlow( shaderStage, node ) {
  35178. this.flowNodes[ shaderStage ].push( node );
  35179. return node;
  35180. }
  35181. /**
  35182. * Sets builder's context.
  35183. *
  35184. * @param {Object} context - The context to set.
  35185. */
  35186. setContext( context ) {
  35187. this.context = context;
  35188. }
  35189. /**
  35190. * Returns the builder's current context.
  35191. *
  35192. * @return {Object} The builder's current context.
  35193. */
  35194. getContext() {
  35195. return this.context;
  35196. }
  35197. /**
  35198. * Adds context data to the builder's current context.
  35199. *
  35200. * @param {Object} context - The context to add.
  35201. * @return {Object} The previous context.
  35202. */
  35203. addContext( context ) {
  35204. const previousContext = this.getContext();
  35205. this.setContext( { ...this.context, ...context } );
  35206. return previousContext;
  35207. }
  35208. /**
  35209. * Gets a context used in shader construction that can be shared across different materials.
  35210. * This is necessary since the renderer cache can reuse shaders generated in one material and use them in another.
  35211. *
  35212. * @return {Object} The builder's current context without material.
  35213. */
  35214. getSharedContext() {
  35215. ({ ...this.context });
  35216. return this.context;
  35217. }
  35218. /**
  35219. * Sets builder's cache.
  35220. *
  35221. * @param {NodeCache} cache - The cache to set.
  35222. */
  35223. setCache( cache ) {
  35224. this.cache = cache;
  35225. }
  35226. /**
  35227. * Returns the builder's current cache.
  35228. *
  35229. * @return {NodeCache} The builder's current cache.
  35230. */
  35231. getCache() {
  35232. return this.cache;
  35233. }
  35234. /**
  35235. * Returns a cache for the given node.
  35236. *
  35237. * @param {Node} node - The node.
  35238. * @param {boolean} [parent=true] - Whether this node refers to a shared parent cache or not.
  35239. * @return {NodeCache} The cache.
  35240. */
  35241. getCacheFromNode( node, parent = true ) {
  35242. const data = this.getDataFromNode( node );
  35243. if ( data.cache === undefined ) data.cache = new NodeCache( parent ? this.getCache() : null );
  35244. return data.cache;
  35245. }
  35246. /**
  35247. * Whether the requested feature is available or not.
  35248. *
  35249. * @abstract
  35250. * @param {string} name - The requested feature.
  35251. * @return {boolean} Whether the requested feature is supported or not.
  35252. */
  35253. isAvailable( /*name*/ ) {
  35254. return false;
  35255. }
  35256. /**
  35257. * Returns the vertexIndex input variable as a native shader string.
  35258. *
  35259. * @abstract
  35260. * @return {string} The instanceIndex shader string.
  35261. */
  35262. getVertexIndex() {
  35263. warn( 'Abstract function.' );
  35264. }
  35265. /**
  35266. * Contextually returns either the vertex stage instance index builtin
  35267. * or the linearized index of an compute invocation within a grid of workgroups.
  35268. *
  35269. * @abstract
  35270. * @return {string} The instanceIndex shader string.
  35271. */
  35272. getInstanceIndex() {
  35273. warn( 'Abstract function.' );
  35274. }
  35275. /**
  35276. * Returns the drawIndex input variable as a native shader string.
  35277. * Only relevant for WebGL and its `WEBGL_multi_draw` extension.
  35278. *
  35279. * @abstract
  35280. * @return {?string} The drawIndex shader string.
  35281. */
  35282. getDrawIndex() {
  35283. warn( 'Abstract function.' );
  35284. }
  35285. /**
  35286. * Returns the frontFacing input variable as a native shader string.
  35287. *
  35288. * @abstract
  35289. * @return {string} The frontFacing shader string.
  35290. */
  35291. getFrontFacing() {
  35292. warn( 'Abstract function.' );
  35293. }
  35294. /**
  35295. * Returns the fragCoord input variable as a native shader string.
  35296. *
  35297. * @abstract
  35298. * @return {string} The fragCoord shader string.
  35299. */
  35300. getFragCoord() {
  35301. warn( 'Abstract function.' );
  35302. }
  35303. /**
  35304. * Whether to flip texture data along its vertical axis or not. WebGL needs
  35305. * this method evaluate to `true`, WebGPU to `false`.
  35306. *
  35307. * @abstract
  35308. * @return {boolean} Whether to flip texture data along its vertical axis or not.
  35309. */
  35310. isFlipY() {
  35311. return false;
  35312. }
  35313. /**
  35314. * Calling this method increases the usage count for the given node by one.
  35315. *
  35316. * @param {Node} node - The node to increase the usage count for.
  35317. * @return {number} The updated usage count.
  35318. */
  35319. increaseUsage( node ) {
  35320. const nodeData = this.getDataFromNode( node );
  35321. nodeData.usageCount = nodeData.usageCount === undefined ? 1 : nodeData.usageCount + 1;
  35322. return nodeData.usageCount;
  35323. }
  35324. /**
  35325. * Generates a texture sample shader string for the given texture data.
  35326. *
  35327. * @abstract
  35328. * @param {Texture} texture - The texture.
  35329. * @param {string} textureProperty - The texture property name.
  35330. * @param {string} uvSnippet - Snippet defining the texture coordinates.
  35331. * @return {string} The generated shader string.
  35332. */
  35333. generateTexture( /* texture, textureProperty, uvSnippet */ ) {
  35334. warn( 'Abstract function.' );
  35335. }
  35336. /**
  35337. * Generates a texture LOD shader string for the given texture data.
  35338. *
  35339. * @abstract
  35340. * @param {Texture} texture - The texture.
  35341. * @param {string} textureProperty - The texture property name.
  35342. * @param {string} uvSnippet - Snippet defining the texture coordinates.
  35343. * @param {?string} depthSnippet - Snippet defining the 0-based texture array index to sample.
  35344. * @param {string} levelSnippet - Snippet defining the mip level.
  35345. * @return {string} The generated shader string.
  35346. */
  35347. generateTextureLod( /* texture, textureProperty, uvSnippet, depthSnippet, levelSnippet */ ) {
  35348. warn( 'Abstract function.' );
  35349. }
  35350. /**
  35351. * Generates the array declaration string.
  35352. *
  35353. * @param {string} type - The type.
  35354. * @param {?number} [count] - The count.
  35355. * @return {string} The generated value as a shader string.
  35356. */
  35357. generateArrayDeclaration( type, count ) {
  35358. return this.getType( type ) + '[ ' + count + ' ]';
  35359. }
  35360. /**
  35361. * Generates the array shader string for the given type and value.
  35362. *
  35363. * @param {string} type - The type.
  35364. * @param {?number} [count] - The count.
  35365. * @param {?Array<Node>} [values=null] - The default values.
  35366. * @return {string} The generated value as a shader string.
  35367. */
  35368. generateArray( type, count, values = null ) {
  35369. let snippet = this.generateArrayDeclaration( type, count ) + '( ';
  35370. for ( let i = 0; i < count; i ++ ) {
  35371. const value = values ? values[ i ] : null;
  35372. if ( value !== null ) {
  35373. snippet += value.build( this, type );
  35374. } else {
  35375. snippet += this.generateConst( type );
  35376. }
  35377. if ( i < count - 1 ) snippet += ', ';
  35378. }
  35379. snippet += ' )';
  35380. return snippet;
  35381. }
  35382. /**
  35383. * Generates the struct shader string.
  35384. *
  35385. * @param {string} type - The type.
  35386. * @param {Array<Object>} [membersLayout] - The count.
  35387. * @param {?Array<Node>} [values=null] - The default values.
  35388. * @return {string} The generated value as a shader string.
  35389. */
  35390. generateStruct( type, membersLayout, values = null ) {
  35391. const snippets = [];
  35392. for ( const member of membersLayout ) {
  35393. const { name, type } = member;
  35394. if ( values && values[ name ] && values[ name ].isNode ) {
  35395. snippets.push( values[ name ].build( this, type ) );
  35396. } else {
  35397. snippets.push( this.generateConst( type ) );
  35398. }
  35399. }
  35400. return type + '( ' + snippets.join( ', ' ) + ' )';
  35401. }
  35402. /**
  35403. * Generates the shader string for the given type and value.
  35404. *
  35405. * @param {string} type - The type.
  35406. * @param {?any} [value=null] - The value.
  35407. * @return {string} The generated value as a shader string.
  35408. */
  35409. generateConst( type, value = null ) {
  35410. if ( value === null ) {
  35411. if ( type === 'float' || type === 'int' || type === 'uint' ) value = 0;
  35412. else if ( type === 'bool' ) value = false;
  35413. else if ( type === 'color' ) value = new Color();
  35414. else if ( type === 'vec2' || type === 'uvec2' || type === 'ivec2' ) value = new Vector2();
  35415. else if ( type === 'vec3' || type === 'uvec3' || type === 'ivec3' ) value = new Vector3();
  35416. else if ( type === 'vec4' || type === 'uvec4' || type === 'ivec4' ) value = new Vector4();
  35417. }
  35418. if ( type === 'float' ) return toFloat( value );
  35419. if ( type === 'int' ) return `${ Math.round( value ) }`;
  35420. if ( type === 'uint' ) return value >= 0 ? `${ Math.round( value ) }u` : '0u';
  35421. if ( type === 'bool' ) return value ? 'true' : 'false';
  35422. if ( type === 'color' ) return `${ this.getType( 'vec3' ) }( ${ toFloat( value.r ) }, ${ toFloat( value.g ) }, ${ toFloat( value.b ) } )`;
  35423. const typeLength = this.getTypeLength( type );
  35424. const componentType = this.getComponentType( type );
  35425. const generateConst = value => this.generateConst( componentType, value );
  35426. if ( typeLength === 2 ) {
  35427. return `${ this.getType( type ) }( ${ generateConst( value.x ) }, ${ generateConst( value.y ) } )`;
  35428. } else if ( typeLength === 3 ) {
  35429. return `${ this.getType( type ) }( ${ generateConst( value.x ) }, ${ generateConst( value.y ) }, ${ generateConst( value.z ) } )`;
  35430. } else if ( typeLength === 4 && type !== 'mat2' ) {
  35431. return `${ this.getType( type ) }( ${ generateConst( value.x ) }, ${ generateConst( value.y ) }, ${ generateConst( value.z ) }, ${ generateConst( value.w ) } )`;
  35432. } else if ( typeLength >= 4 && value && ( value.isMatrix2 || value.isMatrix3 || value.isMatrix4 ) ) {
  35433. return `${ this.getType( type ) }( ${ value.elements.map( generateConst ).join( ', ' ) } )`;
  35434. } else if ( typeLength > 4 ) {
  35435. return `${ this.getType( type ) }()`;
  35436. }
  35437. throw new Error( `NodeBuilder: Type '${type}' not found in generate constant attempt.` );
  35438. }
  35439. /**
  35440. * It might be necessary to convert certain data types to different ones
  35441. * so this method can be used to hide the conversion.
  35442. *
  35443. * @param {string} type - The type.
  35444. * @return {string} The updated type.
  35445. */
  35446. getType( type ) {
  35447. if ( type === 'color' ) return 'vec3';
  35448. return type;
  35449. }
  35450. /**
  35451. * Whether the given attribute name is defined in the geometry or not.
  35452. *
  35453. * @param {string} name - The attribute name.
  35454. * @return {boolean} Whether the given attribute name is defined in the geometry.
  35455. */
  35456. hasGeometryAttribute( name ) {
  35457. return this.geometry && this.geometry.getAttribute( name ) !== undefined;
  35458. }
  35459. /**
  35460. * Returns a node attribute for the given name and type.
  35461. *
  35462. * @param {string} name - The attribute's name.
  35463. * @param {string} type - The attribute's type.
  35464. * @return {NodeAttribute} The node attribute.
  35465. */
  35466. getAttribute( name, type ) {
  35467. const attributes = this.attributes;
  35468. // find attribute
  35469. for ( const attribute of attributes ) {
  35470. if ( attribute.name === name ) {
  35471. return attribute;
  35472. }
  35473. }
  35474. // create a new if no exist
  35475. const attribute = new NodeAttribute( name, type );
  35476. this.registerDeclaration( attribute );
  35477. attributes.push( attribute );
  35478. return attribute;
  35479. }
  35480. /**
  35481. * Returns for the given node and shader stage the property name for the shader.
  35482. *
  35483. * @param {Node} node - The node.
  35484. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  35485. * @return {string} The property name.
  35486. */
  35487. getPropertyName( node/*, shaderStage*/ ) {
  35488. return node.name;
  35489. }
  35490. /**
  35491. * Whether the given type is a vector type or not.
  35492. *
  35493. * @param {string} type - The type to check.
  35494. * @return {boolean} Whether the given type is a vector type or not.
  35495. */
  35496. isVector( type ) {
  35497. return /vec\d/.test( type );
  35498. }
  35499. /**
  35500. * Whether the given type is a matrix type or not.
  35501. *
  35502. * @param {string} type - The type to check.
  35503. * @return {boolean} Whether the given type is a matrix type or not.
  35504. */
  35505. isMatrix( type ) {
  35506. return /mat\d/.test( type );
  35507. }
  35508. /**
  35509. * Whether the given type is a reference type or not.
  35510. *
  35511. * @param {string} type - The type to check.
  35512. * @return {boolean} Whether the given type is a reference type or not.
  35513. */
  35514. isReference( type ) {
  35515. return type === 'void' || type === 'property' || type === 'sampler' || type === 'samplerComparison' || type === 'texture' || type === 'cubeTexture' || type === 'storageTexture' || type === 'depthTexture' || type === 'texture3D';
  35516. }
  35517. /**
  35518. * Checks if the given texture requires a manual conversion to the working color space.
  35519. *
  35520. * @abstract
  35521. * @param {Texture} texture - The texture to check.
  35522. * @return {boolean} Whether the given texture requires a conversion to working color space or not.
  35523. */
  35524. needsToWorkingColorSpace( /*texture*/ ) {
  35525. return false;
  35526. }
  35527. /**
  35528. * Returns the component type of a given texture.
  35529. *
  35530. * @param {Texture} texture - The texture.
  35531. * @return {string} The component type.
  35532. */
  35533. getComponentTypeFromTexture( texture ) {
  35534. const type = texture.type;
  35535. if ( texture.isDataTexture ) {
  35536. if ( type === IntType ) return 'int';
  35537. if ( type === UnsignedIntType ) return 'uint';
  35538. }
  35539. return 'float';
  35540. }
  35541. /**
  35542. * Returns the element type for a given type.
  35543. *
  35544. * @param {string} type - The type.
  35545. * @return {string} The element type.
  35546. */
  35547. getElementType( type ) {
  35548. if ( type === 'mat2' ) return 'vec2';
  35549. if ( type === 'mat3' ) return 'vec3';
  35550. if ( type === 'mat4' ) return 'vec4';
  35551. return this.getComponentType( type );
  35552. }
  35553. /**
  35554. * Returns the component type for a given type.
  35555. *
  35556. * @param {string} type - The type.
  35557. * @return {string} The component type.
  35558. */
  35559. getComponentType( type ) {
  35560. type = this.getVectorType( type );
  35561. if ( type === 'float' || type === 'bool' || type === 'int' || type === 'uint' ) return type;
  35562. const componentType = /(b|i|u|)(vec|mat)([2-4])/.exec( type );
  35563. if ( componentType === null ) return null;
  35564. if ( componentType[ 1 ] === 'b' ) return 'bool';
  35565. if ( componentType[ 1 ] === 'i' ) return 'int';
  35566. if ( componentType[ 1 ] === 'u' ) return 'uint';
  35567. return 'float';
  35568. }
  35569. /**
  35570. * Returns the vector type for a given type.
  35571. *
  35572. * @param {string} type - The type.
  35573. * @return {string} The vector type.
  35574. */
  35575. getVectorType( type ) {
  35576. if ( type === 'color' ) return 'vec3';
  35577. if ( type === 'texture' || type === 'cubeTexture' || type === 'storageTexture' || type === 'texture3D' ) return 'vec4';
  35578. return type;
  35579. }
  35580. /**
  35581. * Returns the data type for the given the length and component type.
  35582. *
  35583. * @param {number} length - The length.
  35584. * @param {string} [componentType='float'] - The component type.
  35585. * @return {string} The type.
  35586. */
  35587. getTypeFromLength( length, componentType = 'float' ) {
  35588. if ( length === 1 ) return componentType;
  35589. let baseType = getTypeFromLength( length );
  35590. const prefix = componentType === 'float' ? '' : componentType[ 0 ];
  35591. // fix edge case for mat2x2 being same size as vec4
  35592. if ( /mat2/.test( componentType ) === true ) {
  35593. baseType = baseType.replace( 'vec', 'mat' );
  35594. }
  35595. return prefix + baseType;
  35596. }
  35597. /**
  35598. * Returns the type for a given typed array.
  35599. *
  35600. * @param {TypedArray} array - The typed array.
  35601. * @return {string} The type.
  35602. */
  35603. getTypeFromArray( array ) {
  35604. return typeFromArray.get( array.constructor );
  35605. }
  35606. /**
  35607. * Returns the type is an integer type.
  35608. *
  35609. * @param {string} type - The type.
  35610. * @return {boolean} Whether the type is an integer type or not.
  35611. */
  35612. isInteger( type ) {
  35613. return /int|uint|(i|u)vec/.test( type );
  35614. }
  35615. /**
  35616. * Returns the type for a given buffer attribute.
  35617. *
  35618. * @param {BufferAttribute} attribute - The buffer attribute.
  35619. * @return {string} The type.
  35620. */
  35621. getTypeFromAttribute( attribute ) {
  35622. let dataAttribute = attribute;
  35623. if ( attribute.isInterleavedBufferAttribute ) dataAttribute = attribute.data;
  35624. const array = dataAttribute.array;
  35625. const itemSize = attribute.itemSize;
  35626. const normalized = attribute.normalized;
  35627. let arrayType;
  35628. if ( ! ( attribute instanceof Float16BufferAttribute ) && normalized !== true ) {
  35629. arrayType = this.getTypeFromArray( array );
  35630. }
  35631. return this.getTypeFromLength( itemSize, arrayType );
  35632. }
  35633. /**
  35634. * Returns the length for the given data type.
  35635. *
  35636. * @param {string} type - The data type.
  35637. * @return {number} The length.
  35638. */
  35639. getTypeLength( type ) {
  35640. const vecType = this.getVectorType( type );
  35641. const vecNum = /vec([2-4])/.exec( vecType );
  35642. if ( vecNum !== null ) return Number( vecNum[ 1 ] );
  35643. if ( vecType === 'float' || vecType === 'bool' || vecType === 'int' || vecType === 'uint' ) return 1;
  35644. if ( /mat2/.test( type ) === true ) return 4;
  35645. if ( /mat3/.test( type ) === true ) return 9;
  35646. if ( /mat4/.test( type ) === true ) return 16;
  35647. return 0;
  35648. }
  35649. /**
  35650. * Returns the vector type for a given matrix type.
  35651. *
  35652. * @param {string} type - The matrix type.
  35653. * @return {string} The vector type.
  35654. */
  35655. getVectorFromMatrix( type ) {
  35656. return type.replace( 'mat', 'vec' );
  35657. }
  35658. /**
  35659. * For a given type this method changes the component type to the
  35660. * given value. E.g. `vec4` should be changed to the new component type
  35661. * `uint` which results in `uvec4`.
  35662. *
  35663. * @param {string} type - The type.
  35664. * @param {string} newComponentType - The new component type.
  35665. * @return {string} The new type.
  35666. */
  35667. changeComponentType( type, newComponentType ) {
  35668. return this.getTypeFromLength( this.getTypeLength( type ), newComponentType );
  35669. }
  35670. /**
  35671. * Returns the integer type pendant for the given type.
  35672. *
  35673. * @param {string} type - The type.
  35674. * @return {string} The integer type.
  35675. */
  35676. getIntegerType( type ) {
  35677. const componentType = this.getComponentType( type );
  35678. if ( componentType === 'int' || componentType === 'uint' ) return type;
  35679. return this.changeComponentType( type, 'int' );
  35680. }
  35681. /**
  35682. * Adds an active stack to the internal stack.
  35683. *
  35684. * @param {StackNode} stack - The stack node to add.
  35685. */
  35686. setActiveStack( stack ) {
  35687. this.activeStacks.push( stack );
  35688. }
  35689. /**
  35690. * Removes the active stack from the internal stack.
  35691. *
  35692. * @param {StackNode} stack - The stack node to remove.
  35693. */
  35694. removeActiveStack( stack ) {
  35695. if ( this.activeStacks[ this.activeStacks.length - 1 ] === stack ) {
  35696. this.activeStacks.pop();
  35697. } else {
  35698. throw new Error( 'NodeBuilder: Invalid active stack removal.' );
  35699. }
  35700. }
  35701. /**
  35702. * Returns the active stack.
  35703. *
  35704. * @return {StackNode} The active stack.
  35705. */
  35706. getActiveStack() {
  35707. return this.activeStacks[ this.activeStacks.length - 1 ];
  35708. }
  35709. /**
  35710. * Returns the base stack.
  35711. *
  35712. * @return {StackNode} The base stack.
  35713. */
  35714. getBaseStack() {
  35715. return this.activeStacks[ 0 ];
  35716. }
  35717. /**
  35718. * Adds a stack node to the internal stack.
  35719. *
  35720. * @return {StackNode} The added stack node.
  35721. */
  35722. addStack() {
  35723. this.stack = stack( this.stack );
  35724. const previousStack = getCurrentStack();
  35725. this.stacks.push( previousStack );
  35726. setCurrentStack( this.stack );
  35727. return this.stack;
  35728. }
  35729. /**
  35730. * Removes the last stack node from the internal stack.
  35731. *
  35732. * @return {StackNode} The removed stack node.
  35733. */
  35734. removeStack() {
  35735. const lastStack = this.stack;
  35736. for ( const node of lastStack.nodes ) {
  35737. const nodeData = this.getDataFromNode( node );
  35738. nodeData.stack = lastStack;
  35739. }
  35740. this.stack = lastStack.parent;
  35741. setCurrentStack( this.stacks.pop() );
  35742. return lastStack;
  35743. }
  35744. /**
  35745. * The builder maintains (cached) data for each node during the building process. This method
  35746. * can be used to get these data for a specific shader stage and cache.
  35747. *
  35748. * @param {Node} node - The node to get the data for.
  35749. * @param {('vertex'|'fragment'|'compute'|'any')} [shaderStage=this.shaderStage] - The shader stage.
  35750. * @param {?NodeCache} cache - An optional cache.
  35751. * @return {Object} The node data.
  35752. */
  35753. getDataFromNode( node, shaderStage = this.shaderStage, cache = null ) {
  35754. cache = cache === null ? ( node.isGlobal( this ) ? this.globalCache : this.cache ) : cache;
  35755. let nodeData = cache.getData( node );
  35756. if ( nodeData === undefined ) {
  35757. nodeData = {};
  35758. cache.setData( node, nodeData );
  35759. }
  35760. if ( nodeData[ shaderStage ] === undefined ) nodeData[ shaderStage ] = {};
  35761. //
  35762. let data = nodeData[ shaderStage ];
  35763. const subBuilds = nodeData.any ? nodeData.any.subBuilds : null;
  35764. const subBuild = this.getClosestSubBuild( subBuilds );
  35765. if ( subBuild ) {
  35766. if ( data.subBuildsCache === undefined ) data.subBuildsCache = {};
  35767. data = data.subBuildsCache[ subBuild ] || ( data.subBuildsCache[ subBuild ] = {} );
  35768. data.subBuilds = subBuilds;
  35769. }
  35770. return data;
  35771. }
  35772. /**
  35773. * Returns the properties for the given node and shader stage.
  35774. *
  35775. * Properties are typically used within a build stage to reference a node's
  35776. * child node or nodes manually assigned to the properties in a separate build stage.
  35777. * A typical usage pattern for defining nodes manually would be assigning dependency nodes
  35778. * to the current node's properties in the setup stage and building those properties in the generate stage.
  35779. *
  35780. * @param {Node} node - The node to get the properties for.
  35781. * @param {('vertex'|'fragment'|'compute'|'any')} [shaderStage='any'] - The shader stage.
  35782. * @return {Object} The node properties.
  35783. */
  35784. getNodeProperties( node, shaderStage = 'any' ) {
  35785. const nodeData = this.getDataFromNode( node, shaderStage );
  35786. return nodeData.properties || ( nodeData.properties = { outputNode: null } );
  35787. }
  35788. /**
  35789. * Returns an instance of {@link NodeAttribute} for the given buffer attribute node.
  35790. *
  35791. * @param {BufferAttributeNode} node - The buffer attribute node.
  35792. * @param {string} type - The node type.
  35793. * @return {NodeAttribute} The node attribute.
  35794. */
  35795. getBufferAttributeFromNode( node, type ) {
  35796. const nodeData = this.getDataFromNode( node, 'vertex' );
  35797. let bufferAttribute = nodeData.bufferAttribute;
  35798. if ( bufferAttribute === undefined ) {
  35799. const index = this.uniforms.index ++;
  35800. bufferAttribute = new NodeAttribute( 'nodeAttribute' + index, type, node );
  35801. this.bufferAttributes.push( bufferAttribute );
  35802. nodeData.bufferAttribute = bufferAttribute;
  35803. }
  35804. return bufferAttribute;
  35805. }
  35806. /**
  35807. * Returns an instance of {@link StructType} for the given struct name and shader stage
  35808. * or null if not found.
  35809. *
  35810. * @param {string} name - The name of the struct.
  35811. * @param {('vertex'|'fragment'|'compute'|'any')} [shaderStage=this.shaderStage] - The shader stage.
  35812. * @return {?StructType} The struct type or null if not found.
  35813. */
  35814. getStructTypeNode( name, shaderStage = this.shaderStage ) {
  35815. return this.types[ shaderStage ][ name ] || null;
  35816. }
  35817. /**
  35818. * Returns an instance of {@link StructType} for the given output struct node.
  35819. *
  35820. * @param {OutputStructNode} node - The output struct node.
  35821. * @param {Array<Object>} membersLayout - The output struct types.
  35822. * @param {?string} [name=null] - The name of the struct.
  35823. * @param {('vertex'|'fragment'|'compute'|'any')} [shaderStage=this.shaderStage] - The shader stage.
  35824. * @return {StructType} The struct type attribute.
  35825. */
  35826. getStructTypeFromNode( node, membersLayout, name = null, shaderStage = this.shaderStage ) {
  35827. const nodeData = this.getDataFromNode( node, shaderStage, this.globalCache );
  35828. let structType = nodeData.structType;
  35829. if ( structType === undefined ) {
  35830. const index = this.structs.index ++;
  35831. if ( name === null ) name = 'StructType' + index;
  35832. structType = new StructType( name, membersLayout );
  35833. this.structs[ shaderStage ].push( structType );
  35834. this.types[ shaderStage ][ name ] = node;
  35835. nodeData.structType = structType;
  35836. }
  35837. return structType;
  35838. }
  35839. /**
  35840. * Returns an instance of {@link StructType} for the given output struct node.
  35841. *
  35842. * @param {OutputStructNode} node - The output struct node.
  35843. * @param {Array<Object>} membersLayout - The output struct types.
  35844. * @return {StructType} The struct type attribute.
  35845. */
  35846. getOutputStructTypeFromNode( node, membersLayout ) {
  35847. const structType = this.getStructTypeFromNode( node, membersLayout, 'OutputType', 'fragment' );
  35848. structType.output = true;
  35849. return structType;
  35850. }
  35851. /**
  35852. * Returns an instance of {@link NodeUniform} for the given uniform node.
  35853. *
  35854. * @param {UniformNode} node - The uniform node.
  35855. * @param {string} type - The uniform type.
  35856. * @param {('vertex'|'fragment'|'compute'|'any')} [shaderStage=this.shaderStage] - The shader stage.
  35857. * @param {?string} name - The name of the uniform.
  35858. * @return {NodeUniform} The node uniform.
  35859. */
  35860. getUniformFromNode( node, type, shaderStage = this.shaderStage, name = null ) {
  35861. const nodeData = this.getDataFromNode( node, shaderStage, this.globalCache );
  35862. let nodeUniform = nodeData.uniform;
  35863. if ( nodeUniform === undefined ) {
  35864. const index = this.uniforms.index ++;
  35865. nodeUniform = new NodeUniform( name || ( 'nodeUniform' + index ), type, node );
  35866. this.uniforms[ shaderStage ].push( nodeUniform );
  35867. this.registerDeclaration( nodeUniform );
  35868. nodeData.uniform = nodeUniform;
  35869. }
  35870. return nodeUniform;
  35871. }
  35872. /**
  35873. * Returns an instance of {@link NodeVar} for the given variable node.
  35874. *
  35875. * @param {VarNode} node - The variable node.
  35876. * @param {?string} name - The variable's name.
  35877. * @param {string} [type=node.getNodeType( this )] - The variable's type.
  35878. * @param {('vertex'|'fragment'|'compute'|'any')} [shaderStage=this.shaderStage] - The shader stage.
  35879. * @param {boolean} [readOnly=false] - Whether the variable is read-only or not.
  35880. *
  35881. * @return {NodeVar} The node variable.
  35882. */
  35883. getVarFromNode( node, name = null, type = node.getNodeType( this ), shaderStage = this.shaderStage, readOnly = false ) {
  35884. const nodeData = this.getDataFromNode( node, shaderStage );
  35885. const subBuildVariable = this.getSubBuildProperty( 'variable', nodeData.subBuilds );
  35886. let nodeVar = nodeData[ subBuildVariable ];
  35887. if ( nodeVar === undefined ) {
  35888. const idNS = readOnly ? '_const' : '_var';
  35889. const vars = this.vars[ shaderStage ] || ( this.vars[ shaderStage ] = [] );
  35890. const id = this.vars[ idNS ] || ( this.vars[ idNS ] = 0 );
  35891. if ( name === null ) {
  35892. name = ( readOnly ? 'nodeConst' : 'nodeVar' ) + id;
  35893. this.vars[ idNS ] ++;
  35894. }
  35895. //
  35896. if ( subBuildVariable !== 'variable' ) {
  35897. name = this.getSubBuildProperty( name, nodeData.subBuilds );
  35898. }
  35899. //
  35900. const count = node.getArrayCount( this );
  35901. nodeVar = new NodeVar( name, type, readOnly, count );
  35902. if ( ! readOnly ) {
  35903. vars.push( nodeVar );
  35904. }
  35905. this.registerDeclaration( nodeVar );
  35906. nodeData[ subBuildVariable ] = nodeVar;
  35907. }
  35908. return nodeVar;
  35909. }
  35910. /**
  35911. * Returns whether a Node or its flow is deterministic, useful for use in `const`.
  35912. *
  35913. * @param {Node} node - The varying node.
  35914. * @return {boolean} Returns true if deterministic.
  35915. */
  35916. isDeterministic( node ) {
  35917. if ( node.isMathNode ) {
  35918. return this.isDeterministic( node.aNode ) &&
  35919. ( node.bNode ? this.isDeterministic( node.bNode ) : true ) &&
  35920. ( node.cNode ? this.isDeterministic( node.cNode ) : true );
  35921. } else if ( node.isOperatorNode ) {
  35922. return this.isDeterministic( node.aNode ) &&
  35923. ( node.bNode ? this.isDeterministic( node.bNode ) : true );
  35924. } else if ( node.isArrayNode ) {
  35925. if ( node.values !== null ) {
  35926. for ( const n of node.values ) {
  35927. if ( ! this.isDeterministic( n ) ) {
  35928. return false;
  35929. }
  35930. }
  35931. }
  35932. return true;
  35933. } else if ( node.isConstNode ) {
  35934. return true;
  35935. }
  35936. return false;
  35937. }
  35938. /**
  35939. * Returns an instance of {@link NodeVarying} for the given varying node.
  35940. *
  35941. * @param {(VaryingNode|PropertyNode)} node - The varying node.
  35942. * @param {?string} name - The varying's name.
  35943. * @param {string} [type=node.getNodeType( this )] - The varying's type.
  35944. * @param {?string} interpolationType - The interpolation type of the varying.
  35945. * @param {?string} interpolationSampling - The interpolation sampling type of the varying.
  35946. * @return {NodeVar} The node varying.
  35947. */
  35948. getVaryingFromNode( node, name = null, type = node.getNodeType( this ), interpolationType = null, interpolationSampling = null ) {
  35949. const nodeData = this.getDataFromNode( node, 'any' );
  35950. const subBuildVarying = this.getSubBuildProperty( 'varying', nodeData.subBuilds );
  35951. let nodeVarying = nodeData[ subBuildVarying ];
  35952. if ( nodeVarying === undefined ) {
  35953. const varyings = this.varyings;
  35954. const index = varyings.length;
  35955. if ( name === null ) name = 'nodeVarying' + index;
  35956. //
  35957. if ( subBuildVarying !== 'varying' ) {
  35958. name = this.getSubBuildProperty( name, nodeData.subBuilds );
  35959. }
  35960. //
  35961. nodeVarying = new NodeVarying( name, type, interpolationType, interpolationSampling );
  35962. varyings.push( nodeVarying );
  35963. this.registerDeclaration( nodeVarying );
  35964. nodeData[ subBuildVarying ] = nodeVarying;
  35965. }
  35966. return nodeVarying;
  35967. }
  35968. /**
  35969. * Registers a node declaration in the current shader stage.
  35970. *
  35971. * @param {Object} node - The node to be registered.
  35972. */
  35973. registerDeclaration( node ) {
  35974. const shaderStage = this.shaderStage;
  35975. const declarations = this.declarations[ shaderStage ] || ( this.declarations[ shaderStage ] = {} );
  35976. const property = this.getPropertyName( node );
  35977. let index = 1;
  35978. let name = property;
  35979. // Automatically renames the property if the name is already in use.
  35980. while ( declarations[ name ] !== undefined ) {
  35981. name = property + '_' + index ++;
  35982. }
  35983. if ( index > 1 ) {
  35984. node.name = name;
  35985. warn( `TSL: Declaration name '${ property }' of '${ node.type }' already in use. Renamed to '${ name }'.` );
  35986. }
  35987. declarations[ name ] = node;
  35988. }
  35989. /**
  35990. * Returns an instance of {@link NodeCode} for the given code node.
  35991. *
  35992. * @param {CodeNode} node - The code node.
  35993. * @param {string} type - The node type.
  35994. * @param {('vertex'|'fragment'|'compute'|'any')} [shaderStage=this.shaderStage] - The shader stage.
  35995. * @return {NodeCode} The node code.
  35996. */
  35997. getCodeFromNode( node, type, shaderStage = this.shaderStage ) {
  35998. const nodeData = this.getDataFromNode( node );
  35999. let nodeCode = nodeData.code;
  36000. if ( nodeCode === undefined ) {
  36001. const codes = this.codes[ shaderStage ] || ( this.codes[ shaderStage ] = [] );
  36002. const index = codes.length;
  36003. nodeCode = new NodeCode( 'nodeCode' + index, type );
  36004. codes.push( nodeCode );
  36005. nodeData.code = nodeCode;
  36006. }
  36007. return nodeCode;
  36008. }
  36009. /**
  36010. * Adds a code flow based on the code-block hierarchy.
  36011. * This is used so that code-blocks like If,Else create their variables locally if the Node
  36012. * is only used inside one of these conditionals in the current shader stage.
  36013. *
  36014. * @param {Node} node - The node to add.
  36015. * @param {Node} nodeBlock - Node-based code-block. Usually 'ConditionalNode'.
  36016. */
  36017. addFlowCodeHierarchy( node, nodeBlock ) {
  36018. const { flowCodes, flowCodeBlock } = this.getDataFromNode( node );
  36019. let needsFlowCode = true;
  36020. let nodeBlockHierarchy = nodeBlock;
  36021. while ( nodeBlockHierarchy ) {
  36022. if ( flowCodeBlock.get( nodeBlockHierarchy ) === true ) {
  36023. needsFlowCode = false;
  36024. break;
  36025. }
  36026. nodeBlockHierarchy = this.getDataFromNode( nodeBlockHierarchy ).parentNodeBlock;
  36027. }
  36028. if ( needsFlowCode ) {
  36029. for ( const flowCode of flowCodes ) {
  36030. this.addLineFlowCode( flowCode );
  36031. }
  36032. }
  36033. }
  36034. /**
  36035. * Add a inline-code to the current flow code-block.
  36036. *
  36037. * @param {Node} node - The node to add.
  36038. * @param {string} code - The code to add.
  36039. * @param {Node} nodeBlock - Current ConditionalNode
  36040. */
  36041. addLineFlowCodeBlock( node, code, nodeBlock ) {
  36042. const nodeData = this.getDataFromNode( node );
  36043. const flowCodes = nodeData.flowCodes || ( nodeData.flowCodes = [] );
  36044. const codeBlock = nodeData.flowCodeBlock || ( nodeData.flowCodeBlock = new WeakMap() );
  36045. flowCodes.push( code );
  36046. codeBlock.set( nodeBlock, true );
  36047. }
  36048. /**
  36049. * Add a inline-code to the current flow.
  36050. *
  36051. * @param {string} code - The code to add.
  36052. * @param {?Node} [node= null] - Optional Node, can help the system understand if the Node is part of a code-block.
  36053. * @return {NodeBuilder} A reference to this node builder.
  36054. */
  36055. addLineFlowCode( code, node = null ) {
  36056. if ( code === '' ) return this;
  36057. if ( node !== null && this.context.nodeBlock ) {
  36058. this.addLineFlowCodeBlock( node, code, this.context.nodeBlock );
  36059. }
  36060. code = this.tab + code;
  36061. if ( ! /;\s*$/.test( code ) ) {
  36062. code = code + ';\n';
  36063. }
  36064. this.flow.code += code;
  36065. return this;
  36066. }
  36067. /**
  36068. * Adds a code to the current code flow.
  36069. *
  36070. * @param {string} code - Shader code.
  36071. * @return {NodeBuilder} A reference to this node builder.
  36072. */
  36073. addFlowCode( code ) {
  36074. this.flow.code += code;
  36075. return this;
  36076. }
  36077. /**
  36078. * Add tab in the code that will be generated so that other snippets respect the current tabulation.
  36079. * Typically used in codes with If,Else.
  36080. *
  36081. * @return {NodeBuilder} A reference to this node builder.
  36082. */
  36083. addFlowTab() {
  36084. this.tab += '\t';
  36085. return this;
  36086. }
  36087. /**
  36088. * Removes a tab.
  36089. *
  36090. * @return {NodeBuilder} A reference to this node builder.
  36091. */
  36092. removeFlowTab() {
  36093. this.tab = this.tab.slice( 0, -1 );
  36094. return this;
  36095. }
  36096. /**
  36097. * Gets the current flow data based on a Node.
  36098. *
  36099. * @param {Node} node - Node that the flow was started.
  36100. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  36101. * @return {Object} The flow data.
  36102. */
  36103. getFlowData( node/*, shaderStage*/ ) {
  36104. return this.flowsData.get( node );
  36105. }
  36106. /**
  36107. * Executes the node flow based on a root node to generate the final shader code.
  36108. *
  36109. * @param {Node} node - The node to execute.
  36110. * @return {Object} The code flow.
  36111. */
  36112. flowNode( node ) {
  36113. const output = node.getNodeType( this );
  36114. const flowData = this.flowChildNode( node, output );
  36115. this.flowsData.set( node, flowData );
  36116. return flowData;
  36117. }
  36118. /**
  36119. * Includes a node in the current function node.
  36120. *
  36121. * @param {Node} node - The node to include.
  36122. * @returns {void}
  36123. */
  36124. addInclude( node ) {
  36125. if ( this.currentFunctionNode !== null ) {
  36126. this.currentFunctionNode.includes.push( node );
  36127. }
  36128. }
  36129. /**
  36130. * Returns the native shader operator name for a given generic name.
  36131. * It is a similar type of method like {@link NodeBuilder#getMethod}.
  36132. *
  36133. * @param {ShaderNodeInternal} shaderNode - The shader node to build the function node with.
  36134. * @return {FunctionNode} The build function node.
  36135. */
  36136. buildFunctionNode( shaderNode ) {
  36137. const fn = new FunctionNode();
  36138. const previous = this.currentFunctionNode;
  36139. this.currentFunctionNode = fn;
  36140. fn.code = this.buildFunctionCode( shaderNode );
  36141. this.currentFunctionNode = previous;
  36142. return fn;
  36143. }
  36144. /**
  36145. * Generates a code flow based on a TSL function: Fn().
  36146. *
  36147. * @param {ShaderNodeInternal} shaderNode - A function code will be generated based on the input.
  36148. * @return {Object}
  36149. */
  36150. flowShaderNode( shaderNode ) {
  36151. const layout = shaderNode.layout;
  36152. const inputs = {
  36153. [ Symbol.iterator ]() {
  36154. let index = 0;
  36155. const values = Object.values( this );
  36156. return {
  36157. next: () => ( {
  36158. value: values[ index ],
  36159. done: index ++ >= values.length
  36160. } )
  36161. };
  36162. }
  36163. };
  36164. for ( const input of layout.inputs ) {
  36165. inputs[ input.name ] = new ParameterNode( input.type, input.name );
  36166. }
  36167. //
  36168. shaderNode.layout = null;
  36169. const callNode = shaderNode.call( inputs );
  36170. const flowData = this.flowStagesNode( callNode, layout.type );
  36171. shaderNode.layout = layout;
  36172. return flowData;
  36173. }
  36174. /**
  36175. * Executes the node in a specific build stage.
  36176. *
  36177. * This function can be used to arbitrarily execute the specified build stage
  36178. * outside of the standard build process. For instance, if a node's type depends
  36179. * on properties created by the 'setup' stage, then flowBuildStage(node, 'setup')
  36180. * can be used to execute the setup build stage and access its generated nodes
  36181. * before the standard build process begins.
  36182. *
  36183. * @param {Node} node - The node to execute.
  36184. * @param {string} buildStage - The build stage to execute the node in.
  36185. * @param {?(Node|string)} [output=null] - Expected output type. For example 'vec3'.
  36186. * @return {?(Node|string)} The result of the node build.
  36187. */
  36188. flowBuildStage( node, buildStage, output = null ) {
  36189. const previousBuildStage = this.getBuildStage();
  36190. this.setBuildStage( buildStage );
  36191. const result = node.build( this, output );
  36192. this.setBuildStage( previousBuildStage );
  36193. return result;
  36194. }
  36195. /**
  36196. * Runs the node flow through all the steps of creation, 'setup', 'analyze', 'generate'.
  36197. *
  36198. * @param {Node} node - The node to execute.
  36199. * @param {?string} output - Expected output type. For example 'vec3'.
  36200. * @return {Object}
  36201. */
  36202. flowStagesNode( node, output = null ) {
  36203. const previousFlow = this.flow;
  36204. const previousVars = this.vars;
  36205. const previousDeclarations = this.declarations;
  36206. const previousCache = this.cache;
  36207. const previousBuildStage = this.buildStage;
  36208. const previousStack = this.stack;
  36209. const flow = {
  36210. code: ''
  36211. };
  36212. this.flow = flow;
  36213. this.vars = {};
  36214. this.declarations = {};
  36215. this.cache = new NodeCache();
  36216. this.stack = stack();
  36217. for ( const buildStage of defaultBuildStages ) {
  36218. this.setBuildStage( buildStage );
  36219. flow.result = node.build( this, output );
  36220. }
  36221. flow.vars = this.getVars( this.shaderStage );
  36222. this.flow = previousFlow;
  36223. this.vars = previousVars;
  36224. this.declarations = previousDeclarations;
  36225. this.cache = previousCache;
  36226. this.stack = previousStack;
  36227. this.setBuildStage( previousBuildStage );
  36228. return flow;
  36229. }
  36230. /**
  36231. * Returns the native shader operator name for a given generic name.
  36232. * It is a similar type of method like {@link NodeBuilder#getMethod}.
  36233. *
  36234. * @abstract
  36235. * @param {string} op - The operator name to resolve.
  36236. * @return {?string} The resolved operator name.
  36237. */
  36238. getFunctionOperator( /* op */ ) {
  36239. return null;
  36240. }
  36241. /**
  36242. * Builds the given shader node.
  36243. *
  36244. * @abstract
  36245. * @param {ShaderNodeInternal} shaderNode - The shader node.
  36246. * @return {string} The function code.
  36247. */
  36248. buildFunctionCode( /* shaderNode */ ) {
  36249. warn( 'Abstract function.' );
  36250. }
  36251. /**
  36252. * Generates a code flow based on a child Node.
  36253. *
  36254. * @param {Node} node - The node to execute.
  36255. * @param {?string} output - Expected output type. For example 'vec3'.
  36256. * @return {Object} The code flow.
  36257. */
  36258. flowChildNode( node, output = null ) {
  36259. const previousFlow = this.flow;
  36260. const flow = {
  36261. code: ''
  36262. };
  36263. this.flow = flow;
  36264. flow.result = node.build( this, output );
  36265. this.flow = previousFlow;
  36266. return flow;
  36267. }
  36268. /**
  36269. * Executes a flow of code in a different stage.
  36270. *
  36271. * Some nodes like `varying()` have the ability to compute code in vertex-stage and
  36272. * return the value in fragment-stage even if it is being executed in an input fragment.
  36273. *
  36274. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  36275. * @param {Node} node - The node to execute.
  36276. * @param {?string} output - Expected output type. For example 'vec3'.
  36277. * @param {?string} propertyName - The property name to assign the result.
  36278. * @return {?(Object|Node)} The code flow or node.build() result.
  36279. */
  36280. flowNodeFromShaderStage( shaderStage, node, output = null, propertyName = null ) {
  36281. const previousTab = this.tab;
  36282. const previousCache = this.cache;
  36283. const previousShaderStage = this.shaderStage;
  36284. const previousContext = this.context;
  36285. this.setShaderStage( shaderStage );
  36286. const context = { ...this.context };
  36287. delete context.nodeBlock;
  36288. this.cache = this.globalCache;
  36289. this.tab = '\t';
  36290. this.context = context;
  36291. let result = null;
  36292. if ( this.buildStage === 'generate' ) {
  36293. const flowData = this.flowChildNode( node, output );
  36294. if ( propertyName !== null ) {
  36295. flowData.code += `${ this.tab + propertyName } = ${ flowData.result };\n`;
  36296. }
  36297. this.flowCode[ shaderStage ] = this.flowCode[ shaderStage ] + flowData.code;
  36298. result = flowData;
  36299. } else {
  36300. result = node.build( this );
  36301. }
  36302. this.setShaderStage( previousShaderStage );
  36303. this.cache = previousCache;
  36304. this.tab = previousTab;
  36305. this.context = previousContext;
  36306. return result;
  36307. }
  36308. /**
  36309. * Returns an array holding all node attributes of this node builder.
  36310. *
  36311. * @return {Array<NodeAttribute>} The node attributes of this builder.
  36312. */
  36313. getAttributesArray() {
  36314. return this.attributes.concat( this.bufferAttributes );
  36315. }
  36316. /**
  36317. * Returns the attribute definitions as a shader string for the given shader stage.
  36318. *
  36319. * @abstract
  36320. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  36321. * @return {string} The attribute code section.
  36322. */
  36323. getAttributes( /*shaderStage*/ ) {
  36324. warn( 'Abstract function.' );
  36325. }
  36326. /**
  36327. * Returns the varying definitions as a shader string for the given shader stage.
  36328. *
  36329. * @abstract
  36330. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  36331. * @return {string} The varying code section.
  36332. */
  36333. getVaryings( /*shaderStage*/ ) {
  36334. warn( 'Abstract function.' );
  36335. }
  36336. /**
  36337. * Returns a single variable definition as a shader string for the given variable type and name.
  36338. *
  36339. * @param {string} type - The variable's type.
  36340. * @param {string} name - The variable's name.
  36341. * @param {?number} [count=null] - The array length.
  36342. * @return {string} The shader string.
  36343. */
  36344. getVar( type, name, count = null ) {
  36345. return `${ count !== null ? this.generateArrayDeclaration( type, count ) : this.getType( type ) } ${ name }`;
  36346. }
  36347. /**
  36348. * Returns the variable definitions as a shader string for the given shader stage.
  36349. *
  36350. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  36351. * @return {string} The variable code section.
  36352. */
  36353. getVars( shaderStage ) {
  36354. let snippet = '';
  36355. const vars = this.vars[ shaderStage ];
  36356. if ( vars !== undefined ) {
  36357. for ( const variable of vars ) {
  36358. snippet += `${ this.getVar( variable.type, variable.name ) }; `;
  36359. }
  36360. }
  36361. return snippet;
  36362. }
  36363. /**
  36364. * Returns the uniform definitions as a shader string for the given shader stage.
  36365. *
  36366. * @abstract
  36367. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  36368. * @return {string} The uniform code section.
  36369. */
  36370. getUniforms( /*shaderStage*/ ) {
  36371. warn( 'Abstract function.' );
  36372. }
  36373. /**
  36374. * Returns the native code definitions as a shader string for the given shader stage.
  36375. *
  36376. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  36377. * @return {string} The native code section.
  36378. */
  36379. getCodes( shaderStage ) {
  36380. const codes = this.codes[ shaderStage ];
  36381. let code = '';
  36382. if ( codes !== undefined ) {
  36383. for ( const nodeCode of codes ) {
  36384. code += nodeCode.code + '\n';
  36385. }
  36386. }
  36387. return code;
  36388. }
  36389. /**
  36390. * Returns the hash of this node builder.
  36391. *
  36392. * @return {string} The hash.
  36393. */
  36394. getHash() {
  36395. return this.vertexShader + this.fragmentShader + this.computeShader;
  36396. }
  36397. /**
  36398. * Sets the current shader stage.
  36399. *
  36400. * @param {?('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage to set.
  36401. */
  36402. setShaderStage( shaderStage ) {
  36403. this.shaderStage = shaderStage;
  36404. }
  36405. /**
  36406. * Returns the current shader stage.
  36407. *
  36408. * @return {?('vertex'|'fragment'|'compute'|'any')} The current shader stage.
  36409. */
  36410. getShaderStage() {
  36411. return this.shaderStage;
  36412. }
  36413. /**
  36414. * Sets the current build stage.
  36415. *
  36416. * @param {?('setup'|'analyze'|'generate')} buildStage - The build stage to set.
  36417. */
  36418. setBuildStage( buildStage ) {
  36419. this.buildStage = buildStage;
  36420. }
  36421. /**
  36422. * Returns the current build stage.
  36423. *
  36424. * @return {?('setup'|'analyze'|'generate')} The current build stage.
  36425. */
  36426. getBuildStage() {
  36427. return this.buildStage;
  36428. }
  36429. /**
  36430. * Controls the code build of the shader stages.
  36431. *
  36432. * @abstract
  36433. */
  36434. buildCode() {
  36435. warn( 'Abstract function.' );
  36436. }
  36437. /**
  36438. * Returns the current sub-build layer.
  36439. *
  36440. * @return {SubBuildNode} The current sub-build layers.
  36441. */
  36442. get subBuild() {
  36443. return this.subBuildLayers[ this.subBuildLayers.length - 1 ] || null;
  36444. }
  36445. /**
  36446. * Adds a sub-build layer to the node builder.
  36447. *
  36448. * @param {SubBuildNode} subBuild - The sub-build layer to add.
  36449. */
  36450. addSubBuild( subBuild ) {
  36451. this.subBuildLayers.push( subBuild );
  36452. }
  36453. /**
  36454. * Removes the last sub-build layer from the node builder.
  36455. *
  36456. * @return {SubBuildNode} The removed sub-build layer.
  36457. */
  36458. removeSubBuild() {
  36459. return this.subBuildLayers.pop();
  36460. }
  36461. /**
  36462. * Returns the closest sub-build layer for the given data.
  36463. *
  36464. * @param {Node|Set<string>|Array<string>} data - The data to get the closest sub-build layer from.
  36465. * @return {?string} The closest sub-build name or null if none found.
  36466. */
  36467. getClosestSubBuild( data ) {
  36468. let subBuilds;
  36469. if ( data && data.isNode ) {
  36470. if ( data.isShaderCallNodeInternal ) {
  36471. subBuilds = data.shaderNode.subBuilds;
  36472. } else if ( data.isStackNode ) {
  36473. subBuilds = [ data.subBuild ];
  36474. } else {
  36475. subBuilds = this.getDataFromNode( data, 'any' ).subBuilds;
  36476. }
  36477. } else if ( data instanceof Set ) {
  36478. subBuilds = [ ...data ];
  36479. } else {
  36480. subBuilds = data;
  36481. }
  36482. if ( ! subBuilds ) return null;
  36483. const subBuildLayers = this.subBuildLayers;
  36484. for ( let i = subBuilds.length - 1; i >= 0; i -- ) {
  36485. const subBuild = subBuilds[ i ];
  36486. if ( subBuildLayers.includes( subBuild ) ) {
  36487. return subBuild;
  36488. }
  36489. }
  36490. return null;
  36491. }
  36492. /**
  36493. * Returns the output node of a sub-build layer.
  36494. *
  36495. * @param {Node} node - The node to get the output from.
  36496. * @return {string} The output node name.
  36497. */
  36498. getSubBuildOutput( node ) {
  36499. return this.getSubBuildProperty( 'outputNode', node );
  36500. }
  36501. /**
  36502. * Returns the sub-build property name for the given property and node.
  36503. *
  36504. * @param {string} [property=''] - The property name.
  36505. * @param {?Node} [node=null] - The node to get the sub-build from.
  36506. * @return {string} The sub-build property name.
  36507. */
  36508. getSubBuildProperty( property = '', node = null ) {
  36509. let subBuild;
  36510. if ( node !== null ) {
  36511. subBuild = this.getClosestSubBuild( node );
  36512. } else {
  36513. subBuild = this.subBuildFn;
  36514. }
  36515. let result;
  36516. if ( subBuild ) {
  36517. result = property ? ( subBuild + '_' + property ) : subBuild;
  36518. } else {
  36519. result = property;
  36520. }
  36521. return result;
  36522. }
  36523. /**
  36524. * Central build method which controls the build for the given object.
  36525. *
  36526. * @return {NodeBuilder} A reference to this node builder.
  36527. */
  36528. build() {
  36529. const { object, material, renderer } = this;
  36530. if ( material !== null ) {
  36531. let nodeMaterial = renderer.library.fromMaterial( material );
  36532. if ( nodeMaterial === null ) {
  36533. error( `NodeMaterial: Material "${ material.type }" is not compatible.` );
  36534. nodeMaterial = new NodeMaterial();
  36535. }
  36536. nodeMaterial.build( this );
  36537. } else {
  36538. this.addFlow( 'compute', object );
  36539. }
  36540. // setup() -> stage 1: create possible new nodes and/or return an output reference node
  36541. // analyze() -> stage 2: analyze nodes to possible optimization and validation
  36542. // generate() -> stage 3: generate shader
  36543. for ( const buildStage of defaultBuildStages ) {
  36544. this.setBuildStage( buildStage );
  36545. if ( this.context.vertex && this.context.vertex.isNode ) {
  36546. this.flowNodeFromShaderStage( 'vertex', this.context.vertex );
  36547. }
  36548. for ( const shaderStage of shaderStages ) {
  36549. this.setShaderStage( shaderStage );
  36550. const flowNodes = this.flowNodes[ shaderStage ];
  36551. for ( const node of flowNodes ) {
  36552. if ( buildStage === 'generate' ) {
  36553. this.flowNode( node );
  36554. } else {
  36555. node.build( this );
  36556. }
  36557. }
  36558. }
  36559. }
  36560. this.setBuildStage( null );
  36561. this.setShaderStage( null );
  36562. // stage 4: build code for a specific output
  36563. this.buildCode();
  36564. this.buildUpdateNodes();
  36565. return this;
  36566. }
  36567. /**
  36568. * Returns a uniform representation which is later used for UBO generation and rendering.
  36569. *
  36570. * @param {NodeUniform} uniformNode - The uniform node.
  36571. * @param {string} type - The requested type.
  36572. * @return {Uniform} The uniform.
  36573. */
  36574. getNodeUniform( uniformNode, type ) {
  36575. if ( type === 'float' || type === 'int' || type === 'uint' ) return new NumberNodeUniform( uniformNode );
  36576. if ( type === 'vec2' || type === 'ivec2' || type === 'uvec2' ) return new Vector2NodeUniform( uniformNode );
  36577. if ( type === 'vec3' || type === 'ivec3' || type === 'uvec3' ) return new Vector3NodeUniform( uniformNode );
  36578. if ( type === 'vec4' || type === 'ivec4' || type === 'uvec4' ) return new Vector4NodeUniform( uniformNode );
  36579. if ( type === 'color' ) return new ColorNodeUniform( uniformNode );
  36580. if ( type === 'mat2' ) return new Matrix2NodeUniform( uniformNode );
  36581. if ( type === 'mat3' ) return new Matrix3NodeUniform( uniformNode );
  36582. if ( type === 'mat4' ) return new Matrix4NodeUniform( uniformNode );
  36583. throw new Error( `Uniform "${type}" not declared.` );
  36584. }
  36585. /**
  36586. * Formats the given shader snippet from a given type into another one. E.g.
  36587. * this method might be used to convert a simple float string `"1.0"` into a
  36588. * `vec3` representation: `"vec3<f32>( 1.0 )"`.
  36589. *
  36590. * @param {string} snippet - The shader snippet.
  36591. * @param {string} fromType - The source type.
  36592. * @param {string} toType - The target type.
  36593. * @return {string} The updated shader string.
  36594. */
  36595. format( snippet, fromType, toType ) {
  36596. fromType = this.getVectorType( fromType );
  36597. toType = this.getVectorType( toType );
  36598. if ( fromType === toType || toType === null || this.isReference( toType ) ) {
  36599. return snippet;
  36600. }
  36601. const fromTypeLength = this.getTypeLength( fromType );
  36602. const toTypeLength = this.getTypeLength( toType );
  36603. if ( fromTypeLength === 16 && toTypeLength === 9 ) {
  36604. return `${ this.getType( toType ) }( ${ snippet }[ 0 ].xyz, ${ snippet }[ 1 ].xyz, ${ snippet }[ 2 ].xyz )`;
  36605. }
  36606. if ( fromTypeLength === 9 && toTypeLength === 4 ) {
  36607. return `${ this.getType( toType ) }( ${ snippet }[ 0 ].xy, ${ snippet }[ 1 ].xy )`;
  36608. }
  36609. if ( fromTypeLength > 4 ) { // fromType is matrix-like
  36610. // @TODO: ignore for now
  36611. return snippet;
  36612. }
  36613. if ( toTypeLength > 4 || toTypeLength === 0 ) { // toType is matrix-like or unknown
  36614. // @TODO: ignore for now
  36615. return snippet;
  36616. }
  36617. if ( fromTypeLength === toTypeLength ) {
  36618. return `${ this.getType( toType ) }( ${ snippet } )`;
  36619. }
  36620. if ( fromTypeLength > toTypeLength ) {
  36621. snippet = toType === 'bool' ? `all( ${ snippet } )` : `${ snippet }.${ 'xyz'.slice( 0, toTypeLength ) }`;
  36622. return this.format( snippet, this.getTypeFromLength( toTypeLength, this.getComponentType( fromType ) ), toType );
  36623. }
  36624. if ( toTypeLength === 4 && fromTypeLength > 1 ) { // toType is vec4-like
  36625. return `${ this.getType( toType ) }( ${ this.format( snippet, fromType, 'vec3' ) }, 1.0 )`;
  36626. }
  36627. if ( fromTypeLength === 2 ) { // fromType is vec2-like and toType is vec3-like
  36628. return `${ this.getType( toType ) }( ${ this.format( snippet, fromType, 'vec2' ) }, 0.0 )`;
  36629. }
  36630. if ( fromTypeLength === 1 && toTypeLength > 1 && fromType !== this.getComponentType( toType ) ) { // fromType is float-like
  36631. // convert a number value to vector type, e.g:
  36632. // vec3( 1u ) -> vec3( float( 1u ) )
  36633. snippet = `${ this.getType( this.getComponentType( toType ) ) }( ${ snippet } )`;
  36634. }
  36635. return `${ this.getType( toType ) }( ${ snippet } )`; // fromType is float-like
  36636. }
  36637. /**
  36638. * Returns a signature with the engine's current revision.
  36639. *
  36640. * @return {string} The signature.
  36641. */
  36642. getSignature() {
  36643. return `// Three.js r${ REVISION } - Node System\n`;
  36644. }
  36645. }
  36646. /**
  36647. * Management class for updating nodes. The module tracks metrics like
  36648. * the elapsed time, delta time, the render and frame ID to correctly
  36649. * call the node update methods {@link Node#updateBefore}, {@link Node#update}
  36650. * and {@link Node#updateAfter} depending on the node's configuration.
  36651. */
  36652. class NodeFrame {
  36653. /**
  36654. * Constructs a new node fame.
  36655. */
  36656. constructor() {
  36657. /**
  36658. * The elapsed time in seconds.
  36659. *
  36660. * @type {number}
  36661. * @default 0
  36662. */
  36663. this.time = 0;
  36664. /**
  36665. * The delta time in seconds.
  36666. *
  36667. * @type {number}
  36668. * @default 0
  36669. */
  36670. this.deltaTime = 0;
  36671. /**
  36672. * The frame ID.
  36673. *
  36674. * @type {number}
  36675. * @default 0
  36676. */
  36677. this.frameId = 0;
  36678. /**
  36679. * The render ID.
  36680. *
  36681. * @type {number}
  36682. * @default 0
  36683. */
  36684. this.renderId = 0;
  36685. /**
  36686. * Used to control the {@link Node#update} call.
  36687. *
  36688. * @type {WeakMap<Node, Object>}
  36689. */
  36690. this.updateMap = new WeakMap();
  36691. /**
  36692. * Used to control the {@link Node#updateBefore} call.
  36693. *
  36694. * @type {WeakMap<Node, Object>}
  36695. */
  36696. this.updateBeforeMap = new WeakMap();
  36697. /**
  36698. * Used to control the {@link Node#updateAfter} call.
  36699. *
  36700. * @type {WeakMap<Node, Object>}
  36701. */
  36702. this.updateAfterMap = new WeakMap();
  36703. /**
  36704. * A reference to the current renderer.
  36705. *
  36706. * @type {?Renderer}
  36707. * @default null
  36708. */
  36709. this.renderer = null;
  36710. /**
  36711. * A reference to the current material.
  36712. *
  36713. * @type {?Material}
  36714. * @default null
  36715. */
  36716. this.material = null;
  36717. /**
  36718. * A reference to the current camera.
  36719. *
  36720. * @type {?Camera}
  36721. * @default null
  36722. */
  36723. this.camera = null;
  36724. /**
  36725. * A reference to the current 3D object.
  36726. *
  36727. * @type {?Object3D}
  36728. * @default null
  36729. */
  36730. this.object = null;
  36731. /**
  36732. * A reference to the current scene.
  36733. *
  36734. * @type {?Scene}
  36735. * @default null
  36736. */
  36737. this.scene = null;
  36738. }
  36739. /**
  36740. * Returns a dictionary for a given node and update map which
  36741. * is used to correctly call node update methods per frame or render.
  36742. *
  36743. * @private
  36744. * @param {WeakMap<Node, Object>} referenceMap - The reference weak map.
  36745. * @param {Node} nodeRef - The reference to the current node.
  36746. * @return {Object<string,WeakMap<Object, number>>} The dictionary.
  36747. */
  36748. _getMaps( referenceMap, nodeRef ) {
  36749. let maps = referenceMap.get( nodeRef );
  36750. if ( maps === undefined ) {
  36751. maps = {
  36752. renderId: 0,
  36753. frameId: 0,
  36754. };
  36755. referenceMap.set( nodeRef, maps );
  36756. }
  36757. return maps;
  36758. }
  36759. /**
  36760. * This method executes the {@link Node#updateBefore} for the given node.
  36761. * It makes sure {@link Node#updateBeforeType} is honored meaning the update
  36762. * is only executed once per frame, render or object depending on the update
  36763. * type.
  36764. *
  36765. * @param {Node} node - The node that should be updated.
  36766. */
  36767. updateBeforeNode( node ) {
  36768. const updateType = node.getUpdateBeforeType();
  36769. const reference = node.updateReference( this );
  36770. if ( updateType === NodeUpdateType.FRAME ) {
  36771. const nodeUpdateBeforeMap = this._getMaps( this.updateBeforeMap, reference );
  36772. if ( nodeUpdateBeforeMap.frameId !== this.frameId ) {
  36773. if ( node.updateBefore( this ) !== false ) {
  36774. nodeUpdateBeforeMap.frameId = this.frameId;
  36775. }
  36776. }
  36777. } else if ( updateType === NodeUpdateType.RENDER ) {
  36778. const nodeUpdateBeforeMap = this._getMaps( this.updateBeforeMap, reference );
  36779. if ( nodeUpdateBeforeMap.renderId !== this.renderId ) {
  36780. if ( node.updateBefore( this ) !== false ) {
  36781. nodeUpdateBeforeMap.renderId = this.renderId;
  36782. }
  36783. }
  36784. } else if ( updateType === NodeUpdateType.OBJECT ) {
  36785. node.updateBefore( this );
  36786. }
  36787. }
  36788. /**
  36789. * This method executes the {@link Node#updateAfter} for the given node.
  36790. * It makes sure {@link Node#updateAfterType} is honored meaning the update
  36791. * is only executed once per frame, render or object depending on the update
  36792. * type.
  36793. *
  36794. * @param {Node} node - The node that should be updated.
  36795. */
  36796. updateAfterNode( node ) {
  36797. const updateType = node.getUpdateAfterType();
  36798. const reference = node.updateReference( this );
  36799. if ( updateType === NodeUpdateType.FRAME ) {
  36800. const nodeUpdateAfterMap = this._getMaps( this.updateAfterMap, reference );
  36801. if ( nodeUpdateAfterMap.frameId !== this.frameId ) {
  36802. if ( node.updateAfter( this ) !== false ) {
  36803. nodeUpdateAfterMap.frameId = this.frameId;
  36804. }
  36805. }
  36806. } else if ( updateType === NodeUpdateType.RENDER ) {
  36807. const nodeUpdateAfterMap = this._getMaps( this.updateAfterMap, reference );
  36808. if ( nodeUpdateAfterMap.renderId !== this.renderId ) {
  36809. if ( node.updateAfter( this ) !== false ) {
  36810. nodeUpdateAfterMap.renderId = this.renderId;
  36811. }
  36812. }
  36813. } else if ( updateType === NodeUpdateType.OBJECT ) {
  36814. node.updateAfter( this );
  36815. }
  36816. }
  36817. /**
  36818. * This method executes the {@link Node#update} for the given node.
  36819. * It makes sure {@link Node#updateType} is honored meaning the update
  36820. * is only executed once per frame, render or object depending on the update
  36821. * type.
  36822. *
  36823. * @param {Node} node - The node that should be updated.
  36824. */
  36825. updateNode( node ) {
  36826. const updateType = node.getUpdateType();
  36827. const reference = node.updateReference( this );
  36828. if ( updateType === NodeUpdateType.FRAME ) {
  36829. const nodeUpdateMap = this._getMaps( this.updateMap, reference );
  36830. if ( nodeUpdateMap.frameId !== this.frameId ) {
  36831. if ( node.update( this ) !== false ) {
  36832. nodeUpdateMap.frameId = this.frameId;
  36833. }
  36834. }
  36835. } else if ( updateType === NodeUpdateType.RENDER ) {
  36836. const nodeUpdateMap = this._getMaps( this.updateMap, reference );
  36837. if ( nodeUpdateMap.renderId !== this.renderId ) {
  36838. if ( node.update( this ) !== false ) {
  36839. nodeUpdateMap.renderId = this.renderId;
  36840. }
  36841. }
  36842. } else if ( updateType === NodeUpdateType.OBJECT ) {
  36843. node.update( this );
  36844. }
  36845. }
  36846. /**
  36847. * Updates the internal state of the node frame. This method is
  36848. * called by the renderer in its internal animation loop.
  36849. */
  36850. update() {
  36851. this.frameId ++;
  36852. if ( this.lastTime === undefined ) this.lastTime = performance.now();
  36853. this.deltaTime = ( performance.now() - this.lastTime ) / 1000;
  36854. this.lastTime = performance.now();
  36855. this.time += this.deltaTime;
  36856. }
  36857. }
  36858. /**
  36859. * Describes the input of a {@link NodeFunction}.
  36860. */
  36861. class NodeFunctionInput {
  36862. /**
  36863. * Constructs a new node function input.
  36864. *
  36865. * @param {string} type - The input type.
  36866. * @param {string} name - The input name.
  36867. * @param {?number} [count=null] - If the input is an Array, count will be the length.
  36868. * @param {('in'|'out'|'inout')} [qualifier=''] - The parameter qualifier (only relevant for GLSL).
  36869. * @param {boolean} [isConst=false] - Whether the input uses a const qualifier or not (only relevant for GLSL).
  36870. */
  36871. constructor( type, name, count = null, qualifier = '', isConst = false ) {
  36872. /**
  36873. * The input type.
  36874. *
  36875. * @type {string}
  36876. */
  36877. this.type = type;
  36878. /**
  36879. * The input name.
  36880. *
  36881. * @type {string}
  36882. */
  36883. this.name = name;
  36884. /**
  36885. * If the input is an Array, count will be the length.
  36886. *
  36887. * @type {?number}
  36888. * @default null
  36889. */
  36890. this.count = count;
  36891. /**
  36892. *The parameter qualifier (only relevant for GLSL).
  36893. *
  36894. * @type {('in'|'out'|'inout')}
  36895. * @default ''
  36896. */
  36897. this.qualifier = qualifier;
  36898. /**
  36899. * Whether the input uses a const qualifier or not (only relevant for GLSL).
  36900. *
  36901. * @type {boolean}
  36902. * @default false
  36903. */
  36904. this.isConst = isConst;
  36905. }
  36906. }
  36907. NodeFunctionInput.isNodeFunctionInput = true;
  36908. /**
  36909. * Module for representing directional lights as nodes.
  36910. *
  36911. * @augments AnalyticLightNode
  36912. */
  36913. class DirectionalLightNode extends AnalyticLightNode {
  36914. static get type() {
  36915. return 'DirectionalLightNode';
  36916. }
  36917. /**
  36918. * Constructs a new directional light node.
  36919. *
  36920. * @param {?DirectionalLight} [light=null] - The directional light source.
  36921. */
  36922. constructor( light = null ) {
  36923. super( light );
  36924. }
  36925. setupDirect() {
  36926. const lightColor = this.colorNode;
  36927. const lightDirection = lightTargetDirection( this.light );
  36928. return { lightDirection, lightColor };
  36929. }
  36930. }
  36931. const _matrix41 = /*@__PURE__*/ new Matrix4();
  36932. const _matrix42 = /*@__PURE__*/ new Matrix4();
  36933. let _ltcLib = null;
  36934. /**
  36935. * Module for representing rect area lights as nodes.
  36936. *
  36937. * @augments AnalyticLightNode
  36938. */
  36939. class RectAreaLightNode extends AnalyticLightNode {
  36940. static get type() {
  36941. return 'RectAreaLightNode';
  36942. }
  36943. /**
  36944. * Constructs a new rect area light node.
  36945. *
  36946. * @param {?RectAreaLight} [light=null] - The rect area light source.
  36947. */
  36948. constructor( light = null ) {
  36949. super( light );
  36950. /**
  36951. * Uniform node representing the half height of the are light.
  36952. *
  36953. * @type {UniformNode<vec3>}
  36954. */
  36955. this.halfHeight = uniform( new Vector3() ).setGroup( renderGroup );
  36956. /**
  36957. * Uniform node representing the half width of the are light.
  36958. *
  36959. * @type {UniformNode<vec3>}
  36960. */
  36961. this.halfWidth = uniform( new Vector3() ).setGroup( renderGroup );
  36962. /**
  36963. * The `updateType` is set to `NodeUpdateType.RENDER` since the light
  36964. * relies on `viewMatrix` which might vary per render call.
  36965. *
  36966. * @type {string}
  36967. * @default 'render'
  36968. */
  36969. this.updateType = NodeUpdateType.RENDER;
  36970. }
  36971. /**
  36972. * Overwritten to updated rect area light specific uniforms.
  36973. *
  36974. * @param {NodeFrame} frame - A reference to the current node frame.
  36975. */
  36976. update( frame ) {
  36977. super.update( frame );
  36978. const { light } = this;
  36979. const viewMatrix = frame.camera.matrixWorldInverse;
  36980. _matrix42.identity();
  36981. _matrix41.copy( light.matrixWorld );
  36982. _matrix41.premultiply( viewMatrix );
  36983. _matrix42.extractRotation( _matrix41 );
  36984. this.halfWidth.value.set( light.width * 0.5, 0.0, 0.0 );
  36985. this.halfHeight.value.set( 0.0, light.height * 0.5, 0.0 );
  36986. this.halfWidth.value.applyMatrix4( _matrix42 );
  36987. this.halfHeight.value.applyMatrix4( _matrix42 );
  36988. }
  36989. setupDirectRectArea( builder ) {
  36990. let ltc_1, ltc_2;
  36991. if ( builder.isAvailable( 'float32Filterable' ) ) {
  36992. ltc_1 = texture( _ltcLib.LTC_FLOAT_1 );
  36993. ltc_2 = texture( _ltcLib.LTC_FLOAT_2 );
  36994. } else {
  36995. ltc_1 = texture( _ltcLib.LTC_HALF_1 );
  36996. ltc_2 = texture( _ltcLib.LTC_HALF_2 );
  36997. }
  36998. const { colorNode, light } = this;
  36999. const lightPosition = lightViewPosition( light );
  37000. return {
  37001. lightColor: colorNode,
  37002. lightPosition,
  37003. halfWidth: this.halfWidth,
  37004. halfHeight: this.halfHeight,
  37005. ltc_1,
  37006. ltc_2
  37007. };
  37008. }
  37009. /**
  37010. * Used to configure the internal BRDF approximation texture data.
  37011. *
  37012. * @param {RectAreaLightTexturesLib} ltc - The BRDF approximation texture data.
  37013. */
  37014. static setLTC( ltc ) {
  37015. _ltcLib = ltc;
  37016. }
  37017. }
  37018. /**
  37019. * Module for representing spot lights as nodes.
  37020. *
  37021. * @augments AnalyticLightNode
  37022. */
  37023. class SpotLightNode extends AnalyticLightNode {
  37024. static get type() {
  37025. return 'SpotLightNode';
  37026. }
  37027. /**
  37028. * Constructs a new spot light node.
  37029. *
  37030. * @param {?SpotLight} [light=null] - The spot light source.
  37031. */
  37032. constructor( light = null ) {
  37033. super( light );
  37034. /**
  37035. * Uniform node representing the cone cosine.
  37036. *
  37037. * @type {UniformNode<float>}
  37038. */
  37039. this.coneCosNode = uniform( 0 ).setGroup( renderGroup );
  37040. /**
  37041. * Uniform node representing the penumbra cosine.
  37042. *
  37043. * @type {UniformNode<float>}
  37044. */
  37045. this.penumbraCosNode = uniform( 0 ).setGroup( renderGroup );
  37046. /**
  37047. * Uniform node representing the cutoff distance.
  37048. *
  37049. * @type {UniformNode<float>}
  37050. */
  37051. this.cutoffDistanceNode = uniform( 0 ).setGroup( renderGroup );
  37052. /**
  37053. * Uniform node representing the decay exponent.
  37054. *
  37055. * @type {UniformNode<float>}
  37056. */
  37057. this.decayExponentNode = uniform( 0 ).setGroup( renderGroup );
  37058. /**
  37059. * Uniform node representing the light color.
  37060. *
  37061. * @type {UniformNode<Color>}
  37062. */
  37063. this.colorNode = uniform( this.color ).setGroup( renderGroup );
  37064. }
  37065. /**
  37066. * Overwritten to updated spot light specific uniforms.
  37067. *
  37068. * @param {NodeFrame} frame - A reference to the current node frame.
  37069. */
  37070. update( frame ) {
  37071. super.update( frame );
  37072. const { light } = this;
  37073. this.coneCosNode.value = Math.cos( light.angle );
  37074. this.penumbraCosNode.value = Math.cos( light.angle * ( 1 - light.penumbra ) );
  37075. this.cutoffDistanceNode.value = light.distance;
  37076. this.decayExponentNode.value = light.decay;
  37077. }
  37078. /**
  37079. * Computes the spot attenuation for the given angle.
  37080. *
  37081. * @param {NodeBuilder} builder - The node builder.
  37082. * @param {Node<float>} angleCosine - The angle to compute the spot attenuation for.
  37083. * @return {Node<float>} The spot attenuation.
  37084. */
  37085. getSpotAttenuation( builder, angleCosine ) {
  37086. const { coneCosNode, penumbraCosNode } = this;
  37087. return smoothstep( coneCosNode, penumbraCosNode, angleCosine );
  37088. }
  37089. getLightCoord( builder ) {
  37090. const properties = builder.getNodeProperties( this );
  37091. let projectionUV = properties.projectionUV;
  37092. if ( projectionUV === undefined ) {
  37093. projectionUV = lightProjectionUV( this.light, builder.context.positionWorld );
  37094. properties.projectionUV = projectionUV;
  37095. }
  37096. return projectionUV;
  37097. }
  37098. setupDirect( builder ) {
  37099. const { colorNode, cutoffDistanceNode, decayExponentNode, light } = this;
  37100. const lightVector = this.getLightVector( builder );
  37101. const lightDirection = lightVector.normalize();
  37102. const angleCos = lightDirection.dot( lightTargetDirection( light ) );
  37103. const spotAttenuation = this.getSpotAttenuation( builder, angleCos );
  37104. const lightDistance = lightVector.length();
  37105. const lightAttenuation = getDistanceAttenuation( {
  37106. lightDistance,
  37107. cutoffDistance: cutoffDistanceNode,
  37108. decayExponent: decayExponentNode
  37109. } );
  37110. let lightColor = colorNode.mul( spotAttenuation ).mul( lightAttenuation );
  37111. let projected, lightCoord;
  37112. if ( light.colorNode ) {
  37113. lightCoord = this.getLightCoord( builder );
  37114. projected = light.colorNode( lightCoord );
  37115. } else if ( light.map ) {
  37116. lightCoord = this.getLightCoord( builder );
  37117. projected = texture( light.map, lightCoord.xy ).onRenderUpdate( () => light.map );
  37118. }
  37119. if ( projected ) {
  37120. const inSpotLightMap = lightCoord.mul( 2. ).sub( 1. ).abs().lessThan( 1. ).all();
  37121. lightColor = inSpotLightMap.select( lightColor.mul( projected ), lightColor );
  37122. }
  37123. return { lightColor, lightDirection };
  37124. }
  37125. }
  37126. /**
  37127. * An IES version of the default spot light node.
  37128. *
  37129. * @augments SpotLightNode
  37130. */
  37131. class IESSpotLightNode extends SpotLightNode {
  37132. static get type() {
  37133. return 'IESSpotLightNode';
  37134. }
  37135. /**
  37136. * Overwrites the default implementation to compute an IES conform spot attenuation.
  37137. *
  37138. * @param {NodeBuilder} builder - The node builder.
  37139. * @param {Node<float>} angleCosine - The angle to compute the spot attenuation for.
  37140. * @return {Node<float>} The spot attenuation.
  37141. */
  37142. getSpotAttenuation( builder, angleCosine ) {
  37143. const iesMap = this.light.iesMap;
  37144. let spotAttenuation = null;
  37145. if ( iesMap && iesMap.isTexture === true ) {
  37146. const angle = angleCosine.acos().mul( 1.0 / Math.PI );
  37147. spotAttenuation = texture( iesMap, vec2( angle, 0 ), 0 ).r;
  37148. } else {
  37149. spotAttenuation = super.getSpotAttenuation( angleCosine );
  37150. }
  37151. return spotAttenuation;
  37152. }
  37153. }
  37154. const sdBox = /*@__PURE__*/ Fn( ( [ p, b ] ) => {
  37155. const d = p.abs().sub( b );
  37156. return length( max$1( d, 0.0 ) ).add( min$1( max$1( d.x, d.y ), 0.0 ) );
  37157. } );
  37158. /**
  37159. * An implementation of a projector light node.
  37160. *
  37161. * @augments SpotLightNode
  37162. */
  37163. class ProjectorLightNode extends SpotLightNode {
  37164. static get type() {
  37165. return 'ProjectorLightNode';
  37166. }
  37167. update( frame ) {
  37168. super.update( frame );
  37169. const light = this.light;
  37170. this.penumbraCosNode.value = Math.min( Math.cos( light.angle * ( 1 - light.penumbra ) ), .99999 );
  37171. if ( light.aspect === null ) {
  37172. let aspect = 1;
  37173. if ( light.map !== null ) {
  37174. aspect = light.map.width / light.map.height;
  37175. }
  37176. light.shadow.aspect = aspect;
  37177. } else {
  37178. light.shadow.aspect = light.aspect;
  37179. }
  37180. }
  37181. /**
  37182. * Overwrites the default implementation to compute projection attenuation.
  37183. *
  37184. * @param {NodeBuilder} builder - The node builder.
  37185. * @return {Node<float>} The spot attenuation.
  37186. */
  37187. getSpotAttenuation( builder ) {
  37188. const attenuation = float( 0 );
  37189. const penumbraCos = this.penumbraCosNode;
  37190. // compute the fragment's position in the light's clip space
  37191. const spotLightCoord = lightShadowMatrix( this.light ).mul( builder.context.positionWorld || positionWorld );
  37192. // the sign of w determines whether the current fragment is in front or behind the light.
  37193. // to avoid a back-projection, it's important to only compute an attenuation if w is positive
  37194. If( spotLightCoord.w.greaterThan( 0 ), () => {
  37195. const projectionUV = spotLightCoord.xyz.div( spotLightCoord.w );
  37196. const boxDist = sdBox( projectionUV.xy.sub( vec2( 0.5 ) ), vec2( 0.5 ) );
  37197. const angleFactor = div( -1, sub( 1.0, acos( penumbraCos ) ).sub( 1.0 ) );
  37198. attenuation.assign( saturate( boxDist.mul( -2 ).mul( angleFactor ) ) );
  37199. } );
  37200. return attenuation;
  37201. }
  37202. }
  37203. /**
  37204. * Module for representing ambient lights as nodes.
  37205. *
  37206. * @augments AnalyticLightNode
  37207. */
  37208. class AmbientLightNode extends AnalyticLightNode {
  37209. static get type() {
  37210. return 'AmbientLightNode';
  37211. }
  37212. /**
  37213. * Constructs a new ambient light node.
  37214. *
  37215. * @param {?AmbientLight} [light=null] - The ambient light source.
  37216. */
  37217. constructor( light = null ) {
  37218. super( light );
  37219. }
  37220. setup( { context } ) {
  37221. context.irradiance.addAssign( this.colorNode );
  37222. }
  37223. }
  37224. /**
  37225. * Module for representing hemisphere lights as nodes.
  37226. *
  37227. * @augments AnalyticLightNode
  37228. */
  37229. class HemisphereLightNode extends AnalyticLightNode {
  37230. static get type() {
  37231. return 'HemisphereLightNode';
  37232. }
  37233. /**
  37234. * Constructs a new hemisphere light node.
  37235. *
  37236. * @param {?HemisphereLight} [light=null] - The hemisphere light source.
  37237. */
  37238. constructor( light = null ) {
  37239. super( light );
  37240. /**
  37241. * Uniform node representing the light's position.
  37242. *
  37243. * @type {UniformNode<vec3>}
  37244. */
  37245. this.lightPositionNode = lightPosition( light );
  37246. /**
  37247. * A node representing the light's direction.
  37248. *
  37249. * @type {Node<vec3>}
  37250. */
  37251. this.lightDirectionNode = this.lightPositionNode.normalize();
  37252. /**
  37253. * Uniform node representing the light's ground color.
  37254. *
  37255. * @type {UniformNode<vec3>}
  37256. */
  37257. this.groundColorNode = uniform( new Color() ).setGroup( renderGroup );
  37258. }
  37259. /**
  37260. * Overwritten to updated hemisphere light specific uniforms.
  37261. *
  37262. * @param {NodeFrame} frame - A reference to the current node frame.
  37263. */
  37264. update( frame ) {
  37265. const { light } = this;
  37266. super.update( frame );
  37267. this.lightPositionNode.object3d = light;
  37268. this.groundColorNode.value.copy( light.groundColor ).multiplyScalar( light.intensity );
  37269. }
  37270. setup( builder ) {
  37271. const { colorNode, groundColorNode, lightDirectionNode } = this;
  37272. const dotNL = normalWorld.dot( lightDirectionNode );
  37273. const hemiDiffuseWeight = dotNL.mul( 0.5 ).add( 0.5 );
  37274. const irradiance = mix( groundColorNode, colorNode, hemiDiffuseWeight );
  37275. builder.context.irradiance.addAssign( irradiance );
  37276. }
  37277. }
  37278. /**
  37279. * Module for representing light probes as nodes.
  37280. *
  37281. * @augments AnalyticLightNode
  37282. */
  37283. class LightProbeNode extends AnalyticLightNode {
  37284. static get type() {
  37285. return 'LightProbeNode';
  37286. }
  37287. /**
  37288. * Constructs a new light probe node.
  37289. *
  37290. * @param {?LightProbe} [light=null] - The light probe.
  37291. */
  37292. constructor( light = null ) {
  37293. super( light );
  37294. const array = [];
  37295. for ( let i = 0; i < 9; i ++ ) array.push( new Vector3() );
  37296. /**
  37297. * Light probe represented as a uniform of spherical harmonics.
  37298. *
  37299. * @type {UniformArrayNode}
  37300. */
  37301. this.lightProbe = uniformArray( array );
  37302. }
  37303. /**
  37304. * Overwritten to updated light probe specific uniforms.
  37305. *
  37306. * @param {NodeFrame} frame - A reference to the current node frame.
  37307. */
  37308. update( frame ) {
  37309. const { light } = this;
  37310. super.update( frame );
  37311. //
  37312. for ( let i = 0; i < 9; i ++ ) {
  37313. this.lightProbe.array[ i ].copy( light.sh.coefficients[ i ] ).multiplyScalar( light.intensity );
  37314. }
  37315. }
  37316. setup( builder ) {
  37317. const irradiance = getShIrradianceAt( normalWorld, this.lightProbe );
  37318. builder.context.irradiance.addAssign( irradiance );
  37319. }
  37320. }
  37321. /**
  37322. * Base class for node parsers. A derived parser must be implemented
  37323. * for each supported native shader language.
  37324. */
  37325. class NodeParser {
  37326. /**
  37327. * The method parses the given native code an returns a node function.
  37328. *
  37329. * @abstract
  37330. * @param {string} source - The native shader code.
  37331. * @return {NodeFunction} A node function.
  37332. */
  37333. parseFunction( /*source*/ ) {
  37334. warn( 'Abstract function.' );
  37335. }
  37336. }
  37337. /**
  37338. * Base class for node functions. A derived module must be implemented
  37339. * for each supported native shader language. Similar to other `Node*` modules,
  37340. * this class is only relevant during the building process and not used
  37341. * in user-level code.
  37342. */
  37343. class NodeFunction {
  37344. /**
  37345. * Constructs a new node function.
  37346. *
  37347. * @param {string} type - The node type. This type is the return type of the node function.
  37348. * @param {Array<NodeFunctionInput>} inputs - The function's inputs.
  37349. * @param {string} [name=''] - The function's name.
  37350. * @param {string} [precision=''] - The precision qualifier.
  37351. */
  37352. constructor( type, inputs, name = '', precision = '' ) {
  37353. /**
  37354. * The node type. This type is the return type of the node function.
  37355. *
  37356. * @type {string}
  37357. */
  37358. this.type = type;
  37359. /**
  37360. * The function's inputs.
  37361. *
  37362. * @type {Array<NodeFunctionInput>}
  37363. */
  37364. this.inputs = inputs;
  37365. /**
  37366. * The name of the uniform.
  37367. *
  37368. * @type {string}
  37369. * @default ''
  37370. */
  37371. this.name = name;
  37372. /**
  37373. * The precision qualifier.
  37374. *
  37375. * @type {string}
  37376. * @default ''
  37377. */
  37378. this.precision = precision;
  37379. }
  37380. /**
  37381. * This method returns the native code of the node function.
  37382. *
  37383. * @abstract
  37384. * @param {string} name - The function's name.
  37385. * @return {string} A shader code.
  37386. */
  37387. getCode( /*name = this.name*/ ) {
  37388. warn( 'Abstract function.' );
  37389. }
  37390. }
  37391. NodeFunction.isNodeFunction = true;
  37392. const declarationRegexp$1 = /^\s*(highp|mediump|lowp)?\s*([a-z_0-9]+)\s*([a-z_0-9]+)?\s*\(([\s\S]*?)\)/i;
  37393. const propertiesRegexp$1 = /[a-z_0-9]+/ig;
  37394. const pragmaMain = '#pragma main';
  37395. const parse$1 = ( source ) => {
  37396. source = source.trim();
  37397. const pragmaMainIndex = source.indexOf( pragmaMain );
  37398. const mainCode = pragmaMainIndex !== -1 ? source.slice( pragmaMainIndex + pragmaMain.length ) : source;
  37399. const declaration = mainCode.match( declarationRegexp$1 );
  37400. if ( declaration !== null && declaration.length === 5 ) {
  37401. // tokenizer
  37402. const inputsCode = declaration[ 4 ];
  37403. const propsMatches = [];
  37404. let nameMatch = null;
  37405. while ( ( nameMatch = propertiesRegexp$1.exec( inputsCode ) ) !== null ) {
  37406. propsMatches.push( nameMatch );
  37407. }
  37408. // parser
  37409. const inputs = [];
  37410. let i = 0;
  37411. while ( i < propsMatches.length ) {
  37412. const isConst = propsMatches[ i ][ 0 ] === 'const';
  37413. if ( isConst === true ) {
  37414. i ++;
  37415. }
  37416. let qualifier = propsMatches[ i ][ 0 ];
  37417. if ( qualifier === 'in' || qualifier === 'out' || qualifier === 'inout' ) {
  37418. i ++;
  37419. } else {
  37420. qualifier = '';
  37421. }
  37422. const type = propsMatches[ i ++ ][ 0 ];
  37423. let count = Number.parseInt( propsMatches[ i ][ 0 ] );
  37424. if ( Number.isNaN( count ) === false ) i ++;
  37425. else count = null;
  37426. const name = propsMatches[ i ++ ][ 0 ];
  37427. inputs.push( new NodeFunctionInput( type, name, count, qualifier, isConst ) );
  37428. }
  37429. //
  37430. const blockCode = mainCode.substring( declaration[ 0 ].length );
  37431. const name = declaration[ 3 ] !== undefined ? declaration[ 3 ] : '';
  37432. const type = declaration[ 2 ];
  37433. const precision = declaration[ 1 ] !== undefined ? declaration[ 1 ] : '';
  37434. const headerCode = pragmaMainIndex !== -1 ? source.slice( 0, pragmaMainIndex ) : '';
  37435. return {
  37436. type,
  37437. inputs,
  37438. name,
  37439. precision,
  37440. inputsCode,
  37441. blockCode,
  37442. headerCode
  37443. };
  37444. } else {
  37445. throw new Error( 'FunctionNode: Function is not a GLSL code.' );
  37446. }
  37447. };
  37448. /**
  37449. * This class represents a GLSL node function.
  37450. *
  37451. * @augments NodeFunction
  37452. */
  37453. class GLSLNodeFunction extends NodeFunction {
  37454. /**
  37455. * Constructs a new GLSL node function.
  37456. *
  37457. * @param {string} source - The GLSL source.
  37458. */
  37459. constructor( source ) {
  37460. const { type, inputs, name, precision, inputsCode, blockCode, headerCode } = parse$1( source );
  37461. super( type, inputs, name, precision );
  37462. this.inputsCode = inputsCode;
  37463. this.blockCode = blockCode;
  37464. this.headerCode = headerCode;
  37465. }
  37466. /**
  37467. * This method returns the GLSL code of the node function.
  37468. *
  37469. * @param {string} [name=this.name] - The function's name.
  37470. * @return {string} The shader code.
  37471. */
  37472. getCode( name = this.name ) {
  37473. let code;
  37474. const blockCode = this.blockCode;
  37475. if ( blockCode !== '' ) {
  37476. const { type, inputsCode, headerCode, precision } = this;
  37477. let declarationCode = `${ type } ${ name } ( ${ inputsCode.trim() } )`;
  37478. if ( precision !== '' ) {
  37479. declarationCode = `${ precision } ${ declarationCode }`;
  37480. }
  37481. code = headerCode + declarationCode + blockCode;
  37482. } else {
  37483. // interface function
  37484. code = '';
  37485. }
  37486. return code;
  37487. }
  37488. }
  37489. /**
  37490. * A GLSL node parser.
  37491. *
  37492. * @augments NodeParser
  37493. */
  37494. class GLSLNodeParser extends NodeParser {
  37495. /**
  37496. * The method parses the given GLSL code an returns a node function.
  37497. *
  37498. * @param {string} source - The GLSL code.
  37499. * @return {GLSLNodeFunction} A node function.
  37500. */
  37501. parseFunction( source ) {
  37502. return new GLSLNodeFunction( source );
  37503. }
  37504. }
  37505. const _outputNodeMap = new WeakMap();
  37506. const _chainKeys$2 = [];
  37507. const _cacheKeyValues = [];
  37508. /**
  37509. * This renderer module manages node-related objects and is the
  37510. * primary interface between the renderer and the node system.
  37511. *
  37512. * @private
  37513. * @augments DataMap
  37514. */
  37515. class Nodes extends DataMap {
  37516. /**
  37517. * Constructs a new nodes management component.
  37518. *
  37519. * @param {Renderer} renderer - The renderer.
  37520. * @param {Backend} backend - The renderer's backend.
  37521. */
  37522. constructor( renderer, backend ) {
  37523. super();
  37524. /**
  37525. * The renderer.
  37526. *
  37527. * @type {Renderer}
  37528. */
  37529. this.renderer = renderer;
  37530. /**
  37531. * The renderer's backend.
  37532. *
  37533. * @type {Backend}
  37534. */
  37535. this.backend = backend;
  37536. /**
  37537. * The node frame.
  37538. *
  37539. * @type {Renderer}
  37540. */
  37541. this.nodeFrame = new NodeFrame();
  37542. /**
  37543. * A cache for managing node builder states.
  37544. *
  37545. * @type {Map<number,NodeBuilderState>}
  37546. */
  37547. this.nodeBuilderCache = new Map();
  37548. /**
  37549. * A cache for managing data cache key data.
  37550. *
  37551. * @type {ChainMap}
  37552. */
  37553. this.callHashCache = new ChainMap();
  37554. /**
  37555. * A cache for managing node uniforms group data.
  37556. *
  37557. * @type {ChainMap}
  37558. */
  37559. this.groupsData = new ChainMap();
  37560. /**
  37561. * A cache for managing node objects of
  37562. * scene properties like fog or environments.
  37563. *
  37564. * @type {Object<string,WeakMap>}
  37565. */
  37566. this.cacheLib = {};
  37567. }
  37568. /**
  37569. * Returns `true` if the given node uniforms group must be updated or not.
  37570. *
  37571. * @param {NodeUniformsGroup} nodeUniformsGroup - The node uniforms group.
  37572. * @return {boolean} Whether the node uniforms group requires an update or not.
  37573. */
  37574. updateGroup( nodeUniformsGroup ) {
  37575. const groupNode = nodeUniformsGroup.groupNode;
  37576. const name = groupNode.name;
  37577. // objectGroup is always updated
  37578. if ( name === objectGroup.name ) return true;
  37579. // renderGroup is updated once per render/compute call
  37580. if ( name === renderGroup.name ) {
  37581. const uniformsGroupData = this.get( nodeUniformsGroup );
  37582. const renderId = this.nodeFrame.renderId;
  37583. if ( uniformsGroupData.renderId !== renderId ) {
  37584. uniformsGroupData.renderId = renderId;
  37585. return true;
  37586. }
  37587. return false;
  37588. }
  37589. // frameGroup is updated once per frame
  37590. if ( name === frameGroup.name ) {
  37591. const uniformsGroupData = this.get( nodeUniformsGroup );
  37592. const frameId = this.nodeFrame.frameId;
  37593. if ( uniformsGroupData.frameId !== frameId ) {
  37594. uniformsGroupData.frameId = frameId;
  37595. return true;
  37596. }
  37597. return false;
  37598. }
  37599. // other groups are updated just when groupNode.needsUpdate is true
  37600. _chainKeys$2[ 0 ] = groupNode;
  37601. _chainKeys$2[ 1 ] = nodeUniformsGroup;
  37602. let groupData = this.groupsData.get( _chainKeys$2 );
  37603. if ( groupData === undefined ) this.groupsData.set( _chainKeys$2, groupData = {} );
  37604. _chainKeys$2.length = 0;
  37605. if ( groupData.version !== groupNode.version ) {
  37606. groupData.version = groupNode.version;
  37607. return true;
  37608. }
  37609. return false;
  37610. }
  37611. /**
  37612. * Returns the cache key for the given render object.
  37613. *
  37614. * @param {RenderObject} renderObject - The render object.
  37615. * @return {number} The cache key.
  37616. */
  37617. getForRenderCacheKey( renderObject ) {
  37618. return renderObject.initialCacheKey;
  37619. }
  37620. /**
  37621. * Returns a node builder state for the given render object.
  37622. *
  37623. * @param {RenderObject} renderObject - The render object.
  37624. * @return {NodeBuilderState} The node builder state.
  37625. */
  37626. getForRender( renderObject ) {
  37627. const renderObjectData = this.get( renderObject );
  37628. let nodeBuilderState = renderObjectData.nodeBuilderState;
  37629. if ( nodeBuilderState === undefined ) {
  37630. const { nodeBuilderCache } = this;
  37631. const cacheKey = this.getForRenderCacheKey( renderObject );
  37632. nodeBuilderState = nodeBuilderCache.get( cacheKey );
  37633. if ( nodeBuilderState === undefined ) {
  37634. const createNodeBuilder = ( material ) => {
  37635. const nodeBuilder = this.backend.createNodeBuilder( renderObject.object, this.renderer );
  37636. nodeBuilder.scene = renderObject.scene;
  37637. nodeBuilder.material = material;
  37638. nodeBuilder.camera = renderObject.camera;
  37639. nodeBuilder.context.material = material;
  37640. nodeBuilder.lightsNode = renderObject.lightsNode;
  37641. nodeBuilder.environmentNode = this.getEnvironmentNode( renderObject.scene );
  37642. nodeBuilder.fogNode = this.getFogNode( renderObject.scene );
  37643. nodeBuilder.clippingContext = renderObject.clippingContext;
  37644. if ( this.renderer.getOutputRenderTarget() ? this.renderer.getOutputRenderTarget().multiview : false ) {
  37645. nodeBuilder.enableMultiview();
  37646. }
  37647. return nodeBuilder;
  37648. };
  37649. let nodeBuilder = createNodeBuilder( renderObject.material );
  37650. try {
  37651. nodeBuilder.build();
  37652. } catch ( e ) {
  37653. nodeBuilder = createNodeBuilder( new NodeMaterial() );
  37654. nodeBuilder.build();
  37655. error( 'TSL: ' + e );
  37656. }
  37657. nodeBuilderState = this._createNodeBuilderState( nodeBuilder );
  37658. nodeBuilderCache.set( cacheKey, nodeBuilderState );
  37659. }
  37660. nodeBuilderState.usedTimes ++;
  37661. renderObjectData.nodeBuilderState = nodeBuilderState;
  37662. }
  37663. return nodeBuilderState;
  37664. }
  37665. /**
  37666. * Deletes the given object from the internal data map
  37667. *
  37668. * @param {any} object - The object to delete.
  37669. * @return {?Object} The deleted dictionary.
  37670. */
  37671. delete( object ) {
  37672. if ( object.isRenderObject ) {
  37673. const nodeBuilderState = this.get( object ).nodeBuilderState;
  37674. nodeBuilderState.usedTimes --;
  37675. if ( nodeBuilderState.usedTimes === 0 ) {
  37676. this.nodeBuilderCache.delete( this.getForRenderCacheKey( object ) );
  37677. }
  37678. }
  37679. return super.delete( object );
  37680. }
  37681. /**
  37682. * Returns a node builder state for the given compute node.
  37683. *
  37684. * @param {Node} computeNode - The compute node.
  37685. * @return {NodeBuilderState} The node builder state.
  37686. */
  37687. getForCompute( computeNode ) {
  37688. const computeData = this.get( computeNode );
  37689. let nodeBuilderState = computeData.nodeBuilderState;
  37690. if ( nodeBuilderState === undefined ) {
  37691. const nodeBuilder = this.backend.createNodeBuilder( computeNode, this.renderer );
  37692. nodeBuilder.build();
  37693. nodeBuilderState = this._createNodeBuilderState( nodeBuilder );
  37694. computeData.nodeBuilderState = nodeBuilderState;
  37695. }
  37696. return nodeBuilderState;
  37697. }
  37698. /**
  37699. * Creates a node builder state for the given node builder.
  37700. *
  37701. * @private
  37702. * @param {NodeBuilder} nodeBuilder - The node builder.
  37703. * @return {NodeBuilderState} The node builder state.
  37704. */
  37705. _createNodeBuilderState( nodeBuilder ) {
  37706. return new NodeBuilderState(
  37707. nodeBuilder.vertexShader,
  37708. nodeBuilder.fragmentShader,
  37709. nodeBuilder.computeShader,
  37710. nodeBuilder.getAttributesArray(),
  37711. nodeBuilder.getBindings(),
  37712. nodeBuilder.updateNodes,
  37713. nodeBuilder.updateBeforeNodes,
  37714. nodeBuilder.updateAfterNodes,
  37715. nodeBuilder.observer,
  37716. nodeBuilder.transforms
  37717. );
  37718. }
  37719. /**
  37720. * Returns an environment node for the current configured
  37721. * scene environment.
  37722. *
  37723. * @param {Scene} scene - The scene.
  37724. * @return {Node} A node representing the current scene environment.
  37725. */
  37726. getEnvironmentNode( scene ) {
  37727. this.updateEnvironment( scene );
  37728. let environmentNode = null;
  37729. if ( scene.environmentNode && scene.environmentNode.isNode ) {
  37730. environmentNode = scene.environmentNode;
  37731. } else {
  37732. const sceneData = this.get( scene );
  37733. if ( sceneData.environmentNode ) {
  37734. environmentNode = sceneData.environmentNode;
  37735. }
  37736. }
  37737. return environmentNode;
  37738. }
  37739. /**
  37740. * Returns a background node for the current configured
  37741. * scene background.
  37742. *
  37743. * @param {Scene} scene - The scene.
  37744. * @return {Node} A node representing the current scene background.
  37745. */
  37746. getBackgroundNode( scene ) {
  37747. this.updateBackground( scene );
  37748. let backgroundNode = null;
  37749. if ( scene.backgroundNode && scene.backgroundNode.isNode ) {
  37750. backgroundNode = scene.backgroundNode;
  37751. } else {
  37752. const sceneData = this.get( scene );
  37753. if ( sceneData.backgroundNode ) {
  37754. backgroundNode = sceneData.backgroundNode;
  37755. }
  37756. }
  37757. return backgroundNode;
  37758. }
  37759. /**
  37760. * Returns a fog node for the current configured scene fog.
  37761. *
  37762. * @param {Scene} scene - The scene.
  37763. * @return {Node} A node representing the current scene fog.
  37764. */
  37765. getFogNode( scene ) {
  37766. this.updateFog( scene );
  37767. return scene.fogNode || this.get( scene ).fogNode || null;
  37768. }
  37769. /**
  37770. * Returns a cache key for the given scene and lights node.
  37771. * This key is used by `RenderObject` as a part of the dynamic
  37772. * cache key (a key that must be checked every time the render
  37773. * objects is drawn).
  37774. *
  37775. * @param {Scene} scene - The scene.
  37776. * @param {LightsNode} lightsNode - The lights node.
  37777. * @return {number} The cache key.
  37778. */
  37779. getCacheKey( scene, lightsNode ) {
  37780. _chainKeys$2[ 0 ] = scene;
  37781. _chainKeys$2[ 1 ] = lightsNode;
  37782. const callId = this.renderer.info.calls;
  37783. const cacheKeyData = this.callHashCache.get( _chainKeys$2 ) || {};
  37784. if ( cacheKeyData.callId !== callId ) {
  37785. const environmentNode = this.getEnvironmentNode( scene );
  37786. const fogNode = this.getFogNode( scene );
  37787. if ( lightsNode ) _cacheKeyValues.push( lightsNode.getCacheKey( true ) );
  37788. if ( environmentNode ) _cacheKeyValues.push( environmentNode.getCacheKey() );
  37789. if ( fogNode ) _cacheKeyValues.push( fogNode.getCacheKey() );
  37790. _cacheKeyValues.push( this.renderer.getOutputRenderTarget() && this.renderer.getOutputRenderTarget().multiview ? 1 : 0 );
  37791. _cacheKeyValues.push( this.renderer.shadowMap.enabled ? 1 : 0 );
  37792. _cacheKeyValues.push( this.renderer.shadowMap.type );
  37793. cacheKeyData.callId = callId;
  37794. cacheKeyData.cacheKey = hashArray( _cacheKeyValues );
  37795. this.callHashCache.set( _chainKeys$2, cacheKeyData );
  37796. _cacheKeyValues.length = 0;
  37797. }
  37798. _chainKeys$2.length = 0;
  37799. return cacheKeyData.cacheKey;
  37800. }
  37801. /**
  37802. * A boolean that indicates whether tone mapping should be enabled
  37803. * or not.
  37804. *
  37805. * @type {boolean}
  37806. */
  37807. get isToneMappingState() {
  37808. return this.renderer.getRenderTarget() ? false : true;
  37809. }
  37810. /**
  37811. * If a scene background is configured, this method makes sure to
  37812. * represent the background with a corresponding node-based implementation.
  37813. *
  37814. * @param {Scene} scene - The scene.
  37815. */
  37816. updateBackground( scene ) {
  37817. const sceneData = this.get( scene );
  37818. const background = scene.background;
  37819. if ( background ) {
  37820. const forceUpdate = ( scene.backgroundBlurriness === 0 && sceneData.backgroundBlurriness > 0 ) || ( scene.backgroundBlurriness > 0 && sceneData.backgroundBlurriness === 0 );
  37821. if ( sceneData.background !== background || forceUpdate ) {
  37822. const backgroundNode = this.getCacheNode( 'background', background, () => {
  37823. if ( background.isCubeTexture === true || ( background.mapping === EquirectangularReflectionMapping || background.mapping === EquirectangularRefractionMapping || background.mapping === CubeUVReflectionMapping ) ) {
  37824. if ( scene.backgroundBlurriness > 0 || background.mapping === CubeUVReflectionMapping ) {
  37825. return pmremTexture( background );
  37826. } else {
  37827. let envMap;
  37828. if ( background.isCubeTexture === true ) {
  37829. envMap = cubeTexture( background );
  37830. } else {
  37831. envMap = texture( background );
  37832. }
  37833. return cubeMapNode( envMap );
  37834. }
  37835. } else if ( background.isTexture === true ) {
  37836. return texture( background, screenUV.flipY() ).setUpdateMatrix( true );
  37837. } else if ( background.isColor !== true ) {
  37838. error( 'WebGPUNodes: Unsupported background configuration.', background );
  37839. }
  37840. }, forceUpdate );
  37841. sceneData.backgroundNode = backgroundNode;
  37842. sceneData.background = background;
  37843. sceneData.backgroundBlurriness = scene.backgroundBlurriness;
  37844. }
  37845. } else if ( sceneData.backgroundNode ) {
  37846. delete sceneData.backgroundNode;
  37847. delete sceneData.background;
  37848. }
  37849. }
  37850. /**
  37851. * This method is part of the caching of nodes which are used to represents the
  37852. * scene's background, fog or environment.
  37853. *
  37854. * @param {string} type - The type of object to cache.
  37855. * @param {Object} object - The object.
  37856. * @param {Function} callback - A callback that produces a node representation for the given object.
  37857. * @param {boolean} [forceUpdate=false] - Whether an update should be enforced or not.
  37858. * @return {Node} The node representation.
  37859. */
  37860. getCacheNode( type, object, callback, forceUpdate = false ) {
  37861. const nodeCache = this.cacheLib[ type ] || ( this.cacheLib[ type ] = new WeakMap() );
  37862. let node = nodeCache.get( object );
  37863. if ( node === undefined || forceUpdate ) {
  37864. node = callback();
  37865. nodeCache.set( object, node );
  37866. }
  37867. return node;
  37868. }
  37869. /**
  37870. * If a scene fog is configured, this method makes sure to
  37871. * represent the fog with a corresponding node-based implementation.
  37872. *
  37873. * @param {Scene} scene - The scene.
  37874. */
  37875. updateFog( scene ) {
  37876. const sceneData = this.get( scene );
  37877. const sceneFog = scene.fog;
  37878. if ( sceneFog ) {
  37879. if ( sceneData.fog !== sceneFog ) {
  37880. const fogNode = this.getCacheNode( 'fog', sceneFog, () => {
  37881. if ( sceneFog.isFogExp2 ) {
  37882. const color = reference( 'color', 'color', sceneFog ).setGroup( renderGroup );
  37883. const density = reference( 'density', 'float', sceneFog ).setGroup( renderGroup );
  37884. return fog( color, densityFogFactor( density ) );
  37885. } else if ( sceneFog.isFog ) {
  37886. const color = reference( 'color', 'color', sceneFog ).setGroup( renderGroup );
  37887. const near = reference( 'near', 'float', sceneFog ).setGroup( renderGroup );
  37888. const far = reference( 'far', 'float', sceneFog ).setGroup( renderGroup );
  37889. return fog( color, rangeFogFactor( near, far ) );
  37890. } else {
  37891. error( 'Renderer: Unsupported fog configuration.', sceneFog );
  37892. }
  37893. } );
  37894. sceneData.fogNode = fogNode;
  37895. sceneData.fog = sceneFog;
  37896. }
  37897. } else {
  37898. delete sceneData.fogNode;
  37899. delete sceneData.fog;
  37900. }
  37901. }
  37902. /**
  37903. * If a scene environment is configured, this method makes sure to
  37904. * represent the environment with a corresponding node-based implementation.
  37905. *
  37906. * @param {Scene} scene - The scene.
  37907. */
  37908. updateEnvironment( scene ) {
  37909. const sceneData = this.get( scene );
  37910. const environment = scene.environment;
  37911. if ( environment ) {
  37912. if ( sceneData.environment !== environment ) {
  37913. const environmentNode = this.getCacheNode( 'environment', environment, () => {
  37914. if ( environment.isCubeTexture === true ) {
  37915. return cubeTexture( environment );
  37916. } else if ( environment.isTexture === true ) {
  37917. return texture( environment );
  37918. } else {
  37919. error( 'Nodes: Unsupported environment configuration.', environment );
  37920. }
  37921. } );
  37922. sceneData.environmentNode = environmentNode;
  37923. sceneData.environment = environment;
  37924. }
  37925. } else if ( sceneData.environmentNode ) {
  37926. delete sceneData.environmentNode;
  37927. delete sceneData.environment;
  37928. }
  37929. }
  37930. getNodeFrame( renderer = this.renderer, scene = null, object = null, camera = null, material = null ) {
  37931. const nodeFrame = this.nodeFrame;
  37932. nodeFrame.renderer = renderer;
  37933. nodeFrame.scene = scene;
  37934. nodeFrame.object = object;
  37935. nodeFrame.camera = camera;
  37936. nodeFrame.material = material;
  37937. return nodeFrame;
  37938. }
  37939. getNodeFrameForRender( renderObject ) {
  37940. return this.getNodeFrame( renderObject.renderer, renderObject.scene, renderObject.object, renderObject.camera, renderObject.material );
  37941. }
  37942. /**
  37943. * Returns the current output cache key.
  37944. *
  37945. * @return {string} The output cache key.
  37946. */
  37947. getOutputCacheKey() {
  37948. const renderer = this.renderer;
  37949. return renderer.toneMapping + ',' + renderer.currentColorSpace + ',' + renderer.xr.isPresenting;
  37950. }
  37951. /**
  37952. * Checks if the output configuration (tone mapping and color space) for
  37953. * the given target has changed.
  37954. *
  37955. * @param {Texture} outputTarget - The output target.
  37956. * @return {boolean} Whether the output configuration has changed or not.
  37957. */
  37958. hasOutputChange( outputTarget ) {
  37959. const cacheKey = _outputNodeMap.get( outputTarget );
  37960. return cacheKey !== this.getOutputCacheKey();
  37961. }
  37962. /**
  37963. * Returns a node that represents the output configuration (tone mapping and
  37964. * color space) for the current target.
  37965. *
  37966. * @param {Texture} outputTarget - The output target.
  37967. * @return {Node} The output node.
  37968. */
  37969. getOutputNode( outputTarget ) {
  37970. const renderer = this.renderer;
  37971. const cacheKey = this.getOutputCacheKey();
  37972. const output = outputTarget.isArrayTexture ?
  37973. texture3D( outputTarget, vec3( screenUV, builtin( 'gl_ViewID_OVR' ) ) ).renderOutput( renderer.toneMapping, renderer.currentColorSpace ) :
  37974. texture( outputTarget, screenUV ).renderOutput( renderer.toneMapping, renderer.currentColorSpace );
  37975. _outputNodeMap.set( outputTarget, cacheKey );
  37976. return output;
  37977. }
  37978. /**
  37979. * Triggers the call of `updateBefore()` methods
  37980. * for all nodes of the given render object.
  37981. *
  37982. * @param {RenderObject} renderObject - The render object.
  37983. */
  37984. updateBefore( renderObject ) {
  37985. const nodeBuilder = renderObject.getNodeBuilderState();
  37986. for ( const node of nodeBuilder.updateBeforeNodes ) {
  37987. // update frame state for each node
  37988. this.getNodeFrameForRender( renderObject ).updateBeforeNode( node );
  37989. }
  37990. }
  37991. /**
  37992. * Triggers the call of `updateAfter()` methods
  37993. * for all nodes of the given render object.
  37994. *
  37995. * @param {RenderObject} renderObject - The render object.
  37996. */
  37997. updateAfter( renderObject ) {
  37998. const nodeBuilder = renderObject.getNodeBuilderState();
  37999. for ( const node of nodeBuilder.updateAfterNodes ) {
  38000. // update frame state for each node
  38001. this.getNodeFrameForRender( renderObject ).updateAfterNode( node );
  38002. }
  38003. }
  38004. /**
  38005. * Triggers the call of `update()` methods
  38006. * for all nodes of the given compute node.
  38007. *
  38008. * @param {Node} computeNode - The compute node.
  38009. */
  38010. updateForCompute( computeNode ) {
  38011. const nodeFrame = this.getNodeFrame();
  38012. const nodeBuilder = this.getForCompute( computeNode );
  38013. for ( const node of nodeBuilder.updateNodes ) {
  38014. nodeFrame.updateNode( node );
  38015. }
  38016. }
  38017. /**
  38018. * Triggers the call of `update()` methods
  38019. * for all nodes of the given compute node.
  38020. *
  38021. * @param {RenderObject} renderObject - The render object.
  38022. */
  38023. updateForRender( renderObject ) {
  38024. const nodeFrame = this.getNodeFrameForRender( renderObject );
  38025. const nodeBuilder = renderObject.getNodeBuilderState();
  38026. for ( const node of nodeBuilder.updateNodes ) {
  38027. nodeFrame.updateNode( node );
  38028. }
  38029. }
  38030. /**
  38031. * Returns `true` if the given render object requires a refresh.
  38032. *
  38033. * @param {RenderObject} renderObject - The render object.
  38034. * @return {boolean} Whether the given render object requires a refresh or not.
  38035. */
  38036. needsRefresh( renderObject ) {
  38037. const nodeFrame = this.getNodeFrameForRender( renderObject );
  38038. const monitor = renderObject.getMonitor();
  38039. return monitor.needsRefresh( renderObject, nodeFrame );
  38040. }
  38041. /**
  38042. * Frees the internal resources.
  38043. */
  38044. dispose() {
  38045. super.dispose();
  38046. this.nodeFrame = new NodeFrame();
  38047. this.nodeBuilderCache = new Map();
  38048. this.cacheLib = {};
  38049. }
  38050. }
  38051. const _plane = /*@__PURE__*/ new Plane();
  38052. /**
  38053. * Represents the state that is used to perform clipping via clipping planes.
  38054. * There is a default clipping context for each render context. When the
  38055. * scene holds instances of `ClippingGroup`, there will be a context for each
  38056. * group.
  38057. *
  38058. * @private
  38059. */
  38060. class ClippingContext {
  38061. /**
  38062. * Constructs a new clipping context.
  38063. *
  38064. * @param {?ClippingContext} [parentContext=null] - A reference to the parent clipping context.
  38065. */
  38066. constructor( parentContext = null ) {
  38067. /**
  38068. * The clipping context's version.
  38069. *
  38070. * @type {number}
  38071. * @readonly
  38072. */
  38073. this.version = 0;
  38074. /**
  38075. * Whether the intersection of the clipping planes is used to clip objects, rather than their union.
  38076. *
  38077. * @type {?boolean}
  38078. * @default null
  38079. */
  38080. this.clipIntersection = null;
  38081. /**
  38082. * The clipping context's cache key.
  38083. *
  38084. * @type {string}
  38085. */
  38086. this.cacheKey = '';
  38087. /**
  38088. * Whether the shadow pass is active or not.
  38089. *
  38090. * @type {boolean}
  38091. * @default false
  38092. */
  38093. this.shadowPass = false;
  38094. /**
  38095. * The view normal matrix.
  38096. *
  38097. * @type {Matrix3}
  38098. */
  38099. this.viewNormalMatrix = new Matrix3();
  38100. /**
  38101. * Internal cache for maintaining clipping contexts.
  38102. *
  38103. * @type {WeakMap<ClippingGroup,ClippingContext>}
  38104. */
  38105. this.clippingGroupContexts = new WeakMap();
  38106. /**
  38107. * The intersection planes.
  38108. *
  38109. * @type {Array<Vector4>}
  38110. */
  38111. this.intersectionPlanes = [];
  38112. /**
  38113. * The intersection planes.
  38114. *
  38115. * @type {Array<Vector4>}
  38116. */
  38117. this.unionPlanes = [];
  38118. /**
  38119. * The version of the clipping context's parent context.
  38120. *
  38121. * @type {?number}
  38122. * @readonly
  38123. */
  38124. this.parentVersion = null;
  38125. if ( parentContext !== null ) {
  38126. this.viewNormalMatrix = parentContext.viewNormalMatrix;
  38127. this.clippingGroupContexts = parentContext.clippingGroupContexts;
  38128. this.shadowPass = parentContext.shadowPass;
  38129. this.viewMatrix = parentContext.viewMatrix;
  38130. }
  38131. }
  38132. /**
  38133. * Projects the given source clipping planes and writes the result into the
  38134. * destination array.
  38135. *
  38136. * @param {Array<Plane>} source - The source clipping planes.
  38137. * @param {Array<Vector4>} destination - The destination.
  38138. * @param {number} offset - The offset.
  38139. */
  38140. projectPlanes( source, destination, offset ) {
  38141. const l = source.length;
  38142. for ( let i = 0; i < l; i ++ ) {
  38143. _plane.copy( source[ i ] ).applyMatrix4( this.viewMatrix, this.viewNormalMatrix );
  38144. const v = destination[ offset + i ];
  38145. const normal = _plane.normal;
  38146. v.x = - normal.x;
  38147. v.y = - normal.y;
  38148. v.z = - normal.z;
  38149. v.w = _plane.constant;
  38150. }
  38151. }
  38152. /**
  38153. * Updates the root clipping context of a scene.
  38154. *
  38155. * @param {Scene} scene - The scene.
  38156. * @param {Camera} camera - The camera that is used to render the scene.
  38157. */
  38158. updateGlobal( scene, camera ) {
  38159. this.shadowPass = ( scene.overrideMaterial !== null && scene.overrideMaterial.isShadowPassMaterial );
  38160. this.viewMatrix = camera.matrixWorldInverse;
  38161. this.viewNormalMatrix.getNormalMatrix( this.viewMatrix );
  38162. }
  38163. /**
  38164. * Updates the clipping context.
  38165. *
  38166. * @param {ClippingContext} parentContext - The parent context.
  38167. * @param {ClippingGroup} clippingGroup - The clipping group this context belongs to.
  38168. */
  38169. update( parentContext, clippingGroup ) {
  38170. let update = false;
  38171. if ( parentContext.version !== this.parentVersion ) {
  38172. this.intersectionPlanes = Array.from( parentContext.intersectionPlanes );
  38173. this.unionPlanes = Array.from( parentContext.unionPlanes );
  38174. this.parentVersion = parentContext.version;
  38175. }
  38176. if ( this.clipIntersection !== clippingGroup.clipIntersection ) {
  38177. this.clipIntersection = clippingGroup.clipIntersection;
  38178. if ( this.clipIntersection ) {
  38179. this.unionPlanes.length = parentContext.unionPlanes.length;
  38180. } else {
  38181. this.intersectionPlanes.length = parentContext.intersectionPlanes.length;
  38182. }
  38183. }
  38184. const srcClippingPlanes = clippingGroup.clippingPlanes;
  38185. const l = srcClippingPlanes.length;
  38186. let dstClippingPlanes;
  38187. let offset;
  38188. if ( this.clipIntersection ) {
  38189. dstClippingPlanes = this.intersectionPlanes;
  38190. offset = parentContext.intersectionPlanes.length;
  38191. } else {
  38192. dstClippingPlanes = this.unionPlanes;
  38193. offset = parentContext.unionPlanes.length;
  38194. }
  38195. if ( dstClippingPlanes.length !== offset + l ) {
  38196. dstClippingPlanes.length = offset + l;
  38197. for ( let i = 0; i < l; i ++ ) {
  38198. dstClippingPlanes[ offset + i ] = new Vector4();
  38199. }
  38200. update = true;
  38201. }
  38202. this.projectPlanes( srcClippingPlanes, dstClippingPlanes, offset );
  38203. if ( update ) {
  38204. this.version ++;
  38205. this.cacheKey = `${ this.intersectionPlanes.length }:${ this.unionPlanes.length }`;
  38206. }
  38207. }
  38208. /**
  38209. * Returns a clipping context for the given clipping group.
  38210. *
  38211. * @param {ClippingGroup} clippingGroup - The clipping group.
  38212. * @return {ClippingContext} The clipping context.
  38213. */
  38214. getGroupContext( clippingGroup ) {
  38215. if ( this.shadowPass && ! clippingGroup.clipShadows ) return this;
  38216. let context = this.clippingGroupContexts.get( clippingGroup );
  38217. if ( context === undefined ) {
  38218. context = new ClippingContext( this );
  38219. this.clippingGroupContexts.set( clippingGroup, context );
  38220. }
  38221. context.update( this, clippingGroup );
  38222. return context;
  38223. }
  38224. /**
  38225. * The count of union clipping planes.
  38226. *
  38227. * @type {number}
  38228. * @readonly
  38229. */
  38230. get unionClippingCount() {
  38231. return this.unionPlanes.length;
  38232. }
  38233. }
  38234. /**
  38235. * This module is used to represent render bundles inside the renderer
  38236. * for further processing.
  38237. *
  38238. * @private
  38239. */
  38240. class RenderBundle {
  38241. /**
  38242. * Constructs a new bundle group.
  38243. *
  38244. * @param {BundleGroup} bundleGroup - The bundle group.
  38245. * @param {Camera} camera - The camera the bundle group is rendered with.
  38246. */
  38247. constructor( bundleGroup, camera ) {
  38248. this.bundleGroup = bundleGroup;
  38249. this.camera = camera;
  38250. }
  38251. }
  38252. const _chainKeys$1 = [];
  38253. /**
  38254. * This renderer module manages render bundles.
  38255. *
  38256. * @private
  38257. */
  38258. class RenderBundles {
  38259. /**
  38260. * Constructs a new render bundle management component.
  38261. */
  38262. constructor() {
  38263. /**
  38264. * A chain map for maintaining the render bundles.
  38265. *
  38266. * @type {ChainMap}
  38267. */
  38268. this.bundles = new ChainMap();
  38269. }
  38270. /**
  38271. * Returns a render bundle for the given bundle group and camera.
  38272. *
  38273. * @param {BundleGroup} bundleGroup - The bundle group.
  38274. * @param {Camera} camera - The camera the bundle group is rendered with.
  38275. * @return {RenderBundle} The render bundle.
  38276. */
  38277. get( bundleGroup, camera ) {
  38278. const bundles = this.bundles;
  38279. _chainKeys$1[ 0 ] = bundleGroup;
  38280. _chainKeys$1[ 1 ] = camera;
  38281. let bundle = bundles.get( _chainKeys$1 );
  38282. if ( bundle === undefined ) {
  38283. bundle = new RenderBundle( bundleGroup, camera );
  38284. bundles.set( _chainKeys$1, bundle );
  38285. }
  38286. _chainKeys$1.length = 0;
  38287. return bundle;
  38288. }
  38289. /**
  38290. * Frees all internal resources.
  38291. */
  38292. dispose() {
  38293. this.bundles = new ChainMap();
  38294. }
  38295. }
  38296. /**
  38297. * The purpose of a node library is to assign node implementations
  38298. * to existing library features. In `WebGPURenderer` lights, materials
  38299. * which are not based on `NodeMaterial` as well as tone mapping techniques
  38300. * are implemented with node-based modules.
  38301. *
  38302. * @private
  38303. */
  38304. class NodeLibrary {
  38305. /**
  38306. * Constructs a new node library.
  38307. */
  38308. constructor() {
  38309. /**
  38310. * A weak map that maps lights to light nodes.
  38311. *
  38312. * @type {WeakMap<Light.constructor,AnalyticLightNode.constructor>}
  38313. */
  38314. this.lightNodes = new WeakMap();
  38315. /**
  38316. * A map that maps materials to node materials.
  38317. *
  38318. * @type {Map<string,NodeMaterial.constructor>}
  38319. */
  38320. this.materialNodes = new Map();
  38321. /**
  38322. * A map that maps tone mapping techniques (constants)
  38323. * to tone mapping node functions.
  38324. *
  38325. * @type {Map<number,Function>}
  38326. */
  38327. this.toneMappingNodes = new Map();
  38328. }
  38329. /**
  38330. * Returns a matching node material instance for the given material object.
  38331. *
  38332. * This method also assigns/copies the properties of the given material object
  38333. * to the node material. This is done to make sure the current material
  38334. * configuration carries over to the node version.
  38335. *
  38336. * @param {Material} material - A material.
  38337. * @return {NodeMaterial} The corresponding node material.
  38338. */
  38339. fromMaterial( material ) {
  38340. if ( material.isNodeMaterial ) return material;
  38341. let nodeMaterial = null;
  38342. const nodeMaterialClass = this.getMaterialNodeClass( material.type );
  38343. if ( nodeMaterialClass !== null ) {
  38344. nodeMaterial = new nodeMaterialClass();
  38345. for ( const key in material ) {
  38346. nodeMaterial[ key ] = material[ key ];
  38347. }
  38348. }
  38349. return nodeMaterial;
  38350. }
  38351. /**
  38352. * Adds a tone mapping node function for a tone mapping technique (constant).
  38353. *
  38354. * @param {Function} toneMappingNode - The tone mapping node function.
  38355. * @param {number} toneMapping - The tone mapping.
  38356. */
  38357. addToneMapping( toneMappingNode, toneMapping ) {
  38358. this.addType( toneMappingNode, toneMapping, this.toneMappingNodes );
  38359. }
  38360. /**
  38361. * Returns a tone mapping node function for a tone mapping technique (constant).
  38362. *
  38363. * @param {number} toneMapping - The tone mapping.
  38364. * @return {?Function} The tone mapping node function. Returns `null` if no node function is found.
  38365. */
  38366. getToneMappingFunction( toneMapping ) {
  38367. return this.toneMappingNodes.get( toneMapping ) || null;
  38368. }
  38369. /**
  38370. * Returns a node material class definition for a material type.
  38371. *
  38372. * @param {string} materialType - The material type.
  38373. * @return {?NodeMaterial.constructor} The node material class definition. Returns `null` if no node material is found.
  38374. */
  38375. getMaterialNodeClass( materialType ) {
  38376. return this.materialNodes.get( materialType ) || null;
  38377. }
  38378. /**
  38379. * Adds a node material class definition for a given material type.
  38380. *
  38381. * @param {NodeMaterial.constructor} materialNodeClass - The node material class definition.
  38382. * @param {string} materialClassType - The material type.
  38383. */
  38384. addMaterial( materialNodeClass, materialClassType ) {
  38385. this.addType( materialNodeClass, materialClassType, this.materialNodes );
  38386. }
  38387. /**
  38388. * Returns a light node class definition for a light class definition.
  38389. *
  38390. * @param {Light.constructor} light - The light class definition.
  38391. * @return {?AnalyticLightNode.constructor} The light node class definition. Returns `null` if no light node is found.
  38392. */
  38393. getLightNodeClass( light ) {
  38394. return this.lightNodes.get( light ) || null;
  38395. }
  38396. /**
  38397. * Adds a light node class definition for a given light class definition.
  38398. *
  38399. * @param {AnalyticLightNode.constructor} lightNodeClass - The light node class definition.
  38400. * @param {Light.constructor} lightClass - The light class definition.
  38401. */
  38402. addLight( lightNodeClass, lightClass ) {
  38403. this.addClass( lightNodeClass, lightClass, this.lightNodes );
  38404. }
  38405. /**
  38406. * Adds a node class definition for the given type to the provided type library.
  38407. *
  38408. * @param {Node.constructor} nodeClass - The node class definition.
  38409. * @param {number|string} type - The object type.
  38410. * @param {Map<number|string,Node.constructor>} library - The type library.
  38411. */
  38412. addType( nodeClass, type, library ) {
  38413. if ( library.has( type ) ) {
  38414. warn( `Redefinition of node ${ type }` );
  38415. return;
  38416. }
  38417. if ( typeof nodeClass !== 'function' ) throw new Error( `Node class ${ nodeClass.name } is not a class.` );
  38418. if ( typeof type === 'function' || typeof type === 'object' ) throw new Error( `Base class ${ type } is not a class.` );
  38419. library.set( type, nodeClass );
  38420. }
  38421. /**
  38422. * Adds a node class definition for the given class definition to the provided type library.
  38423. *
  38424. * @param {Node.constructor} nodeClass - The node class definition.
  38425. * @param {Node.constructor} baseClass - The class definition.
  38426. * @param {WeakMap<Node.constructor, Node.constructor>} library - The type library.
  38427. */
  38428. addClass( nodeClass, baseClass, library ) {
  38429. if ( library.has( baseClass ) ) {
  38430. warn( `Redefinition of node ${ baseClass.name }` );
  38431. return;
  38432. }
  38433. if ( typeof nodeClass !== 'function' ) throw new Error( `Node class ${ nodeClass.name } is not a class.` );
  38434. if ( typeof baseClass !== 'function' ) throw new Error( `Base class ${ baseClass.name } is not a class.` );
  38435. library.set( baseClass, nodeClass );
  38436. }
  38437. }
  38438. const _defaultLights = /*@__PURE__*/ new LightsNode();
  38439. const _chainKeys = [];
  38440. /**
  38441. * This renderer module manages the lights nodes which are unique
  38442. * per scene and camera combination.
  38443. *
  38444. * The lights node itself is later configured in the render list
  38445. * with the actual lights from the scene.
  38446. *
  38447. * @private
  38448. * @augments ChainMap
  38449. */
  38450. class Lighting extends ChainMap {
  38451. /**
  38452. * Constructs a lighting management component.
  38453. */
  38454. constructor() {
  38455. super();
  38456. }
  38457. /**
  38458. * Creates a new lights node for the given array of lights.
  38459. *
  38460. * @param {Array<Light>} lights - The render object.
  38461. * @return {LightsNode} The lights node.
  38462. */
  38463. createNode( lights = [] ) {
  38464. return new LightsNode().setLights( lights );
  38465. }
  38466. /**
  38467. * Returns a lights node for the given scene and camera.
  38468. *
  38469. * @param {Scene} scene - The scene.
  38470. * @param {Camera} camera - The camera.
  38471. * @return {LightsNode} The lights node.
  38472. */
  38473. getNode( scene, camera ) {
  38474. // ignore post-processing
  38475. if ( scene.isQuadMesh ) return _defaultLights;
  38476. _chainKeys[ 0 ] = scene;
  38477. _chainKeys[ 1 ] = camera;
  38478. let node = this.get( _chainKeys );
  38479. if ( node === undefined ) {
  38480. node = this.createNode();
  38481. this.set( _chainKeys, node );
  38482. }
  38483. _chainKeys.length = 0;
  38484. return node;
  38485. }
  38486. }
  38487. /**
  38488. * A special type of render target that is used when rendering
  38489. * with the WebXR Device API.
  38490. *
  38491. * @private
  38492. * @augments RenderTarget
  38493. */
  38494. class XRRenderTarget extends RenderTarget {
  38495. /**
  38496. * Constructs a new XR render target.
  38497. *
  38498. * @param {number} [width=1] - The width of the render target.
  38499. * @param {number} [height=1] - The height of the render target.
  38500. * @param {Object} [options={}] - The configuration options.
  38501. */
  38502. constructor( width = 1, height = 1, options = {} ) {
  38503. super( width, height, options );
  38504. /**
  38505. * This flag can be used for type testing.
  38506. *
  38507. * @type {boolean}
  38508. * @readonly
  38509. * @default true
  38510. */
  38511. this.isXRRenderTarget = true;
  38512. /**
  38513. * Whether the attachments of the render target
  38514. * are defined by external textures. This flag is
  38515. * set to `true` when using the WebXR Layers API.
  38516. *
  38517. * @private
  38518. * @type {boolean}
  38519. * @default false
  38520. */
  38521. this._hasExternalTextures = false;
  38522. /**
  38523. * Whether a depth buffer should automatically be allocated
  38524. * for this XR render target or not.
  38525. *
  38526. * Allocating a depth buffer is the default behavior of XR render
  38527. * targets. However, when using the WebXR Layers API, this flag
  38528. * must be set to `false` when the `ignoreDepthValues` property of
  38529. * the projection layers evaluates to `false`.
  38530. *
  38531. * Reference: {@link https://www.w3.org/TR/webxrlayers-1/#dom-xrprojectionlayer-ignoredepthvalues}.
  38532. *
  38533. * @private
  38534. * @type {boolean}
  38535. * @default true
  38536. */
  38537. this._autoAllocateDepthBuffer = true;
  38538. /**
  38539. * Whether this render target is associated with a XRWebGLLayer.
  38540. *
  38541. * A XRWebGLLayer points to an opaque framebuffer. Basically,
  38542. * this means that you don't have access to its bound color,
  38543. * stencil and depth buffers. We need to handle this framebuffer
  38544. * differently since its textures are always bound.
  38545. *
  38546. * @private
  38547. * @type {boolean}
  38548. * @default false
  38549. * */
  38550. this._isOpaqueFramebuffer = false;
  38551. }
  38552. copy( source ) {
  38553. super.copy( source );
  38554. this._hasExternalTextures = source._hasExternalTextures;
  38555. this._autoAllocateDepthBuffer = source._autoAllocateDepthBuffer;
  38556. this._isOpaqueFramebuffer = source._isOpaqueFramebuffer;
  38557. return this;
  38558. }
  38559. }
  38560. const _cameraLPos = /*@__PURE__*/ new Vector3();
  38561. const _cameraRPos = /*@__PURE__*/ new Vector3();
  38562. /**
  38563. * The XR manager is built on top of the WebXR Device API to
  38564. * manage XR sessions with `WebGPURenderer`.
  38565. *
  38566. * XR is currently only supported with a WebGL 2 backend.
  38567. *
  38568. * @augments EventDispatcher
  38569. */
  38570. class XRManager extends EventDispatcher {
  38571. /**
  38572. * Constructs a new XR manager.
  38573. *
  38574. * @param {Renderer} renderer - The renderer.
  38575. * @param {boolean} [multiview=false] - Enables multiview if the device supports it.
  38576. */
  38577. constructor( renderer, multiview = false ) {
  38578. super();
  38579. /**
  38580. * This flag globally enables XR rendering.
  38581. *
  38582. * @type {boolean}
  38583. * @default false
  38584. */
  38585. this.enabled = false;
  38586. /**
  38587. * Whether the XR device is currently presenting or not.
  38588. *
  38589. * @type {boolean}
  38590. * @default false
  38591. * @readonly
  38592. */
  38593. this.isPresenting = false;
  38594. /**
  38595. * Whether the XR camera should automatically be updated or not.
  38596. *
  38597. * @type {boolean}
  38598. * @default true
  38599. */
  38600. this.cameraAutoUpdate = true;
  38601. /**
  38602. * The renderer.
  38603. *
  38604. * @private
  38605. * @type {Renderer}
  38606. */
  38607. this._renderer = renderer;
  38608. // camera
  38609. /**
  38610. * Represents the camera for the left eye.
  38611. *
  38612. * @private
  38613. * @type {PerspectiveCamera}
  38614. */
  38615. this._cameraL = new PerspectiveCamera();
  38616. this._cameraL.viewport = new Vector4();
  38617. /**
  38618. * Represents the camera for the right eye.
  38619. *
  38620. * @private
  38621. * @type {PerspectiveCamera}
  38622. */
  38623. this._cameraR = new PerspectiveCamera();
  38624. this._cameraR.viewport = new Vector4();
  38625. /**
  38626. * A list of cameras used for rendering the XR views.
  38627. *
  38628. * @private
  38629. * @type {Array<Camera>}
  38630. */
  38631. this._cameras = [ this._cameraL, this._cameraR ];
  38632. /**
  38633. * The main XR camera.
  38634. *
  38635. * @private
  38636. * @type {ArrayCamera}
  38637. */
  38638. this._cameraXR = new ArrayCamera();
  38639. /**
  38640. * The current near value of the XR camera.
  38641. *
  38642. * @private
  38643. * @type {?number}
  38644. * @default null
  38645. */
  38646. this._currentDepthNear = null;
  38647. /**
  38648. * The current far value of the XR camera.
  38649. *
  38650. * @private
  38651. * @type {?number}
  38652. * @default null
  38653. */
  38654. this._currentDepthFar = null;
  38655. /**
  38656. * A list of WebXR controllers requested by the application.
  38657. *
  38658. * @private
  38659. * @type {Array<WebXRController>}
  38660. */
  38661. this._controllers = [];
  38662. /**
  38663. * A list of XR input source. Each input source belongs to
  38664. * an instance of WebXRController.
  38665. *
  38666. * @private
  38667. * @type {Array<XRInputSource?>}
  38668. */
  38669. this._controllerInputSources = [];
  38670. /**
  38671. * The XR render target that represents the rendering destination
  38672. * during an active XR session.
  38673. *
  38674. * @private
  38675. * @type {?RenderTarget}
  38676. * @default null
  38677. */
  38678. this._xrRenderTarget = null;
  38679. /**
  38680. * An array holding all the non-projection layers
  38681. *
  38682. * @private
  38683. * @type {Array<Object>}
  38684. * @default []
  38685. */
  38686. this._layers = [];
  38687. /**
  38688. * Whether the XR session uses layers.
  38689. *
  38690. * @private
  38691. * @type {boolean}
  38692. * @default false
  38693. */
  38694. this._sessionUsesLayers = false;
  38695. /**
  38696. * Whether the device supports binding gl objects.
  38697. *
  38698. * @private
  38699. * @type {boolean}
  38700. * @readonly
  38701. */
  38702. this._supportsGlBinding = typeof XRWebGLBinding !== 'undefined';
  38703. this._frameBufferTargets = null;
  38704. /**
  38705. * Helper function to create native WebXR Layer.
  38706. *
  38707. * @private
  38708. * @type {Function}
  38709. */
  38710. this._createXRLayer = createXRLayer.bind( this );
  38711. /**
  38712. * The current WebGL context.
  38713. *
  38714. * @private
  38715. * @type {?WebGL2RenderingContext}
  38716. * @default null
  38717. */
  38718. this._gl = null;
  38719. /**
  38720. * The current animation context.
  38721. *
  38722. * @private
  38723. * @type {?Window}
  38724. * @default null
  38725. */
  38726. this._currentAnimationContext = null;
  38727. /**
  38728. * The current animation loop.
  38729. *
  38730. * @private
  38731. * @type {?Function}
  38732. * @default null
  38733. */
  38734. this._currentAnimationLoop = null;
  38735. /**
  38736. * The current pixel ratio.
  38737. *
  38738. * @private
  38739. * @type {?number}
  38740. * @default null
  38741. */
  38742. this._currentPixelRatio = null;
  38743. /**
  38744. * The current size of the renderer's canvas
  38745. * in logical pixel unit.
  38746. *
  38747. * @private
  38748. * @type {Vector2}
  38749. */
  38750. this._currentSize = new Vector2();
  38751. /**
  38752. * The default event listener for handling events inside a XR session.
  38753. *
  38754. * @private
  38755. * @type {Function}
  38756. */
  38757. this._onSessionEvent = onSessionEvent.bind( this );
  38758. /**
  38759. * The event listener for handling the end of a XR session.
  38760. *
  38761. * @private
  38762. * @type {Function}
  38763. */
  38764. this._onSessionEnd = onSessionEnd.bind( this );
  38765. /**
  38766. * The event listener for handling the `inputsourceschange` event.
  38767. *
  38768. * @private
  38769. * @type {Function}
  38770. */
  38771. this._onInputSourcesChange = onInputSourcesChange.bind( this );
  38772. /**
  38773. * The animation loop which is used as a replacement for the default
  38774. * animation loop of the application. It is only used when a XR session
  38775. * is active.
  38776. *
  38777. * @private
  38778. * @type {Function}
  38779. */
  38780. this._onAnimationFrame = onAnimationFrame.bind( this );
  38781. /**
  38782. * The current XR reference space.
  38783. *
  38784. * @private
  38785. * @type {?XRReferenceSpace}
  38786. * @default null
  38787. */
  38788. this._referenceSpace = null;
  38789. /**
  38790. * The current XR reference space type.
  38791. *
  38792. * @private
  38793. * @type {XRReferenceSpaceType}
  38794. * @default 'local-floor'
  38795. */
  38796. this._referenceSpaceType = 'local-floor';
  38797. /**
  38798. * A custom reference space defined by the application.
  38799. *
  38800. * @private
  38801. * @type {?XRReferenceSpace}
  38802. * @default null
  38803. */
  38804. this._customReferenceSpace = null;
  38805. /**
  38806. * The framebuffer scale factor.
  38807. *
  38808. * @private
  38809. * @type {number}
  38810. * @default 1
  38811. */
  38812. this._framebufferScaleFactor = 1;
  38813. /**
  38814. * The foveation factor.
  38815. *
  38816. * @private
  38817. * @type {number}
  38818. * @default 1
  38819. */
  38820. this._foveation = 1.0;
  38821. /**
  38822. * A reference to the current XR session.
  38823. *
  38824. * @private
  38825. * @type {?XRSession}
  38826. * @default null
  38827. */
  38828. this._session = null;
  38829. /**
  38830. * A reference to the current XR base layer.
  38831. *
  38832. * @private
  38833. * @type {?XRWebGLLayer}
  38834. * @default null
  38835. */
  38836. this._glBaseLayer = null;
  38837. /**
  38838. * A reference to the current XR binding.
  38839. *
  38840. * @private
  38841. * @type {?XRWebGLBinding}
  38842. * @default null
  38843. */
  38844. this._glBinding = null;
  38845. /**
  38846. * A reference to the current XR projection layer.
  38847. *
  38848. * @private
  38849. * @type {?XRProjectionLayer}
  38850. * @default null
  38851. */
  38852. this._glProjLayer = null;
  38853. /**
  38854. * A reference to the current XR frame.
  38855. *
  38856. * @private
  38857. * @type {?XRFrame}
  38858. * @default null
  38859. */
  38860. this._xrFrame = null;
  38861. /**
  38862. * Whether the browser supports the APIs necessary to use XRProjectionLayers.
  38863. *
  38864. * Note: this does not represent XRSession explicitly requesting
  38865. * `'layers'` as a feature - see `_sessionUsesLayers` and #30112
  38866. *
  38867. * @private
  38868. * @type {boolean}
  38869. * @readonly
  38870. */
  38871. this._supportsLayers = ( this._supportsGlBinding && 'createProjectionLayer' in XRWebGLBinding.prototype ); // eslint-disable-line compat/compat
  38872. /**
  38873. * Whether the usage of multiview has been requested by the application or not.
  38874. *
  38875. * @private
  38876. * @type {boolean}
  38877. * @default false
  38878. * @readonly
  38879. */
  38880. this._useMultiviewIfPossible = multiview;
  38881. /**
  38882. * Whether the usage of multiview is actually enabled. This flag only evaluates to `true`
  38883. * if multiview has been requested by the application and the `OVR_multiview2` is available.
  38884. *
  38885. * @private
  38886. * @type {boolean}
  38887. * @readonly
  38888. */
  38889. this._useMultiview = false;
  38890. }
  38891. /**
  38892. * Returns an instance of `THREE.Group` that represents the transformation
  38893. * of a XR controller in target ray space. The requested controller is defined
  38894. * by the given index.
  38895. *
  38896. * @param {number} index - The index of the XR controller.
  38897. * @return {Group} A group that represents the controller's transformation.
  38898. */
  38899. getController( index ) {
  38900. const controller = this._getController( index );
  38901. return controller.getTargetRaySpace();
  38902. }
  38903. /**
  38904. * Returns an instance of `THREE.Group` that represents the transformation
  38905. * of a XR controller in grip space. The requested controller is defined
  38906. * by the given index.
  38907. *
  38908. * @param {number} index - The index of the XR controller.
  38909. * @return {Group} A group that represents the controller's transformation.
  38910. */
  38911. getControllerGrip( index ) {
  38912. const controller = this._getController( index );
  38913. return controller.getGripSpace();
  38914. }
  38915. /**
  38916. * Returns an instance of `THREE.Group` that represents the transformation
  38917. * of a XR controller in hand space. The requested controller is defined
  38918. * by the given index.
  38919. *
  38920. * @param {number} index - The index of the XR controller.
  38921. * @return {Group} A group that represents the controller's transformation.
  38922. */
  38923. getHand( index ) {
  38924. const controller = this._getController( index );
  38925. return controller.getHandSpace();
  38926. }
  38927. /**
  38928. * Returns the foveation value.
  38929. *
  38930. * @return {number|undefined} The foveation value. Returns `undefined` if no base or projection layer is defined.
  38931. */
  38932. getFoveation() {
  38933. if ( this._glProjLayer === null && this._glBaseLayer === null ) {
  38934. return undefined;
  38935. }
  38936. return this._foveation;
  38937. }
  38938. /**
  38939. * Sets the foveation value.
  38940. *
  38941. * @param {number} foveation - A number in the range `[0,1]` where `0` means no foveation (full resolution)
  38942. * and `1` means maximum foveation (the edges render at lower resolution).
  38943. */
  38944. setFoveation( foveation ) {
  38945. this._foveation = foveation;
  38946. if ( this._glProjLayer !== null ) {
  38947. this._glProjLayer.fixedFoveation = foveation;
  38948. }
  38949. if ( this._glBaseLayer !== null && this._glBaseLayer.fixedFoveation !== undefined ) {
  38950. this._glBaseLayer.fixedFoveation = foveation;
  38951. }
  38952. }
  38953. /**
  38954. * Returns the framebuffer scale factor.
  38955. *
  38956. * @return {number} The framebuffer scale factor.
  38957. */
  38958. getFramebufferScaleFactor() {
  38959. return this._framebufferScaleFactor;
  38960. }
  38961. /**
  38962. * Sets the framebuffer scale factor.
  38963. *
  38964. * This method can not be used during a XR session.
  38965. *
  38966. * @param {number} factor - The framebuffer scale factor.
  38967. */
  38968. setFramebufferScaleFactor( factor ) {
  38969. this._framebufferScaleFactor = factor;
  38970. if ( this.isPresenting === true ) {
  38971. warn( 'XRManager: Cannot change framebuffer scale while presenting.' );
  38972. }
  38973. }
  38974. /**
  38975. * Returns the reference space type.
  38976. *
  38977. * @return {XRReferenceSpaceType} The reference space type.
  38978. */
  38979. getReferenceSpaceType() {
  38980. return this._referenceSpaceType;
  38981. }
  38982. /**
  38983. * Sets the reference space type.
  38984. *
  38985. * This method can not be used during a XR session.
  38986. *
  38987. * @param {XRReferenceSpaceType} type - The reference space type.
  38988. */
  38989. setReferenceSpaceType( type ) {
  38990. this._referenceSpaceType = type;
  38991. if ( this.isPresenting === true ) {
  38992. warn( 'XRManager: Cannot change reference space type while presenting.' );
  38993. }
  38994. }
  38995. /**
  38996. * Returns the XR reference space.
  38997. *
  38998. * @return {XRReferenceSpace} The XR reference space.
  38999. */
  39000. getReferenceSpace() {
  39001. return this._customReferenceSpace || this._referenceSpace;
  39002. }
  39003. /**
  39004. * Sets a custom XR reference space.
  39005. *
  39006. * @param {XRReferenceSpace} space - The XR reference space.
  39007. */
  39008. setReferenceSpace( space ) {
  39009. this._customReferenceSpace = space;
  39010. }
  39011. /**
  39012. * Returns the XR camera.
  39013. *
  39014. * @return {ArrayCamera} The XR camera.
  39015. */
  39016. getCamera() {
  39017. return this._cameraXR;
  39018. }
  39019. /**
  39020. * Returns the environment blend mode from the current XR session.
  39021. *
  39022. * @return {'opaque'|'additive'|'alpha-blend'|undefined} The environment blend mode. Returns `undefined` when used outside of a XR session.
  39023. */
  39024. getEnvironmentBlendMode() {
  39025. if ( this._session !== null ) {
  39026. return this._session.environmentBlendMode;
  39027. }
  39028. }
  39029. /**
  39030. * Returns the current XR binding.
  39031. *
  39032. * Creates a new binding if needed and the browser is
  39033. * capable of doing so.
  39034. *
  39035. * @return {?XRWebGLBinding} The XR binding. Returns `null` if one cannot be created.
  39036. */
  39037. getBinding() {
  39038. if ( this._glBinding === null && this._supportsGlBinding ) {
  39039. this._glBinding = new XRWebGLBinding( this._session, this._gl );
  39040. }
  39041. return this._glBinding;
  39042. }
  39043. /**
  39044. * Returns the current XR frame.
  39045. *
  39046. * @return {?XRFrame} The XR frame. Returns `null` when used outside a XR session.
  39047. */
  39048. getFrame() {
  39049. return this._xrFrame;
  39050. }
  39051. /**
  39052. * Returns `true` if the engine renders to a multiview target.
  39053. *
  39054. * @return {boolean} Whether the engine renders to a multiview render target or not.
  39055. */
  39056. useMultiview() {
  39057. return this._useMultiview;
  39058. }
  39059. /**
  39060. * This method can be used in XR applications to create a quadratic layer that presents a separate
  39061. * rendered scene.
  39062. *
  39063. * @param {number} width - The width of the layer plane in world units.
  39064. * @param {number} height - The height of the layer plane in world units.
  39065. * @param {Vector3} translation - The position/translation of the layer plane in world units.
  39066. * @param {Quaternion} quaternion - The orientation of the layer plane expressed as a quaternion.
  39067. * @param {number} pixelwidth - The width of the layer's render target in pixels.
  39068. * @param {number} pixelheight - The height of the layer's render target in pixels.
  39069. * @param {Function} rendercall - A callback function that renders the layer. Similar to code in
  39070. * the default animation loop, this method can be used to update/transform 3D object in the layer's scene.
  39071. * @param {Object} [attributes={}] - Allows to configure the layer's render target.
  39072. * @return {Mesh} A mesh representing the quadratic XR layer. This mesh should be added to the XR scene.
  39073. */
  39074. createQuadLayer( width, height, translation, quaternion, pixelwidth, pixelheight, rendercall, attributes = {} ) {
  39075. const geometry = new PlaneGeometry( width, height );
  39076. const renderTarget = new XRRenderTarget(
  39077. pixelwidth,
  39078. pixelheight,
  39079. {
  39080. format: RGBAFormat,
  39081. type: UnsignedByteType,
  39082. depthTexture: new DepthTexture(
  39083. pixelwidth,
  39084. pixelheight,
  39085. attributes.stencil ? UnsignedInt248Type : UnsignedIntType,
  39086. undefined,
  39087. undefined,
  39088. undefined,
  39089. undefined,
  39090. undefined,
  39091. undefined,
  39092. attributes.stencil ? DepthStencilFormat : DepthFormat
  39093. ),
  39094. stencilBuffer: attributes.stencil,
  39095. resolveDepthBuffer: false,
  39096. resolveStencilBuffer: false
  39097. } );
  39098. renderTarget._autoAllocateDepthBuffer = true;
  39099. const material = new MeshBasicMaterial( { color: 0xffffff, side: FrontSide } );
  39100. material.map = renderTarget.texture;
  39101. material.map.offset.y = 1;
  39102. material.map.repeat.y = -1;
  39103. const plane = new Mesh( geometry, material );
  39104. plane.position.copy( translation );
  39105. plane.quaternion.copy( quaternion );
  39106. const layer = {
  39107. type: 'quad',
  39108. width: width,
  39109. height: height,
  39110. translation: translation,
  39111. quaternion: quaternion,
  39112. pixelwidth: pixelwidth,
  39113. pixelheight: pixelheight,
  39114. plane: plane,
  39115. material: material,
  39116. rendercall: rendercall,
  39117. renderTarget: renderTarget };
  39118. this._layers.push( layer );
  39119. if ( this._session !== null ) {
  39120. layer.plane.material = new MeshBasicMaterial( { color: 0xffffff, side: FrontSide } );
  39121. layer.plane.material.blending = CustomBlending;
  39122. layer.plane.material.blendEquation = AddEquation;
  39123. layer.plane.material.blendSrc = ZeroFactor;
  39124. layer.plane.material.blendDst = ZeroFactor;
  39125. layer.xrlayer = this._createXRLayer( layer );
  39126. const xrlayers = this._session.renderState.layers;
  39127. xrlayers.unshift( layer.xrlayer );
  39128. this._session.updateRenderState( { layers: xrlayers } );
  39129. } else {
  39130. renderTarget.isXRRenderTarget = false;
  39131. }
  39132. return plane;
  39133. }
  39134. /**
  39135. * This method can be used in XR applications to create a cylindrical layer that presents a separate
  39136. * rendered scene.
  39137. *
  39138. * @param {number} radius - The radius of the cylinder in world units.
  39139. * @param {number} centralAngle - The central angle of the cylinder in radians.
  39140. * @param {number} aspectratio - The aspect ratio.
  39141. * @param {Vector3} translation - The position/translation of the layer plane in world units.
  39142. * @param {Quaternion} quaternion - The orientation of the layer plane expressed as a quaternion.
  39143. * @param {number} pixelwidth - The width of the layer's render target in pixels.
  39144. * @param {number} pixelheight - The height of the layer's render target in pixels.
  39145. * @param {Function} rendercall - A callback function that renders the layer. Similar to code in
  39146. * the default animation loop, this method can be used to update/transform 3D object in the layer's scene.
  39147. * @param {Object} [attributes={}] - Allows to configure the layer's render target.
  39148. * @return {Mesh} A mesh representing the cylindrical XR layer. This mesh should be added to the XR scene.
  39149. */
  39150. createCylinderLayer( radius, centralAngle, aspectratio, translation, quaternion, pixelwidth, pixelheight, rendercall, attributes = {} ) {
  39151. const geometry = new CylinderGeometry( radius, radius, radius * centralAngle / aspectratio, 64, 64, true, Math.PI - centralAngle / 2, centralAngle );
  39152. const renderTarget = new XRRenderTarget(
  39153. pixelwidth,
  39154. pixelheight,
  39155. {
  39156. format: RGBAFormat,
  39157. type: UnsignedByteType,
  39158. depthTexture: new DepthTexture(
  39159. pixelwidth,
  39160. pixelheight,
  39161. attributes.stencil ? UnsignedInt248Type : UnsignedIntType,
  39162. undefined,
  39163. undefined,
  39164. undefined,
  39165. undefined,
  39166. undefined,
  39167. undefined,
  39168. attributes.stencil ? DepthStencilFormat : DepthFormat
  39169. ),
  39170. stencilBuffer: attributes.stencil,
  39171. resolveDepthBuffer: false,
  39172. resolveStencilBuffer: false
  39173. } );
  39174. renderTarget._autoAllocateDepthBuffer = true;
  39175. const material = new MeshBasicMaterial( { color: 0xffffff, side: BackSide } );
  39176. material.map = renderTarget.texture;
  39177. material.map.offset.y = 1;
  39178. material.map.repeat.y = -1;
  39179. const plane = new Mesh( geometry, material );
  39180. plane.position.copy( translation );
  39181. plane.quaternion.copy( quaternion );
  39182. const layer = {
  39183. type: 'cylinder',
  39184. radius: radius,
  39185. centralAngle: centralAngle,
  39186. aspectratio: aspectratio,
  39187. translation: translation,
  39188. quaternion: quaternion,
  39189. pixelwidth: pixelwidth,
  39190. pixelheight: pixelheight,
  39191. plane: plane,
  39192. material: material,
  39193. rendercall: rendercall,
  39194. renderTarget: renderTarget };
  39195. this._layers.push( layer );
  39196. if ( this._session !== null ) {
  39197. layer.plane.material = new MeshBasicMaterial( { color: 0xffffff, side: BackSide } );
  39198. layer.plane.material.blending = CustomBlending;
  39199. layer.plane.material.blendEquation = AddEquation;
  39200. layer.plane.material.blendSrc = ZeroFactor;
  39201. layer.plane.material.blendDst = ZeroFactor;
  39202. layer.xrlayer = this._createXRLayer( layer );
  39203. const xrlayers = this._session.renderState.layers;
  39204. xrlayers.unshift( layer.xrlayer );
  39205. this._session.updateRenderState( { layers: xrlayers } );
  39206. } else {
  39207. renderTarget.isXRRenderTarget = false;
  39208. }
  39209. return plane;
  39210. }
  39211. /**
  39212. * Renders the XR layers that have been previously added to the scene.
  39213. *
  39214. * This method is usually called in your animation loop before rendering
  39215. * the actual scene via `renderer.render( scene, camera );`.
  39216. */
  39217. renderLayers( ) {
  39218. const translationObject = new Vector3();
  39219. const quaternionObject = new Quaternion();
  39220. const renderer = this._renderer;
  39221. const wasPresenting = this.isPresenting;
  39222. const rendererOutputTarget = renderer.getOutputRenderTarget();
  39223. const rendererFramebufferTarget = renderer._frameBufferTarget;
  39224. this.isPresenting = false;
  39225. const rendererSize = new Vector2();
  39226. renderer.getSize( rendererSize );
  39227. const rendererQuad = renderer._quad;
  39228. for ( const layer of this._layers ) {
  39229. layer.renderTarget.isXRRenderTarget = this._session !== null;
  39230. layer.renderTarget._hasExternalTextures = layer.renderTarget.isXRRenderTarget;
  39231. if ( layer.renderTarget.isXRRenderTarget && this._sessionUsesLayers ) {
  39232. layer.xrlayer.transform = new XRRigidTransform( layer.plane.getWorldPosition( translationObject ), layer.plane.getWorldQuaternion( quaternionObject ) );
  39233. const glSubImage = this._glBinding.getSubImage( layer.xrlayer, this._xrFrame );
  39234. renderer.backend.setXRRenderTargetTextures(
  39235. layer.renderTarget,
  39236. glSubImage.colorTexture,
  39237. undefined );
  39238. renderer._setXRLayerSize( layer.renderTarget.width, layer.renderTarget.height );
  39239. renderer.setOutputRenderTarget( layer.renderTarget );
  39240. renderer.setRenderTarget( null );
  39241. renderer._frameBufferTarget = null;
  39242. this._frameBufferTargets || ( this._frameBufferTargets = new WeakMap() );
  39243. const { frameBufferTarget, quad } = this._frameBufferTargets.get( layer.renderTarget ) || { frameBufferTarget: null, quad: null };
  39244. if ( ! frameBufferTarget ) {
  39245. renderer._quad = new QuadMesh( new NodeMaterial() );
  39246. this._frameBufferTargets.set( layer.renderTarget, { frameBufferTarget: renderer._getFrameBufferTarget(), quad: renderer._quad } );
  39247. } else {
  39248. renderer._frameBufferTarget = frameBufferTarget;
  39249. renderer._quad = quad;
  39250. }
  39251. layer.rendercall();
  39252. renderer._frameBufferTarget = null;
  39253. } else {
  39254. renderer.setRenderTarget( layer.renderTarget );
  39255. layer.rendercall();
  39256. }
  39257. }
  39258. renderer.setRenderTarget( null );
  39259. renderer.setOutputRenderTarget( rendererOutputTarget );
  39260. renderer._frameBufferTarget = rendererFramebufferTarget;
  39261. renderer._setXRLayerSize( rendererSize.x, rendererSize.y );
  39262. renderer._quad = rendererQuad;
  39263. this.isPresenting = wasPresenting;
  39264. }
  39265. /**
  39266. * Returns the current XR session.
  39267. *
  39268. * @return {?XRSession} The XR session. Returns `null` when used outside a XR session.
  39269. */
  39270. getSession() {
  39271. return this._session;
  39272. }
  39273. /**
  39274. * After a XR session has been requested usually with one of the `*Button` modules, it
  39275. * is injected into the renderer with this method. This method triggers the start of
  39276. * the actual XR rendering.
  39277. *
  39278. * @async
  39279. * @param {XRSession} session - The XR session to set.
  39280. * @return {Promise} A Promise that resolves when the session has been set.
  39281. */
  39282. async setSession( session ) {
  39283. const renderer = this._renderer;
  39284. const backend = renderer.backend;
  39285. this._gl = renderer.getContext();
  39286. const gl = this._gl;
  39287. const attributes = gl.getContextAttributes();
  39288. this._session = session;
  39289. if ( session !== null ) {
  39290. if ( backend.isWebGPUBackend === true ) throw new Error( 'THREE.XRManager: XR is currently not supported with a WebGPU backend. Use WebGL by passing "{ forceWebGL: true }" to the constructor of the renderer.' );
  39291. session.addEventListener( 'select', this._onSessionEvent );
  39292. session.addEventListener( 'selectstart', this._onSessionEvent );
  39293. session.addEventListener( 'selectend', this._onSessionEvent );
  39294. session.addEventListener( 'squeeze', this._onSessionEvent );
  39295. session.addEventListener( 'squeezestart', this._onSessionEvent );
  39296. session.addEventListener( 'squeezeend', this._onSessionEvent );
  39297. session.addEventListener( 'end', this._onSessionEnd );
  39298. session.addEventListener( 'inputsourceschange', this._onInputSourcesChange );
  39299. await backend.makeXRCompatible();
  39300. this._currentPixelRatio = renderer.getPixelRatio();
  39301. renderer.getSize( this._currentSize );
  39302. this._currentAnimationContext = renderer._animation.getContext();
  39303. this._currentAnimationLoop = renderer._animation.getAnimationLoop();
  39304. renderer._animation.stop();
  39305. //
  39306. if ( this._supportsLayers === true ) {
  39307. // default path using XRProjectionLayer
  39308. let depthFormat = null;
  39309. let depthType = null;
  39310. let glDepthFormat = null;
  39311. if ( renderer.depth ) {
  39312. glDepthFormat = renderer.stencil ? gl.DEPTH24_STENCIL8 : gl.DEPTH_COMPONENT24;
  39313. depthFormat = renderer.stencil ? DepthStencilFormat : DepthFormat;
  39314. depthType = renderer.stencil ? UnsignedInt248Type : UnsignedIntType;
  39315. }
  39316. const projectionlayerInit = {
  39317. colorFormat: gl.RGBA8,
  39318. depthFormat: glDepthFormat,
  39319. scaleFactor: this._framebufferScaleFactor,
  39320. clearOnAccess: false
  39321. };
  39322. if ( this._useMultiviewIfPossible && renderer.hasFeature( 'OVR_multiview2' ) ) {
  39323. projectionlayerInit.textureType = 'texture-array';
  39324. this._useMultiview = true;
  39325. }
  39326. this._glBinding = this.getBinding();
  39327. const glProjLayer = this._glBinding.createProjectionLayer( projectionlayerInit );
  39328. const layersArray = [ glProjLayer ];
  39329. this._glProjLayer = glProjLayer;
  39330. renderer.setPixelRatio( 1 );
  39331. renderer._setXRLayerSize( glProjLayer.textureWidth, glProjLayer.textureHeight );
  39332. const depth = this._useMultiview ? 2 : 1;
  39333. const depthTexture = new DepthTexture( glProjLayer.textureWidth, glProjLayer.textureHeight, depthType, undefined, undefined, undefined, undefined, undefined, undefined, depthFormat, depth );
  39334. this._xrRenderTarget = new XRRenderTarget(
  39335. glProjLayer.textureWidth,
  39336. glProjLayer.textureHeight,
  39337. {
  39338. format: RGBAFormat,
  39339. type: UnsignedByteType,
  39340. colorSpace: renderer.outputColorSpace,
  39341. depthTexture: depthTexture,
  39342. stencilBuffer: renderer.stencil,
  39343. samples: attributes.antialias ? 4 : 0,
  39344. resolveDepthBuffer: ( glProjLayer.ignoreDepthValues === false ),
  39345. resolveStencilBuffer: ( glProjLayer.ignoreDepthValues === false ),
  39346. depth: this._useMultiview ? 2 : 1,
  39347. multiview: this._useMultiview
  39348. } );
  39349. this._xrRenderTarget._hasExternalTextures = true;
  39350. this._xrRenderTarget.depth = this._useMultiview ? 2 : 1;
  39351. this._sessionUsesLayers = session.enabledFeatures.includes( 'layers' );
  39352. this._referenceSpace = await session.requestReferenceSpace( this.getReferenceSpaceType() );
  39353. if ( this._sessionUsesLayers ) {
  39354. // switch layers to native
  39355. for ( const layer of this._layers ) {
  39356. // change material so it "punches" out a hole to show the XR Layer.
  39357. layer.plane.material = new MeshBasicMaterial( { color: 0xffffff, side: layer.type === 'cylinder' ? BackSide : FrontSide } );
  39358. layer.plane.material.blending = CustomBlending;
  39359. layer.plane.material.blendEquation = AddEquation;
  39360. layer.plane.material.blendSrc = ZeroFactor;
  39361. layer.plane.material.blendDst = ZeroFactor;
  39362. layer.xrlayer = this._createXRLayer( layer );
  39363. layersArray.unshift( layer.xrlayer );
  39364. }
  39365. }
  39366. session.updateRenderState( { layers: layersArray } );
  39367. } else {
  39368. // fallback to XRWebGLLayer
  39369. const layerInit = {
  39370. antialias: renderer.currentSamples > 0,
  39371. alpha: true,
  39372. depth: renderer.depth,
  39373. stencil: renderer.stencil,
  39374. framebufferScaleFactor: this.getFramebufferScaleFactor()
  39375. };
  39376. const glBaseLayer = new XRWebGLLayer( session, gl, layerInit );
  39377. this._glBaseLayer = glBaseLayer;
  39378. session.updateRenderState( { baseLayer: glBaseLayer } );
  39379. renderer.setPixelRatio( 1 );
  39380. renderer._setXRLayerSize( glBaseLayer.framebufferWidth, glBaseLayer.framebufferHeight );
  39381. this._xrRenderTarget = new XRRenderTarget(
  39382. glBaseLayer.framebufferWidth,
  39383. glBaseLayer.framebufferHeight,
  39384. {
  39385. format: RGBAFormat,
  39386. type: UnsignedByteType,
  39387. colorSpace: renderer.outputColorSpace,
  39388. stencilBuffer: renderer.stencil,
  39389. resolveDepthBuffer: ( glBaseLayer.ignoreDepthValues === false ),
  39390. resolveStencilBuffer: ( glBaseLayer.ignoreDepthValues === false ),
  39391. }
  39392. );
  39393. this._xrRenderTarget._isOpaqueFramebuffer = true;
  39394. this._referenceSpace = await session.requestReferenceSpace( this.getReferenceSpaceType() );
  39395. }
  39396. //
  39397. this.setFoveation( this.getFoveation() );
  39398. renderer._animation.setAnimationLoop( this._onAnimationFrame );
  39399. renderer._animation.setContext( session );
  39400. renderer._animation.start();
  39401. this.isPresenting = true;
  39402. this.dispatchEvent( { type: 'sessionstart' } );
  39403. }
  39404. }
  39405. /**
  39406. * This method is called by the renderer per frame and updates the XR camera
  39407. * and it sub cameras based on the given camera. The given camera is the "user"
  39408. * camera created on application level and used for non-XR rendering.
  39409. *
  39410. * @param {PerspectiveCamera} camera - The camera.
  39411. */
  39412. updateCamera( camera ) {
  39413. const session = this._session;
  39414. if ( session === null ) return;
  39415. const depthNear = camera.near;
  39416. const depthFar = camera.far;
  39417. const cameraXR = this._cameraXR;
  39418. const cameraL = this._cameraL;
  39419. const cameraR = this._cameraR;
  39420. cameraXR.near = cameraR.near = cameraL.near = depthNear;
  39421. cameraXR.far = cameraR.far = cameraL.far = depthFar;
  39422. cameraXR.isMultiViewCamera = this._useMultiview;
  39423. if ( this._currentDepthNear !== cameraXR.near || this._currentDepthFar !== cameraXR.far ) {
  39424. // Note that the new renderState won't apply until the next frame. See #18320
  39425. session.updateRenderState( {
  39426. depthNear: cameraXR.near,
  39427. depthFar: cameraXR.far
  39428. } );
  39429. this._currentDepthNear = cameraXR.near;
  39430. this._currentDepthFar = cameraXR.far;
  39431. }
  39432. // inherit camera layers and enable eye layers (1 = left, 2 = right)
  39433. cameraXR.layers.mask = camera.layers.mask | 0b110;
  39434. cameraL.layers.mask = cameraXR.layers.mask & 0b011;
  39435. cameraR.layers.mask = cameraXR.layers.mask & 0b101;
  39436. const parent = camera.parent;
  39437. const cameras = cameraXR.cameras;
  39438. updateCamera( cameraXR, parent );
  39439. for ( let i = 0; i < cameras.length; i ++ ) {
  39440. updateCamera( cameras[ i ], parent );
  39441. }
  39442. // update projection matrix for proper view frustum culling
  39443. if ( cameras.length === 2 ) {
  39444. setProjectionFromUnion( cameraXR, cameraL, cameraR );
  39445. } else {
  39446. // assume single camera setup (AR)
  39447. cameraXR.projectionMatrix.copy( cameraL.projectionMatrix );
  39448. }
  39449. // update user camera and its children
  39450. updateUserCamera( camera, cameraXR, parent );
  39451. }
  39452. /**
  39453. * Returns a WebXR controller for the given controller index.
  39454. *
  39455. * @private
  39456. * @param {number} index - The controller index.
  39457. * @return {WebXRController} The XR controller.
  39458. */
  39459. _getController( index ) {
  39460. let controller = this._controllers[ index ];
  39461. if ( controller === undefined ) {
  39462. controller = new WebXRController();
  39463. this._controllers[ index ] = controller;
  39464. }
  39465. return controller;
  39466. }
  39467. }
  39468. /**
  39469. * Assumes 2 cameras that are parallel and share an X-axis, and that
  39470. * the cameras' projection and world matrices have already been set.
  39471. * And that near and far planes are identical for both cameras.
  39472. * Visualization of this technique: https://computergraphics.stackexchange.com/a/4765
  39473. *
  39474. * @param {ArrayCamera} camera - The camera to update.
  39475. * @param {PerspectiveCamera} cameraL - The left camera.
  39476. * @param {PerspectiveCamera} cameraR - The right camera.
  39477. */
  39478. function setProjectionFromUnion( camera, cameraL, cameraR ) {
  39479. _cameraLPos.setFromMatrixPosition( cameraL.matrixWorld );
  39480. _cameraRPos.setFromMatrixPosition( cameraR.matrixWorld );
  39481. const ipd = _cameraLPos.distanceTo( _cameraRPos );
  39482. const projL = cameraL.projectionMatrix.elements;
  39483. const projR = cameraR.projectionMatrix.elements;
  39484. // VR systems will have identical far and near planes, and
  39485. // most likely identical top and bottom frustum extents.
  39486. // Use the left camera for these values.
  39487. const near = projL[ 14 ] / ( projL[ 10 ] - 1 );
  39488. const far = projL[ 14 ] / ( projL[ 10 ] + 1 );
  39489. const topFov = ( projL[ 9 ] + 1 ) / projL[ 5 ];
  39490. const bottomFov = ( projL[ 9 ] - 1 ) / projL[ 5 ];
  39491. const leftFov = ( projL[ 8 ] - 1 ) / projL[ 0 ];
  39492. const rightFov = ( projR[ 8 ] + 1 ) / projR[ 0 ];
  39493. const left = near * leftFov;
  39494. const right = near * rightFov;
  39495. // Calculate the new camera's position offset from the
  39496. // left camera. xOffset should be roughly half `ipd`.
  39497. const zOffset = ipd / ( - leftFov + rightFov );
  39498. const xOffset = zOffset * - leftFov;
  39499. // TODO: Better way to apply this offset?
  39500. cameraL.matrixWorld.decompose( camera.position, camera.quaternion, camera.scale );
  39501. camera.translateX( xOffset );
  39502. camera.translateZ( zOffset );
  39503. camera.matrixWorld.compose( camera.position, camera.quaternion, camera.scale );
  39504. camera.matrixWorldInverse.copy( camera.matrixWorld ).invert();
  39505. // Check if the projection uses an infinite far plane.
  39506. if ( projL[ 10 ] === -1 ) {
  39507. // Use the projection matrix from the left eye.
  39508. // The camera offset is sufficient to include the view volumes
  39509. // of both eyes (assuming symmetric projections).
  39510. camera.projectionMatrix.copy( cameraL.projectionMatrix );
  39511. camera.projectionMatrixInverse.copy( cameraL.projectionMatrixInverse );
  39512. } else {
  39513. // Find the union of the frustum values of the cameras and scale
  39514. // the values so that the near plane's position does not change in world space,
  39515. // although must now be relative to the new union camera.
  39516. const near2 = near + zOffset;
  39517. const far2 = far + zOffset;
  39518. const left2 = left - xOffset;
  39519. const right2 = right + ( ipd - xOffset );
  39520. const top2 = topFov * far / far2 * near2;
  39521. const bottom2 = bottomFov * far / far2 * near2;
  39522. camera.projectionMatrix.makePerspective( left2, right2, top2, bottom2, near2, far2 );
  39523. camera.projectionMatrixInverse.copy( camera.projectionMatrix ).invert();
  39524. }
  39525. }
  39526. /**
  39527. * Updates the world matrices for the given camera based on the parent 3D object.
  39528. *
  39529. * @inner
  39530. * @param {Camera} camera - The camera to update.
  39531. * @param {Object3D} parent - The parent 3D object.
  39532. */
  39533. function updateCamera( camera, parent ) {
  39534. if ( parent === null ) {
  39535. camera.matrixWorld.copy( camera.matrix );
  39536. } else {
  39537. camera.matrixWorld.multiplyMatrices( parent.matrixWorld, camera.matrix );
  39538. }
  39539. camera.matrixWorldInverse.copy( camera.matrixWorld ).invert();
  39540. }
  39541. /**
  39542. * Updates the given camera with the transformation of the XR camera and parent object.
  39543. *
  39544. * @inner
  39545. * @param {Camera} camera - The camera to update.
  39546. * @param {ArrayCamera} cameraXR - The XR camera.
  39547. * @param {Object3D} parent - The parent 3D object.
  39548. */
  39549. function updateUserCamera( camera, cameraXR, parent ) {
  39550. if ( parent === null ) {
  39551. camera.matrix.copy( cameraXR.matrixWorld );
  39552. } else {
  39553. camera.matrix.copy( parent.matrixWorld );
  39554. camera.matrix.invert();
  39555. camera.matrix.multiply( cameraXR.matrixWorld );
  39556. }
  39557. camera.matrix.decompose( camera.position, camera.quaternion, camera.scale );
  39558. camera.updateMatrixWorld( true );
  39559. camera.projectionMatrix.copy( cameraXR.projectionMatrix );
  39560. camera.projectionMatrixInverse.copy( cameraXR.projectionMatrixInverse );
  39561. if ( camera.isPerspectiveCamera ) {
  39562. camera.fov = RAD2DEG * 2 * Math.atan( 1 / camera.projectionMatrix.elements[ 5 ] );
  39563. camera.zoom = 1;
  39564. }
  39565. }
  39566. function onSessionEvent( event ) {
  39567. const controllerIndex = this._controllerInputSources.indexOf( event.inputSource );
  39568. if ( controllerIndex === -1 ) {
  39569. return;
  39570. }
  39571. const controller = this._controllers[ controllerIndex ];
  39572. if ( controller !== undefined ) {
  39573. const referenceSpace = this.getReferenceSpace();
  39574. controller.update( event.inputSource, event.frame, referenceSpace );
  39575. controller.dispatchEvent( { type: event.type, data: event.inputSource } );
  39576. }
  39577. }
  39578. function onSessionEnd() {
  39579. const session = this._session;
  39580. const renderer = this._renderer;
  39581. session.removeEventListener( 'select', this._onSessionEvent );
  39582. session.removeEventListener( 'selectstart', this._onSessionEvent );
  39583. session.removeEventListener( 'selectend', this._onSessionEvent );
  39584. session.removeEventListener( 'squeeze', this._onSessionEvent );
  39585. session.removeEventListener( 'squeezestart', this._onSessionEvent );
  39586. session.removeEventListener( 'squeezeend', this._onSessionEvent );
  39587. session.removeEventListener( 'end', this._onSessionEnd );
  39588. session.removeEventListener( 'inputsourceschange', this._onInputSourcesChange );
  39589. for ( let i = 0; i < this._controllers.length; i ++ ) {
  39590. const inputSource = this._controllerInputSources[ i ];
  39591. if ( inputSource === null ) continue;
  39592. this._controllerInputSources[ i ] = null;
  39593. this._controllers[ i ].disconnect( inputSource );
  39594. }
  39595. this._currentDepthNear = null;
  39596. this._currentDepthFar = null;
  39597. // restore framebuffer/rendering state
  39598. renderer._resetXRState();
  39599. this._session = null;
  39600. this._xrRenderTarget = null;
  39601. this._glBinding = null;
  39602. this._glBaseLayer = null;
  39603. this._glProjLayer = null;
  39604. // switch layers back to emulated
  39605. if ( this._sessionUsesLayers === true ) {
  39606. for ( const layer of this._layers ) {
  39607. // Recreate layer render target to reset state
  39608. layer.renderTarget = new XRRenderTarget(
  39609. layer.pixelwidth,
  39610. layer.pixelheight,
  39611. {
  39612. format: RGBAFormat,
  39613. type: UnsignedByteType,
  39614. depthTexture: new DepthTexture(
  39615. layer.pixelwidth,
  39616. layer.pixelheight,
  39617. layer.stencilBuffer ? UnsignedInt248Type : UnsignedIntType,
  39618. undefined,
  39619. undefined,
  39620. undefined,
  39621. undefined,
  39622. undefined,
  39623. undefined,
  39624. layer.stencilBuffer ? DepthStencilFormat : DepthFormat
  39625. ),
  39626. stencilBuffer: layer.stencilBuffer,
  39627. resolveDepthBuffer: false,
  39628. resolveStencilBuffer: false
  39629. } );
  39630. layer.renderTarget.isXRRenderTarget = false;
  39631. layer.plane.material = layer.material;
  39632. layer.material.map = layer.renderTarget.texture;
  39633. layer.material.map.offset.y = 1;
  39634. layer.material.map.repeat.y = -1;
  39635. delete layer.xrlayer;
  39636. }
  39637. }
  39638. //
  39639. this.isPresenting = false;
  39640. this._useMultiview = false;
  39641. renderer._animation.stop();
  39642. renderer._animation.setAnimationLoop( this._currentAnimationLoop );
  39643. renderer._animation.setContext( this._currentAnimationContext );
  39644. renderer._animation.start();
  39645. renderer.setPixelRatio( this._currentPixelRatio );
  39646. renderer.setSize( this._currentSize.width, this._currentSize.height, false );
  39647. this.dispatchEvent( { type: 'sessionend' } );
  39648. }
  39649. function onInputSourcesChange( event ) {
  39650. const controllers = this._controllers;
  39651. const controllerInputSources = this._controllerInputSources;
  39652. // Notify disconnected
  39653. for ( let i = 0; i < event.removed.length; i ++ ) {
  39654. const inputSource = event.removed[ i ];
  39655. const index = controllerInputSources.indexOf( inputSource );
  39656. if ( index >= 0 ) {
  39657. controllerInputSources[ index ] = null;
  39658. controllers[ index ].disconnect( inputSource );
  39659. }
  39660. }
  39661. // Notify connected
  39662. for ( let i = 0; i < event.added.length; i ++ ) {
  39663. const inputSource = event.added[ i ];
  39664. let controllerIndex = controllerInputSources.indexOf( inputSource );
  39665. if ( controllerIndex === -1 ) {
  39666. // Assign input source a controller that currently has no input source
  39667. for ( let i = 0; i < controllers.length; i ++ ) {
  39668. if ( i >= controllerInputSources.length ) {
  39669. controllerInputSources.push( inputSource );
  39670. controllerIndex = i;
  39671. break;
  39672. } else if ( controllerInputSources[ i ] === null ) {
  39673. controllerInputSources[ i ] = inputSource;
  39674. controllerIndex = i;
  39675. break;
  39676. }
  39677. }
  39678. // If all controllers do currently receive input we ignore new ones
  39679. if ( controllerIndex === -1 ) break;
  39680. }
  39681. const controller = controllers[ controllerIndex ];
  39682. if ( controller ) {
  39683. controller.connect( inputSource );
  39684. }
  39685. }
  39686. }
  39687. // Creation method for native WebXR layers
  39688. function createXRLayer( layer ) {
  39689. if ( layer.type === 'quad' ) {
  39690. return this._glBinding.createQuadLayer( {
  39691. transform: new XRRigidTransform( layer.translation, layer.quaternion ),
  39692. width: layer.width / 2,
  39693. height: layer.height / 2,
  39694. space: this._referenceSpace,
  39695. viewPixelWidth: layer.pixelwidth,
  39696. viewPixelHeight: layer.pixelheight,
  39697. clearOnAccess: false
  39698. } );
  39699. } else {
  39700. return this._glBinding.createCylinderLayer( {
  39701. transform: new XRRigidTransform( layer.translation, layer.quaternion ),
  39702. radius: layer.radius,
  39703. centralAngle: layer.centralAngle,
  39704. aspectRatio: layer.aspectRatio,
  39705. space: this._referenceSpace,
  39706. viewPixelWidth: layer.pixelwidth,
  39707. viewPixelHeight: layer.pixelheight,
  39708. clearOnAccess: false
  39709. } );
  39710. }
  39711. }
  39712. // Animation Loop
  39713. function onAnimationFrame( time, frame ) {
  39714. if ( frame === undefined ) return;
  39715. const cameraXR = this._cameraXR;
  39716. const renderer = this._renderer;
  39717. const backend = renderer.backend;
  39718. const glBaseLayer = this._glBaseLayer;
  39719. const referenceSpace = this.getReferenceSpace();
  39720. const pose = frame.getViewerPose( referenceSpace );
  39721. this._xrFrame = frame;
  39722. if ( pose !== null ) {
  39723. const views = pose.views;
  39724. if ( this._glBaseLayer !== null ) {
  39725. backend.setXRTarget( glBaseLayer.framebuffer );
  39726. }
  39727. let cameraXRNeedsUpdate = false;
  39728. // check if it's necessary to rebuild cameraXR's camera list
  39729. if ( views.length !== cameraXR.cameras.length ) {
  39730. cameraXR.cameras.length = 0;
  39731. cameraXRNeedsUpdate = true;
  39732. }
  39733. for ( let i = 0; i < views.length; i ++ ) {
  39734. const view = views[ i ];
  39735. let viewport;
  39736. if ( this._supportsLayers === true ) {
  39737. const glSubImage = this._glBinding.getViewSubImage( this._glProjLayer, view );
  39738. viewport = glSubImage.viewport;
  39739. // For side-by-side projection, we only produce a single texture for both eyes.
  39740. if ( i === 0 ) {
  39741. backend.setXRRenderTargetTextures(
  39742. this._xrRenderTarget,
  39743. glSubImage.colorTexture,
  39744. ( this._glProjLayer.ignoreDepthValues && ! this._useMultiview ) ? undefined : glSubImage.depthStencilTexture
  39745. );
  39746. }
  39747. } else {
  39748. viewport = glBaseLayer.getViewport( view );
  39749. }
  39750. let camera = this._cameras[ i ];
  39751. if ( camera === undefined ) {
  39752. camera = new PerspectiveCamera();
  39753. camera.layers.enable( i );
  39754. camera.viewport = new Vector4();
  39755. this._cameras[ i ] = camera;
  39756. }
  39757. camera.matrix.fromArray( view.transform.matrix );
  39758. camera.matrix.decompose( camera.position, camera.quaternion, camera.scale );
  39759. camera.projectionMatrix.fromArray( view.projectionMatrix );
  39760. camera.projectionMatrixInverse.copy( camera.projectionMatrix ).invert();
  39761. camera.viewport.set( viewport.x, viewport.y, viewport.width, viewport.height );
  39762. if ( i === 0 ) {
  39763. cameraXR.matrix.copy( camera.matrix );
  39764. cameraXR.matrix.decompose( cameraXR.position, cameraXR.quaternion, cameraXR.scale );
  39765. }
  39766. if ( cameraXRNeedsUpdate === true ) {
  39767. cameraXR.cameras.push( camera );
  39768. }
  39769. }
  39770. renderer.setOutputRenderTarget( this._xrRenderTarget );
  39771. }
  39772. //
  39773. for ( let i = 0; i < this._controllers.length; i ++ ) {
  39774. const inputSource = this._controllerInputSources[ i ];
  39775. const controller = this._controllers[ i ];
  39776. if ( inputSource !== null && controller !== undefined ) {
  39777. controller.update( inputSource, frame, referenceSpace );
  39778. }
  39779. }
  39780. if ( this._currentAnimationLoop ) this._currentAnimationLoop( time, frame );
  39781. if ( frame.detectedPlanes ) {
  39782. this.dispatchEvent( { type: 'planesdetected', data: frame } );
  39783. }
  39784. this._xrFrame = null;
  39785. }
  39786. /**
  39787. * CanvasTarget is a class that represents the final output destination of the renderer.
  39788. *
  39789. * @augments EventDispatcher
  39790. */
  39791. class CanvasTarget extends EventDispatcher {
  39792. /**
  39793. * Constructs a new CanvasTarget.
  39794. *
  39795. * @param {HTMLCanvasElement|OffscreenCanvas} domElement - The canvas element to render to.
  39796. */
  39797. constructor( domElement ) {
  39798. super();
  39799. /**
  39800. * A reference to the canvas element the renderer is drawing to.
  39801. * This value of this property will automatically be created by
  39802. * the renderer.
  39803. *
  39804. * @type {HTMLCanvasElement|OffscreenCanvas}
  39805. */
  39806. this.domElement = domElement;
  39807. /**
  39808. * The renderer's pixel ratio.
  39809. *
  39810. * @private
  39811. * @type {number}
  39812. * @default 1
  39813. */
  39814. this._pixelRatio = 1;
  39815. /**
  39816. * The width of the renderer's default framebuffer in logical pixel unit.
  39817. *
  39818. * @private
  39819. * @type {number}
  39820. */
  39821. this._width = this.domElement.width;
  39822. /**
  39823. * The height of the renderer's default framebuffer in logical pixel unit.
  39824. *
  39825. * @private
  39826. * @type {number}
  39827. */
  39828. this._height = this.domElement.height;
  39829. /**
  39830. * The viewport of the renderer in logical pixel unit.
  39831. *
  39832. * @private
  39833. * @type {Vector4}
  39834. */
  39835. this._viewport = new Vector4( 0, 0, this._width, this._height );
  39836. /**
  39837. * The scissor rectangle of the renderer in logical pixel unit.
  39838. *
  39839. * @private
  39840. * @type {Vector4}
  39841. */
  39842. this._scissor = new Vector4( 0, 0, this._width, this._height );
  39843. /**
  39844. * Whether the scissor test should be enabled or not.
  39845. *
  39846. * @private
  39847. * @type {boolean}
  39848. */
  39849. this._scissorTest = false;
  39850. /**
  39851. * The color texture of the default framebuffer.
  39852. *
  39853. * @type {FramebufferTexture}
  39854. */
  39855. this.colorTexture = new FramebufferTexture();
  39856. /**
  39857. * The depth texture of the default framebuffer.
  39858. *
  39859. * @type {DepthTexture}
  39860. */
  39861. this.depthTexture = new DepthTexture();
  39862. }
  39863. /**
  39864. * Returns the pixel ratio.
  39865. *
  39866. * @return {number} The pixel ratio.
  39867. */
  39868. getPixelRatio() {
  39869. return this._pixelRatio;
  39870. }
  39871. /**
  39872. * Returns the drawing buffer size in physical pixels. This method honors the pixel ratio.
  39873. *
  39874. * @param {Vector2} target - The method writes the result in this target object.
  39875. * @return {Vector2} The drawing buffer size.
  39876. */
  39877. getDrawingBufferSize( target ) {
  39878. return target.set( this._width * this._pixelRatio, this._height * this._pixelRatio ).floor();
  39879. }
  39880. /**
  39881. * Returns the renderer's size in logical pixels. This method does not honor the pixel ratio.
  39882. *
  39883. * @param {Vector2} target - The method writes the result in this target object.
  39884. * @return {Vector2} The renderer's size in logical pixels.
  39885. */
  39886. getSize( target ) {
  39887. return target.set( this._width, this._height );
  39888. }
  39889. /**
  39890. * Sets the given pixel ratio and resizes the canvas if necessary.
  39891. *
  39892. * @param {number} [value=1] - The pixel ratio.
  39893. */
  39894. setPixelRatio( value = 1 ) {
  39895. if ( this._pixelRatio === value ) return;
  39896. this._pixelRatio = value;
  39897. this.setSize( this._width, this._height, false );
  39898. }
  39899. /**
  39900. * This method allows to define the drawing buffer size by specifying
  39901. * width, height and pixel ratio all at once. The size of the drawing
  39902. * buffer is computed with this formula:
  39903. * ```js
  39904. * size.x = width * pixelRatio;
  39905. * size.y = height * pixelRatio;
  39906. * ```
  39907. *
  39908. * @param {number} width - The width in logical pixels.
  39909. * @param {number} height - The height in logical pixels.
  39910. * @param {number} pixelRatio - The pixel ratio.
  39911. */
  39912. setDrawingBufferSize( width, height, pixelRatio ) {
  39913. // Renderer can't be resized while presenting in XR.
  39914. if ( this.xr && this.xr.isPresenting ) return;
  39915. this._width = width;
  39916. this._height = height;
  39917. this._pixelRatio = pixelRatio;
  39918. this.domElement.width = Math.floor( width * pixelRatio );
  39919. this.domElement.height = Math.floor( height * pixelRatio );
  39920. this.setViewport( 0, 0, width, height );
  39921. this._dispatchResize();
  39922. }
  39923. /**
  39924. * Sets the size of the renderer.
  39925. *
  39926. * @param {number} width - The width in logical pixels.
  39927. * @param {number} height - The height in logical pixels.
  39928. * @param {boolean} [updateStyle=true] - Whether to update the `style` attribute of the canvas or not.
  39929. */
  39930. setSize( width, height, updateStyle = true ) {
  39931. // Renderer can't be resized while presenting in XR.
  39932. if ( this.xr && this.xr.isPresenting ) return;
  39933. this._width = width;
  39934. this._height = height;
  39935. this.domElement.width = Math.floor( width * this._pixelRatio );
  39936. this.domElement.height = Math.floor( height * this._pixelRatio );
  39937. if ( updateStyle === true ) {
  39938. this.domElement.style.width = width + 'px';
  39939. this.domElement.style.height = height + 'px';
  39940. }
  39941. this.setViewport( 0, 0, width, height );
  39942. this._dispatchResize();
  39943. }
  39944. /**
  39945. * Returns the scissor rectangle.
  39946. *
  39947. * @param {Vector4} target - The method writes the result in this target object.
  39948. * @return {Vector4} The scissor rectangle.
  39949. */
  39950. getScissor( target ) {
  39951. const scissor = this._scissor;
  39952. target.x = scissor.x;
  39953. target.y = scissor.y;
  39954. target.width = scissor.width;
  39955. target.height = scissor.height;
  39956. return target;
  39957. }
  39958. /**
  39959. * Defines the scissor rectangle.
  39960. *
  39961. * @param {number | Vector4} x - The horizontal coordinate for the lower left corner of the box in logical pixel unit.
  39962. * Instead of passing four arguments, the method also works with a single four-dimensional vector.
  39963. * @param {number} y - The vertical coordinate for the lower left corner of the box in logical pixel unit.
  39964. * @param {number} width - The width of the scissor box in logical pixel unit.
  39965. * @param {number} height - The height of the scissor box in logical pixel unit.
  39966. */
  39967. setScissor( x, y, width, height ) {
  39968. const scissor = this._scissor;
  39969. if ( x.isVector4 ) {
  39970. scissor.copy( x );
  39971. } else {
  39972. scissor.set( x, y, width, height );
  39973. }
  39974. }
  39975. /**
  39976. * Returns the scissor test value.
  39977. *
  39978. * @return {boolean} Whether the scissor test should be enabled or not.
  39979. */
  39980. getScissorTest() {
  39981. return this._scissorTest;
  39982. }
  39983. /**
  39984. * Defines the scissor test.
  39985. *
  39986. * @param {boolean} boolean - Whether the scissor test should be enabled or not.
  39987. */
  39988. setScissorTest( boolean ) {
  39989. this._scissorTest = boolean;
  39990. }
  39991. /**
  39992. * Returns the viewport definition.
  39993. *
  39994. * @param {Vector4} target - The method writes the result in this target object.
  39995. * @return {Vector4} The viewport definition.
  39996. */
  39997. getViewport( target ) {
  39998. return target.copy( this._viewport );
  39999. }
  40000. /**
  40001. * Defines the viewport.
  40002. *
  40003. * @param {number | Vector4} x - The horizontal coordinate for the lower left corner of the viewport origin in logical pixel unit.
  40004. * @param {number} y - The vertical coordinate for the lower left corner of the viewport origin in logical pixel unit.
  40005. * @param {number} width - The width of the viewport in logical pixel unit.
  40006. * @param {number} height - The height of the viewport in logical pixel unit.
  40007. * @param {number} minDepth - The minimum depth value of the viewport. WebGPU only.
  40008. * @param {number} maxDepth - The maximum depth value of the viewport. WebGPU only.
  40009. */
  40010. setViewport( x, y, width, height, minDepth = 0, maxDepth = 1 ) {
  40011. const viewport = this._viewport;
  40012. if ( x.isVector4 ) {
  40013. viewport.copy( x );
  40014. } else {
  40015. viewport.set( x, y, width, height );
  40016. }
  40017. viewport.minDepth = minDepth;
  40018. viewport.maxDepth = maxDepth;
  40019. }
  40020. /**
  40021. * Dispatches the resize event.
  40022. *
  40023. * @private
  40024. */
  40025. _dispatchResize() {
  40026. this.dispatchEvent( { type: 'resize' } );
  40027. }
  40028. /**
  40029. * Frees the GPU-related resources allocated by this instance. Call this
  40030. * method whenever this instance is no longer used in your app.
  40031. *
  40032. * @fires RenderTarget#dispose
  40033. */
  40034. dispose() {
  40035. this.dispatchEvent( { type: 'dispose' } );
  40036. }
  40037. }
  40038. const _scene = /*@__PURE__*/ new Scene();
  40039. const _drawingBufferSize = /*@__PURE__*/ new Vector2();
  40040. const _screen = /*@__PURE__*/ new Vector4();
  40041. const _frustum = /*@__PURE__*/ new Frustum();
  40042. const _frustumArray = /*@__PURE__*/ new FrustumArray();
  40043. const _projScreenMatrix = /*@__PURE__*/ new Matrix4();
  40044. const _vector4 = /*@__PURE__*/ new Vector4();
  40045. /**
  40046. * Base class for renderers.
  40047. */
  40048. class Renderer {
  40049. /**
  40050. * Renderer options.
  40051. *
  40052. * @typedef {Object} Renderer~Options
  40053. * @property {boolean} [logarithmicDepthBuffer=false] - Whether logarithmic depth buffer is enabled or not.
  40054. * @property {boolean} [alpha=true] - Whether the default framebuffer (which represents the final contents of the canvas) should be transparent or opaque.
  40055. * @property {boolean} [depth=true] - Whether the default framebuffer should have a depth buffer or not.
  40056. * @property {boolean} [stencil=false] - Whether the default framebuffer should have a stencil buffer or not.
  40057. * @property {boolean} [antialias=false] - Whether MSAA as the default anti-aliasing should be enabled or not.
  40058. * @property {number} [samples=0] - When `antialias` is `true`, `4` samples are used by default. This parameter can set to any other integer value than 0
  40059. * to overwrite the default.
  40060. * @property {?Function} [getFallback=null] - This callback function can be used to provide a fallback backend, if the primary backend can't be targeted.
  40061. * @property {number} [colorBufferType=HalfFloatType] - Defines the type of color buffers. The default `HalfFloatType` is recommend for best
  40062. * quality. To save memory and bandwidth, `UnsignedByteType` might be used. This will reduce rendering quality though.
  40063. * @property {boolean} [multiview=false] - If set to `true`, the renderer will use multiview during WebXR rendering if supported.
  40064. */
  40065. /**
  40066. * Constructs a new renderer.
  40067. *
  40068. * @param {Backend} backend - The backend the renderer is targeting (e.g. WebGPU or WebGL 2).
  40069. * @param {Renderer~Options} [parameters] - The configuration parameter.
  40070. */
  40071. constructor( backend, parameters = {} ) {
  40072. /**
  40073. * This flag can be used for type testing.
  40074. *
  40075. * @type {boolean}
  40076. * @readonly
  40077. * @default true
  40078. */
  40079. this.isRenderer = true;
  40080. //
  40081. const {
  40082. logarithmicDepthBuffer = false,
  40083. alpha = true,
  40084. depth = true,
  40085. stencil = false,
  40086. antialias = false,
  40087. samples = 0,
  40088. getFallback = null,
  40089. colorBufferType = HalfFloatType,
  40090. multiview = false
  40091. } = parameters;
  40092. /**
  40093. * A reference to the current backend.
  40094. *
  40095. * @type {Backend}
  40096. */
  40097. this.backend = backend;
  40098. /**
  40099. * Whether the renderer should automatically clear the current rendering target
  40100. * before execute a `render()` call. The target can be the canvas (default framebuffer)
  40101. * or the current bound render target (custom framebuffer).
  40102. *
  40103. * @type {boolean}
  40104. * @default true
  40105. */
  40106. this.autoClear = true;
  40107. /**
  40108. * When `autoClear` is set to `true`, this property defines whether the renderer
  40109. * should clear the color buffer.
  40110. *
  40111. * @type {boolean}
  40112. * @default true
  40113. */
  40114. this.autoClearColor = true;
  40115. /**
  40116. * When `autoClear` is set to `true`, this property defines whether the renderer
  40117. * should clear the depth buffer.
  40118. *
  40119. * @type {boolean}
  40120. * @default true
  40121. */
  40122. this.autoClearDepth = true;
  40123. /**
  40124. * When `autoClear` is set to `true`, this property defines whether the renderer
  40125. * should clear the stencil buffer.
  40126. *
  40127. * @type {boolean}
  40128. * @default true
  40129. */
  40130. this.autoClearStencil = true;
  40131. /**
  40132. * Whether the default framebuffer should be transparent or opaque.
  40133. *
  40134. * @type {boolean}
  40135. * @default true
  40136. */
  40137. this.alpha = alpha;
  40138. /**
  40139. * Whether logarithmic depth buffer is enabled or not.
  40140. *
  40141. * @type {boolean}
  40142. * @default false
  40143. */
  40144. this.logarithmicDepthBuffer = logarithmicDepthBuffer;
  40145. /**
  40146. * Defines the output color space of the renderer.
  40147. *
  40148. * @type {string}
  40149. * @default SRGBColorSpace
  40150. */
  40151. this.outputColorSpace = SRGBColorSpace;
  40152. /**
  40153. * Defines the tone mapping of the renderer.
  40154. *
  40155. * @type {number}
  40156. * @default NoToneMapping
  40157. */
  40158. this.toneMapping = NoToneMapping;
  40159. /**
  40160. * Defines the tone mapping exposure.
  40161. *
  40162. * @type {number}
  40163. * @default 1
  40164. */
  40165. this.toneMappingExposure = 1.0;
  40166. /**
  40167. * Whether the renderer should sort its render lists or not.
  40168. *
  40169. * Note: Sorting is used to attempt to properly render objects that have some degree of transparency.
  40170. * By definition, sorting objects may not work in all cases. Depending on the needs of application,
  40171. * it may be necessary to turn off sorting and use other methods to deal with transparency rendering
  40172. * e.g. manually determining each object's rendering order.
  40173. *
  40174. * @type {boolean}
  40175. * @default true
  40176. */
  40177. this.sortObjects = true;
  40178. /**
  40179. * Whether the default framebuffer should have a depth buffer or not.
  40180. *
  40181. * @type {boolean}
  40182. * @default true
  40183. */
  40184. this.depth = depth;
  40185. /**
  40186. * Whether the default framebuffer should have a stencil buffer or not.
  40187. *
  40188. * @type {boolean}
  40189. * @default false
  40190. */
  40191. this.stencil = stencil;
  40192. /**
  40193. * Holds a series of statistical information about the GPU memory
  40194. * and the rendering process. Useful for debugging and monitoring.
  40195. *
  40196. * @type {Info}
  40197. */
  40198. this.info = new Info();
  40199. /**
  40200. * Stores override nodes for specific transformations or calculations.
  40201. * These nodes can be used to replace default behavior in the rendering pipeline.
  40202. *
  40203. * @type {Object}
  40204. * @property {?Node} modelViewMatrix - An override node for the model-view matrix.
  40205. * @property {?Node} modelNormalViewMatrix - An override node for the model normal view matrix.
  40206. */
  40207. this.overrideNodes = {
  40208. modelViewMatrix: null,
  40209. modelNormalViewMatrix: null
  40210. };
  40211. /**
  40212. * The node library defines how certain library objects like materials, lights
  40213. * or tone mapping functions are mapped to node types. This is required since
  40214. * although instances of classes like `MeshBasicMaterial` or `PointLight` can
  40215. * be part of the scene graph, they are internally represented as nodes for
  40216. * further processing.
  40217. *
  40218. * @type {NodeLibrary}
  40219. */
  40220. this.library = new NodeLibrary();
  40221. /**
  40222. * A map-like data structure for managing lights.
  40223. *
  40224. * @type {Lighting}
  40225. */
  40226. this.lighting = new Lighting();
  40227. // internals
  40228. /**
  40229. * The number of MSAA samples.
  40230. *
  40231. * @private
  40232. * @type {number}
  40233. * @default 0
  40234. */
  40235. this._samples = samples || ( antialias === true ) ? 4 : 0;
  40236. /**
  40237. * OnCanvasTargetResize callback function.
  40238. *
  40239. * @private
  40240. * @type {Function}
  40241. */
  40242. this._onCanvasTargetResize = this._onCanvasTargetResize.bind( this );
  40243. /**
  40244. * The canvas target for rendering.
  40245. *
  40246. * @private
  40247. * @type {CanvasTarget}
  40248. */
  40249. this._canvasTarget = new CanvasTarget( backend.getDomElement() );
  40250. this._canvasTarget.addEventListener( 'resize', this._onCanvasTargetResize );
  40251. this._canvasTarget.isDefaultCanvasTarget = true;
  40252. /**
  40253. * The inspector provides information about the internal renderer state.
  40254. *
  40255. * @private
  40256. * @type {InspectorBase}
  40257. */
  40258. this._inspector = new InspectorBase();
  40259. this._inspector.setRenderer( this );
  40260. /**
  40261. * This callback function can be used to provide a fallback backend, if the primary backend can't be targeted.
  40262. *
  40263. * @private
  40264. * @type {?Function}
  40265. */
  40266. this._getFallback = getFallback;
  40267. /**
  40268. * A reference to a renderer module for managing shader attributes.
  40269. *
  40270. * @private
  40271. * @type {?Attributes}
  40272. * @default null
  40273. */
  40274. this._attributes = null;
  40275. /**
  40276. * A reference to a renderer module for managing geometries.
  40277. *
  40278. * @private
  40279. * @type {?Geometries}
  40280. * @default null
  40281. */
  40282. this._geometries = null;
  40283. /**
  40284. * A reference to a renderer module for managing node related logic.
  40285. *
  40286. * @private
  40287. * @type {?Nodes}
  40288. * @default null
  40289. */
  40290. this._nodes = null;
  40291. /**
  40292. * A reference to a renderer module for managing the internal animation loop.
  40293. *
  40294. * @private
  40295. * @type {?Animation}
  40296. * @default null
  40297. */
  40298. this._animation = null;
  40299. /**
  40300. * A reference to a renderer module for managing shader program bindings.
  40301. *
  40302. * @private
  40303. * @type {?Bindings}
  40304. * @default null
  40305. */
  40306. this._bindings = null;
  40307. /**
  40308. * A reference to a renderer module for managing render objects.
  40309. *
  40310. * @private
  40311. * @type {?RenderObjects}
  40312. * @default null
  40313. */
  40314. this._objects = null;
  40315. /**
  40316. * A reference to a renderer module for managing render and compute pipelines.
  40317. *
  40318. * @private
  40319. * @type {?Pipelines}
  40320. * @default null
  40321. */
  40322. this._pipelines = null;
  40323. /**
  40324. * A reference to a renderer module for managing render bundles.
  40325. *
  40326. * @private
  40327. * @type {?RenderBundles}
  40328. * @default null
  40329. */
  40330. this._bundles = null;
  40331. /**
  40332. * A reference to a renderer module for managing render lists.
  40333. *
  40334. * @private
  40335. * @type {?RenderLists}
  40336. * @default null
  40337. */
  40338. this._renderLists = null;
  40339. /**
  40340. * A reference to a renderer module for managing render contexts.
  40341. *
  40342. * @private
  40343. * @type {?RenderContexts}
  40344. * @default null
  40345. */
  40346. this._renderContexts = null;
  40347. /**
  40348. * A reference to a renderer module for managing textures.
  40349. *
  40350. * @private
  40351. * @type {?Textures}
  40352. * @default null
  40353. */
  40354. this._textures = null;
  40355. /**
  40356. * A reference to a renderer module for backgrounds.
  40357. *
  40358. * @private
  40359. * @type {?Background}
  40360. * @default null
  40361. */
  40362. this._background = null;
  40363. /**
  40364. * This fullscreen quad is used for internal render passes
  40365. * like the tone mapping and color space output pass.
  40366. *
  40367. * @private
  40368. * @type {QuadMesh}
  40369. */
  40370. this._quad = new QuadMesh( new NodeMaterial() );
  40371. this._quad.name = 'Output Color Transform';
  40372. this._quad.material.name = 'outputColorTransform';
  40373. /**
  40374. * A reference to the current render context.
  40375. *
  40376. * @private
  40377. * @type {?RenderContext}
  40378. * @default null
  40379. */
  40380. this._currentRenderContext = null;
  40381. /**
  40382. * A custom sort function for the opaque render list.
  40383. *
  40384. * @private
  40385. * @type {?Function}
  40386. * @default null
  40387. */
  40388. this._opaqueSort = null;
  40389. /**
  40390. * A custom sort function for the transparent render list.
  40391. *
  40392. * @private
  40393. * @type {?Function}
  40394. * @default null
  40395. */
  40396. this._transparentSort = null;
  40397. /**
  40398. * The framebuffer target.
  40399. *
  40400. * @private
  40401. * @type {?RenderTarget}
  40402. * @default null
  40403. */
  40404. this._frameBufferTarget = null;
  40405. const alphaClear = this.alpha === true ? 0 : 1;
  40406. /**
  40407. * The clear color value.
  40408. *
  40409. * @private
  40410. * @type {Color4}
  40411. */
  40412. this._clearColor = new Color4( 0, 0, 0, alphaClear );
  40413. /**
  40414. * The clear depth value.
  40415. *
  40416. * @private
  40417. * @type {number}
  40418. * @default 1
  40419. */
  40420. this._clearDepth = 1;
  40421. /**
  40422. * The clear stencil value.
  40423. *
  40424. * @private
  40425. * @type {number}
  40426. * @default 0
  40427. */
  40428. this._clearStencil = 0;
  40429. /**
  40430. * The current render target.
  40431. *
  40432. * @private
  40433. * @type {?RenderTarget}
  40434. * @default null
  40435. */
  40436. this._renderTarget = null;
  40437. /**
  40438. * The active cube face.
  40439. *
  40440. * @private
  40441. * @type {number}
  40442. * @default 0
  40443. */
  40444. this._activeCubeFace = 0;
  40445. /**
  40446. * The active mipmap level.
  40447. *
  40448. * @private
  40449. * @type {number}
  40450. * @default 0
  40451. */
  40452. this._activeMipmapLevel = 0;
  40453. /**
  40454. * The current output render target.
  40455. *
  40456. * @private
  40457. * @type {?RenderTarget}
  40458. * @default null
  40459. */
  40460. this._outputRenderTarget = null;
  40461. /**
  40462. * The MRT setting.
  40463. *
  40464. * @private
  40465. * @type {?MRTNode}
  40466. * @default null
  40467. */
  40468. this._mrt = null;
  40469. /**
  40470. * This function defines how a render object is going
  40471. * to be rendered.
  40472. *
  40473. * @private
  40474. * @type {?Function}
  40475. * @default null
  40476. */
  40477. this._renderObjectFunction = null;
  40478. /**
  40479. * Used to keep track of the current render object function.
  40480. *
  40481. * @private
  40482. * @type {?Function}
  40483. * @default null
  40484. */
  40485. this._currentRenderObjectFunction = null;
  40486. /**
  40487. * Used to keep track of the current render bundle.
  40488. *
  40489. * @private
  40490. * @type {?RenderBundle}
  40491. * @default null
  40492. */
  40493. this._currentRenderBundle = null;
  40494. /**
  40495. * Next to `_renderObjectFunction()`, this function provides another hook
  40496. * for influencing the render process of a render object. It is meant for internal
  40497. * use and only relevant for `compileAsync()` right now. Instead of using
  40498. * the default logic of `_renderObjectDirect()` which actually draws the render object,
  40499. * a different function might be used which performs no draw but just the node
  40500. * and pipeline updates.
  40501. *
  40502. * @private
  40503. * @type {?Function}
  40504. * @default null
  40505. */
  40506. this._handleObjectFunction = this._renderObjectDirect;
  40507. /**
  40508. * Indicates whether the device has been lost or not. In WebGL terms, the device
  40509. * lost is considered as a context lost. When this is set to `true`, rendering
  40510. * isn't possible anymore.
  40511. *
  40512. * @private
  40513. * @type {boolean}
  40514. * @default false
  40515. */
  40516. this._isDeviceLost = false;
  40517. /**
  40518. * A callback function that defines what should happen when a device/context lost occurs.
  40519. *
  40520. * @type {Function}
  40521. */
  40522. this.onDeviceLost = this._onDeviceLost;
  40523. /**
  40524. * Defines the type of color buffers. The default `HalfFloatType` is recommend for
  40525. * best quality. To save memory and bandwidth, `UnsignedByteType` might be used.
  40526. * This will reduce rendering quality though.
  40527. *
  40528. * @private
  40529. * @type {number}
  40530. * @default HalfFloatType
  40531. */
  40532. this._colorBufferType = colorBufferType;
  40533. /**
  40534. * A cache for shadow nodes per material
  40535. *
  40536. * @private
  40537. * @type {WeakMap<Material, Object>}
  40538. */
  40539. this._cacheShadowNodes = new WeakMap();
  40540. /**
  40541. * Whether the renderer has been initialized or not.
  40542. *
  40543. * @private
  40544. * @type {boolean}
  40545. * @default false
  40546. */
  40547. this._initialized = false;
  40548. /**
  40549. * A reference to the promise which initializes the renderer.
  40550. *
  40551. * @private
  40552. * @type {?Promise<this>}
  40553. * @default null
  40554. */
  40555. this._initPromise = null;
  40556. /**
  40557. * An array of compilation promises which are used in `compileAsync()`.
  40558. *
  40559. * @private
  40560. * @type {?Array<Promise>}
  40561. * @default null
  40562. */
  40563. this._compilationPromises = null;
  40564. /**
  40565. * Whether the renderer should render transparent render objects or not.
  40566. *
  40567. * @type {boolean}
  40568. * @default true
  40569. */
  40570. this.transparent = true;
  40571. /**
  40572. * Whether the renderer should render opaque render objects or not.
  40573. *
  40574. * @type {boolean}
  40575. * @default true
  40576. */
  40577. this.opaque = true;
  40578. /**
  40579. * Shadow map configuration
  40580. * @typedef {Object} ShadowMapConfig
  40581. * @property {boolean} enabled - Whether to globally enable shadows or not.
  40582. * @property {number} type - The shadow map type.
  40583. */
  40584. /**
  40585. * The renderer's shadow configuration.
  40586. *
  40587. * @type {ShadowMapConfig}
  40588. */
  40589. this.shadowMap = {
  40590. enabled: false,
  40591. type: PCFShadowMap
  40592. };
  40593. /**
  40594. * XR configuration.
  40595. * @typedef {Object} XRConfig
  40596. * @property {boolean} enabled - Whether to globally enable XR or not.
  40597. */
  40598. /**
  40599. * The renderer's XR manager.
  40600. *
  40601. * @type {XRManager}
  40602. */
  40603. this.xr = new XRManager( this, multiview );
  40604. /**
  40605. * Debug configuration.
  40606. * @typedef {Object} DebugConfig
  40607. * @property {boolean} checkShaderErrors - Whether shader errors should be checked or not.
  40608. * @property {?Function} onShaderError - A callback function that is executed when a shader error happens. Only supported with WebGL 2 right now.
  40609. * @property {Function} getShaderAsync - Allows the get the raw shader code for the given scene, camera and 3D object.
  40610. */
  40611. /**
  40612. * The renderer's debug configuration.
  40613. *
  40614. * @type {DebugConfig}
  40615. */
  40616. this.debug = {
  40617. checkShaderErrors: true,
  40618. onShaderError: null,
  40619. getShaderAsync: async ( scene, camera, object ) => {
  40620. await this.compileAsync( scene, camera );
  40621. const renderList = this._renderLists.get( scene, camera );
  40622. const renderContext = this._renderContexts.get( scene, camera, this._renderTarget );
  40623. const material = scene.overrideMaterial || object.material;
  40624. const renderObject = this._objects.get( object, material, scene, camera, renderList.lightsNode, renderContext, renderContext.clippingContext );
  40625. const { fragmentShader, vertexShader } = renderObject.getNodeBuilderState();
  40626. return { fragmentShader, vertexShader };
  40627. }
  40628. };
  40629. }
  40630. /**
  40631. * Initializes the renderer so it is ready for usage.
  40632. *
  40633. * @async
  40634. * @return {Promise<this>} A Promise that resolves when the renderer has been initialized.
  40635. */
  40636. async init() {
  40637. if ( this._initPromise !== null ) {
  40638. return this._initPromise;
  40639. }
  40640. this._initPromise = new Promise( async ( resolve, reject ) => {
  40641. let backend = this.backend;
  40642. try {
  40643. await backend.init( this );
  40644. } catch ( error ) {
  40645. if ( this._getFallback !== null ) {
  40646. // try the fallback
  40647. try {
  40648. this.backend = backend = this._getFallback( error );
  40649. await backend.init( this );
  40650. } catch ( error ) {
  40651. reject( error );
  40652. return;
  40653. }
  40654. } else {
  40655. reject( error );
  40656. return;
  40657. }
  40658. }
  40659. this._nodes = new Nodes( this, backend );
  40660. this._animation = new Animation( this, this._nodes, this.info );
  40661. this._attributes = new Attributes( backend );
  40662. this._background = new Background( this, this._nodes );
  40663. this._geometries = new Geometries( this._attributes, this.info );
  40664. this._textures = new Textures( this, backend, this.info );
  40665. this._pipelines = new Pipelines( backend, this._nodes );
  40666. this._bindings = new Bindings( backend, this._nodes, this._textures, this._attributes, this._pipelines, this.info );
  40667. this._objects = new RenderObjects( this, this._nodes, this._geometries, this._pipelines, this._bindings, this.info );
  40668. this._renderLists = new RenderLists( this.lighting );
  40669. this._bundles = new RenderBundles();
  40670. this._renderContexts = new RenderContexts();
  40671. //
  40672. this._animation.start();
  40673. this._initialized = true;
  40674. //
  40675. this._inspector.init();
  40676. //
  40677. resolve( this );
  40678. } );
  40679. return this._initPromise;
  40680. }
  40681. /**
  40682. * A reference to the canvas element the renderer is drawing to.
  40683. * This value of this property will automatically be created by
  40684. * the renderer.
  40685. *
  40686. * @type {HTMLCanvasElement|OffscreenCanvas}
  40687. */
  40688. get domElement() {
  40689. return this._canvasTarget.domElement;
  40690. }
  40691. /**
  40692. * The coordinate system of the renderer. The value of this property
  40693. * depends on the selected backend. Either `THREE.WebGLCoordinateSystem` or
  40694. * `THREE.WebGPUCoordinateSystem`.
  40695. *
  40696. * @readonly
  40697. * @type {number}
  40698. */
  40699. get coordinateSystem() {
  40700. return this.backend.coordinateSystem;
  40701. }
  40702. /**
  40703. * Compiles all materials in the given scene. This can be useful to avoid a
  40704. * phenomenon which is called "shader compilation stutter", which occurs when
  40705. * rendering an object with a new shader for the first time.
  40706. *
  40707. * If you want to add a 3D object to an existing scene, use the third optional
  40708. * parameter for applying the target scene. Note that the (target) scene's lighting
  40709. * and environment must be configured before calling this method.
  40710. *
  40711. * @async
  40712. * @param {Object3D} scene - The scene or 3D object to precompile.
  40713. * @param {Camera} camera - The camera that is used to render the scene.
  40714. * @param {?Scene} targetScene - If the first argument is a 3D object, this parameter must represent the scene the 3D object is going to be added.
  40715. * @return {Promise<Array|undefined>} A Promise that resolves when the compile has been finished.
  40716. */
  40717. async compileAsync( scene, camera, targetScene = null ) {
  40718. if ( this._isDeviceLost === true ) return;
  40719. if ( this._initialized === false ) await this.init();
  40720. // preserve render tree
  40721. const nodeFrame = this._nodes.nodeFrame;
  40722. const previousRenderId = nodeFrame.renderId;
  40723. const previousRenderContext = this._currentRenderContext;
  40724. const previousRenderObjectFunction = this._currentRenderObjectFunction;
  40725. const previousCompilationPromises = this._compilationPromises;
  40726. //
  40727. const sceneRef = ( scene.isScene === true ) ? scene : _scene;
  40728. if ( targetScene === null ) targetScene = scene;
  40729. const renderTarget = this._renderTarget;
  40730. const renderContext = this._renderContexts.get( targetScene, camera, renderTarget );
  40731. const activeMipmapLevel = this._activeMipmapLevel;
  40732. const compilationPromises = [];
  40733. this._currentRenderContext = renderContext;
  40734. this._currentRenderObjectFunction = this.renderObject;
  40735. this._handleObjectFunction = this._createObjectPipeline;
  40736. this._compilationPromises = compilationPromises;
  40737. nodeFrame.renderId ++;
  40738. //
  40739. nodeFrame.update();
  40740. //
  40741. renderContext.depth = this.depth;
  40742. renderContext.stencil = this.stencil;
  40743. if ( ! renderContext.clippingContext ) renderContext.clippingContext = new ClippingContext();
  40744. renderContext.clippingContext.updateGlobal( sceneRef, camera );
  40745. //
  40746. sceneRef.onBeforeRender( this, scene, camera, renderTarget );
  40747. //
  40748. const renderList = this._renderLists.get( scene, camera );
  40749. renderList.begin();
  40750. this._projectObject( scene, camera, 0, renderList, renderContext.clippingContext );
  40751. // include lights from target scene
  40752. if ( targetScene !== scene ) {
  40753. targetScene.traverseVisible( function ( object ) {
  40754. if ( object.isLight && object.layers.test( camera.layers ) ) {
  40755. renderList.pushLight( object );
  40756. }
  40757. } );
  40758. }
  40759. renderList.finish();
  40760. //
  40761. if ( renderTarget !== null ) {
  40762. this._textures.updateRenderTarget( renderTarget, activeMipmapLevel );
  40763. const renderTargetData = this._textures.get( renderTarget );
  40764. renderContext.textures = renderTargetData.textures;
  40765. renderContext.depthTexture = renderTargetData.depthTexture;
  40766. } else {
  40767. renderContext.textures = null;
  40768. renderContext.depthTexture = null;
  40769. }
  40770. //
  40771. this._background.update( sceneRef, renderList, renderContext );
  40772. // process render lists
  40773. const opaqueObjects = renderList.opaque;
  40774. const transparentObjects = renderList.transparent;
  40775. const transparentDoublePassObjects = renderList.transparentDoublePass;
  40776. const lightsNode = renderList.lightsNode;
  40777. if ( this.opaque === true && opaqueObjects.length > 0 ) this._renderObjects( opaqueObjects, camera, sceneRef, lightsNode );
  40778. if ( this.transparent === true && transparentObjects.length > 0 ) this._renderTransparents( transparentObjects, transparentDoublePassObjects, camera, sceneRef, lightsNode );
  40779. // restore render tree
  40780. nodeFrame.renderId = previousRenderId;
  40781. this._currentRenderContext = previousRenderContext;
  40782. this._currentRenderObjectFunction = previousRenderObjectFunction;
  40783. this._compilationPromises = previousCompilationPromises;
  40784. this._handleObjectFunction = this._renderObjectDirect;
  40785. // wait for all promises setup by backends awaiting compilation/linking/pipeline creation to complete
  40786. await Promise.all( compilationPromises );
  40787. }
  40788. /**
  40789. * Renders the scene in an async fashion.
  40790. *
  40791. * @async
  40792. * @deprecated
  40793. * @param {Object3D} scene - The scene or 3D object to render.
  40794. * @param {Camera} camera - The camera.
  40795. * @return {Promise} A Promise that resolves when the render has been finished.
  40796. */
  40797. async renderAsync( scene, camera ) {
  40798. warnOnce( 'Renderer: "renderAsync()" has been deprecated. Use "render()" and "await renderer.init();" when creating the renderer.' ); // @deprecated r181
  40799. await this.init();
  40800. this.render( scene, camera );
  40801. }
  40802. /**
  40803. * Can be used to synchronize CPU operations with GPU tasks. So when this method is called,
  40804. * the CPU waits for the GPU to complete its operation (e.g. a compute task).
  40805. *
  40806. * @async
  40807. * @deprecated
  40808. * @return {Promise} A Promise that resolves when synchronization has been finished.
  40809. */
  40810. async waitForGPU() {
  40811. error( 'Renderer: waitForGPU() has been removed. Read https://github.com/mrdoob/three.js/issues/32012 for more information.' );
  40812. }
  40813. //
  40814. set inspector( value ) {
  40815. if ( this._inspector !== null ) {
  40816. this._inspector.setRenderer( null );
  40817. }
  40818. this._inspector = value;
  40819. this._inspector.setRenderer( this );
  40820. }
  40821. /**
  40822. * The inspector instance. The inspector can be any class that extends from `InspectorBase`.
  40823. *
  40824. * @type {InspectorBase}
  40825. */
  40826. get inspector() {
  40827. return this._inspector;
  40828. }
  40829. /**
  40830. * Enables or disables high precision for model-view and normal-view matrices.
  40831. * When enabled, will use CPU 64-bit precision for higher precision instead of GPU 32-bit for higher performance.
  40832. *
  40833. * NOTE: 64-bit precision is not compatible with `InstancedMesh` and `SkinnedMesh`.
  40834. *
  40835. * @param {boolean} value - Whether to enable or disable high precision.
  40836. * @type {boolean}
  40837. */
  40838. set highPrecision( value ) {
  40839. if ( value === true ) {
  40840. this.overrideNodes.modelViewMatrix = highpModelViewMatrix;
  40841. this.overrideNodes.modelNormalViewMatrix = highpModelNormalViewMatrix;
  40842. } else if ( this.highPrecision ) {
  40843. this.overrideNodes.modelViewMatrix = null;
  40844. this.overrideNodes.modelNormalViewMatrix = null;
  40845. }
  40846. }
  40847. /**
  40848. * Returns whether high precision is enabled or not.
  40849. *
  40850. * @return {boolean} Whether high precision is enabled or not.
  40851. * @type {boolean}
  40852. */
  40853. get highPrecision() {
  40854. return this.overrideNodes.modelViewMatrix === highpModelViewMatrix && this.overrideNodes.modelNormalViewMatrix === highpModelNormalViewMatrix;
  40855. }
  40856. /**
  40857. * Sets the given MRT configuration.
  40858. *
  40859. * @param {MRTNode} mrt - The MRT node to set.
  40860. * @return {Renderer} A reference to this renderer.
  40861. */
  40862. setMRT( mrt ) {
  40863. this._mrt = mrt;
  40864. return this;
  40865. }
  40866. /**
  40867. * Returns the MRT configuration.
  40868. *
  40869. * @return {MRTNode} The MRT configuration.
  40870. */
  40871. getMRT() {
  40872. return this._mrt;
  40873. }
  40874. /**
  40875. * Returns the color buffer type.
  40876. *
  40877. * @return {number} The color buffer type.
  40878. */
  40879. getColorBufferType() {
  40880. return this._colorBufferType;
  40881. }
  40882. /**
  40883. * Default implementation of the device lost callback.
  40884. *
  40885. * @private
  40886. * @param {Object} info - Information about the context lost.
  40887. */
  40888. _onDeviceLost( info ) {
  40889. let errorMessage = `THREE.WebGPURenderer: ${info.api} Device Lost:\n\nMessage: ${info.message}`;
  40890. if ( info.reason ) {
  40891. errorMessage += `\nReason: ${info.reason}`;
  40892. }
  40893. error( errorMessage );
  40894. this._isDeviceLost = true;
  40895. }
  40896. /**
  40897. * Renders the given render bundle.
  40898. *
  40899. * @private
  40900. * @param {Object} bundle - Render bundle data.
  40901. * @param {Scene} sceneRef - The scene the render bundle belongs to.
  40902. * @param {LightsNode} lightsNode - The lights node.
  40903. */
  40904. _renderBundle( bundle, sceneRef, lightsNode ) {
  40905. const { bundleGroup, camera, renderList } = bundle;
  40906. const renderContext = this._currentRenderContext;
  40907. //
  40908. const renderBundle = this._bundles.get( bundleGroup, camera );
  40909. const renderBundleData = this.backend.get( renderBundle );
  40910. if ( renderBundleData.renderContexts === undefined ) renderBundleData.renderContexts = new Set();
  40911. //
  40912. const needsUpdate = bundleGroup.version !== renderBundleData.version;
  40913. const renderBundleNeedsUpdate = renderBundleData.renderContexts.has( renderContext ) === false || needsUpdate;
  40914. renderBundleData.renderContexts.add( renderContext );
  40915. if ( renderBundleNeedsUpdate ) {
  40916. this.backend.beginBundle( renderContext );
  40917. if ( renderBundleData.renderObjects === undefined || needsUpdate ) {
  40918. renderBundleData.renderObjects = [];
  40919. }
  40920. this._currentRenderBundle = renderBundle;
  40921. const {
  40922. transparentDoublePass: transparentDoublePassObjects,
  40923. transparent: transparentObjects,
  40924. opaque: opaqueObjects
  40925. } = renderList;
  40926. if ( this.opaque === true && opaqueObjects.length > 0 ) this._renderObjects( opaqueObjects, camera, sceneRef, lightsNode );
  40927. if ( this.transparent === true && transparentObjects.length > 0 ) this._renderTransparents( transparentObjects, transparentDoublePassObjects, camera, sceneRef, lightsNode );
  40928. this._currentRenderBundle = null;
  40929. //
  40930. this.backend.finishBundle( renderContext, renderBundle );
  40931. renderBundleData.version = bundleGroup.version;
  40932. } else {
  40933. const { renderObjects } = renderBundleData;
  40934. for ( let i = 0, l = renderObjects.length; i < l; i ++ ) {
  40935. const renderObject = renderObjects[ i ];
  40936. if ( this._nodes.needsRefresh( renderObject ) ) {
  40937. this._nodes.updateBefore( renderObject );
  40938. this._nodes.updateForRender( renderObject );
  40939. this._bindings.updateForRender( renderObject );
  40940. this._nodes.updateAfter( renderObject );
  40941. }
  40942. }
  40943. }
  40944. this.backend.addBundle( renderContext, renderBundle );
  40945. }
  40946. /**
  40947. * Renders the scene or 3D object with the given camera. This method can only be called
  40948. * if the renderer has been initialized. When using `render()` inside an animation loop,
  40949. * it's guaranteed the renderer will be initialized. The animation loop must be defined
  40950. * with {@link Renderer#setAnimationLoop} though.
  40951. *
  40952. * For all other use cases (like when using on-demand rendering), you must call
  40953. * {@link Renderer#init} before rendering.
  40954. *
  40955. * The target of the method is the default framebuffer (meaning the canvas)
  40956. * or alternatively a render target when specified via `setRenderTarget()`.
  40957. *
  40958. * @param {Object3D} scene - The scene or 3D object to render.
  40959. * @param {Camera} camera - The camera to render the scene with.
  40960. */
  40961. render( scene, camera ) {
  40962. if ( this._initialized === false ) {
  40963. throw new Error( 'Renderer: .render() called before the backend is initialized. Use "await renderer.init();" before rendering.' );
  40964. }
  40965. this._renderScene( scene, camera );
  40966. }
  40967. /**
  40968. * Returns whether the renderer has been initialized or not.
  40969. *
  40970. * @readonly
  40971. * @return {boolean} Whether the renderer has been initialized or not.
  40972. */
  40973. get initialized() {
  40974. return this._initialized;
  40975. }
  40976. /**
  40977. * Returns an internal render target which is used when computing the output tone mapping
  40978. * and color space conversion. Unlike in `WebGLRenderer`, this is done in a separate render
  40979. * pass and not inline to achieve more correct results.
  40980. *
  40981. * @private
  40982. * @return {?RenderTarget} The render target. The method returns `null` if no output conversion should be applied.
  40983. */
  40984. _getFrameBufferTarget() {
  40985. const { currentToneMapping, currentColorSpace } = this;
  40986. const useToneMapping = currentToneMapping !== NoToneMapping;
  40987. const useColorSpace = currentColorSpace !== ColorManagement.workingColorSpace;
  40988. if ( useToneMapping === false && useColorSpace === false ) return null;
  40989. const { width, height } = this.getDrawingBufferSize( _drawingBufferSize );
  40990. const { depth, stencil } = this;
  40991. let frameBufferTarget = this._frameBufferTarget;
  40992. if ( frameBufferTarget === null ) {
  40993. frameBufferTarget = new RenderTarget( width, height, {
  40994. depthBuffer: depth,
  40995. stencilBuffer: stencil,
  40996. type: this._colorBufferType,
  40997. format: RGBAFormat,
  40998. colorSpace: ColorManagement.workingColorSpace,
  40999. generateMipmaps: false,
  41000. minFilter: LinearFilter,
  41001. magFilter: LinearFilter,
  41002. samples: this.samples
  41003. } );
  41004. frameBufferTarget.isPostProcessingRenderTarget = true;
  41005. this._frameBufferTarget = frameBufferTarget;
  41006. }
  41007. const outputRenderTarget = this.getOutputRenderTarget();
  41008. frameBufferTarget.depthBuffer = depth;
  41009. frameBufferTarget.stencilBuffer = stencil;
  41010. if ( outputRenderTarget !== null ) {
  41011. frameBufferTarget.setSize( outputRenderTarget.width, outputRenderTarget.height, outputRenderTarget.depth );
  41012. } else {
  41013. frameBufferTarget.setSize( width, height, 1 );
  41014. }
  41015. const canvasTarget = this._canvasTarget;
  41016. frameBufferTarget.viewport.copy( canvasTarget._viewport );
  41017. frameBufferTarget.scissor.copy( canvasTarget._scissor );
  41018. frameBufferTarget.viewport.multiplyScalar( canvasTarget._pixelRatio );
  41019. frameBufferTarget.scissor.multiplyScalar( canvasTarget._pixelRatio );
  41020. frameBufferTarget.scissorTest = canvasTarget._scissorTest;
  41021. frameBufferTarget.multiview = outputRenderTarget !== null ? outputRenderTarget.multiview : false;
  41022. frameBufferTarget.resolveDepthBuffer = outputRenderTarget !== null ? outputRenderTarget.resolveDepthBuffer : true;
  41023. frameBufferTarget._autoAllocateDepthBuffer = outputRenderTarget !== null ? outputRenderTarget._autoAllocateDepthBuffer : false;
  41024. return frameBufferTarget;
  41025. }
  41026. /**
  41027. * Renders the scene or 3D object with the given camera.
  41028. *
  41029. * @private
  41030. * @param {Object3D} scene - The scene or 3D object to render.
  41031. * @param {Camera} camera - The camera to render the scene with.
  41032. * @param {boolean} [useFrameBufferTarget=true] - Whether to use a framebuffer target or not.
  41033. * @return {RenderContext} The current render context.
  41034. */
  41035. _renderScene( scene, camera, useFrameBufferTarget = true ) {
  41036. if ( this._isDeviceLost === true ) return;
  41037. //
  41038. const frameBufferTarget = useFrameBufferTarget ? this._getFrameBufferTarget() : null;
  41039. // preserve render tree
  41040. const nodeFrame = this._nodes.nodeFrame;
  41041. const previousRenderId = nodeFrame.renderId;
  41042. const previousRenderContext = this._currentRenderContext;
  41043. const previousRenderObjectFunction = this._currentRenderObjectFunction;
  41044. //
  41045. const sceneRef = ( scene.isScene === true ) ? scene : _scene;
  41046. const outputRenderTarget = this._renderTarget || this._outputRenderTarget;
  41047. const activeCubeFace = this._activeCubeFace;
  41048. const activeMipmapLevel = this._activeMipmapLevel;
  41049. //
  41050. let renderTarget;
  41051. if ( frameBufferTarget !== null ) {
  41052. renderTarget = frameBufferTarget;
  41053. this.setRenderTarget( renderTarget );
  41054. } else {
  41055. renderTarget = outputRenderTarget;
  41056. }
  41057. //
  41058. const renderContext = this._renderContexts.get( scene, camera, renderTarget );
  41059. this._currentRenderContext = renderContext;
  41060. this._currentRenderObjectFunction = this._renderObjectFunction || this.renderObject;
  41061. //
  41062. this.info.calls ++;
  41063. this.info.render.calls ++;
  41064. this.info.render.frameCalls ++;
  41065. nodeFrame.renderId = this.info.calls;
  41066. //
  41067. this.backend.updateTimeStampUID( renderContext );
  41068. this.inspector.beginRender( this.backend.getTimestampUID( renderContext ), scene, camera, renderTarget );
  41069. //
  41070. const coordinateSystem = this.coordinateSystem;
  41071. const xr = this.xr;
  41072. if ( camera.coordinateSystem !== coordinateSystem && xr.isPresenting === false ) {
  41073. camera.coordinateSystem = coordinateSystem;
  41074. camera.updateProjectionMatrix();
  41075. if ( camera.isArrayCamera ) {
  41076. for ( const subCamera of camera.cameras ) {
  41077. subCamera.coordinateSystem = coordinateSystem;
  41078. subCamera.updateProjectionMatrix();
  41079. }
  41080. }
  41081. }
  41082. //
  41083. if ( scene.matrixWorldAutoUpdate === true ) scene.updateMatrixWorld();
  41084. if ( camera.parent === null && camera.matrixWorldAutoUpdate === true ) camera.updateMatrixWorld();
  41085. if ( xr.enabled === true && xr.isPresenting === true ) {
  41086. if ( xr.cameraAutoUpdate === true ) xr.updateCamera( camera );
  41087. camera = xr.getCamera(); // use XR camera for rendering
  41088. }
  41089. //
  41090. const canvasTarget = this._canvasTarget;
  41091. let viewport = canvasTarget._viewport;
  41092. let scissor = canvasTarget._scissor;
  41093. let pixelRatio = canvasTarget._pixelRatio;
  41094. if ( renderTarget !== null ) {
  41095. viewport = renderTarget.viewport;
  41096. scissor = renderTarget.scissor;
  41097. pixelRatio = 1;
  41098. }
  41099. this.getDrawingBufferSize( _drawingBufferSize );
  41100. _screen.set( 0, 0, _drawingBufferSize.width, _drawingBufferSize.height );
  41101. const minDepth = ( viewport.minDepth === undefined ) ? 0 : viewport.minDepth;
  41102. const maxDepth = ( viewport.maxDepth === undefined ) ? 1 : viewport.maxDepth;
  41103. renderContext.viewportValue.copy( viewport ).multiplyScalar( pixelRatio ).floor();
  41104. renderContext.viewportValue.width >>= activeMipmapLevel;
  41105. renderContext.viewportValue.height >>= activeMipmapLevel;
  41106. renderContext.viewportValue.minDepth = minDepth;
  41107. renderContext.viewportValue.maxDepth = maxDepth;
  41108. renderContext.viewport = renderContext.viewportValue.equals( _screen ) === false;
  41109. renderContext.scissorValue.copy( scissor ).multiplyScalar( pixelRatio ).floor();
  41110. renderContext.scissor = canvasTarget._scissorTest && renderContext.scissorValue.equals( _screen ) === false;
  41111. renderContext.scissorValue.width >>= activeMipmapLevel;
  41112. renderContext.scissorValue.height >>= activeMipmapLevel;
  41113. if ( ! renderContext.clippingContext ) renderContext.clippingContext = new ClippingContext();
  41114. renderContext.clippingContext.updateGlobal( sceneRef, camera );
  41115. //
  41116. sceneRef.onBeforeRender( this, scene, camera, renderTarget );
  41117. //
  41118. const frustum = camera.isArrayCamera ? _frustumArray : _frustum;
  41119. if ( ! camera.isArrayCamera ) {
  41120. _projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
  41121. frustum.setFromProjectionMatrix( _projScreenMatrix, camera.coordinateSystem, camera.reversedDepth );
  41122. }
  41123. const renderList = this._renderLists.get( scene, camera );
  41124. renderList.begin();
  41125. this._projectObject( scene, camera, 0, renderList, renderContext.clippingContext );
  41126. renderList.finish();
  41127. if ( this.sortObjects === true ) {
  41128. renderList.sort( this._opaqueSort, this._transparentSort );
  41129. }
  41130. //
  41131. if ( renderTarget !== null ) {
  41132. this._textures.updateRenderTarget( renderTarget, activeMipmapLevel );
  41133. const renderTargetData = this._textures.get( renderTarget );
  41134. renderContext.textures = renderTargetData.textures;
  41135. renderContext.depthTexture = renderTargetData.depthTexture;
  41136. renderContext.width = renderTargetData.width;
  41137. renderContext.height = renderTargetData.height;
  41138. renderContext.renderTarget = renderTarget;
  41139. renderContext.depth = renderTarget.depthBuffer;
  41140. renderContext.stencil = renderTarget.stencilBuffer;
  41141. } else {
  41142. renderContext.textures = null;
  41143. renderContext.depthTexture = null;
  41144. renderContext.width = _drawingBufferSize.width;
  41145. renderContext.height = _drawingBufferSize.height;
  41146. renderContext.depth = this.depth;
  41147. renderContext.stencil = this.stencil;
  41148. }
  41149. renderContext.width >>= activeMipmapLevel;
  41150. renderContext.height >>= activeMipmapLevel;
  41151. renderContext.activeCubeFace = activeCubeFace;
  41152. renderContext.activeMipmapLevel = activeMipmapLevel;
  41153. renderContext.occlusionQueryCount = renderList.occlusionQueryCount;
  41154. //
  41155. renderContext.scissorValue.max( _vector4.set( 0, 0, 0, 0 ) );
  41156. if ( renderContext.scissorValue.x + renderContext.scissorValue.width > renderContext.width ) {
  41157. renderContext.scissorValue.width = Math.max( renderContext.width - renderContext.scissorValue.x, 0 );
  41158. }
  41159. if ( renderContext.scissorValue.y + renderContext.scissorValue.height > renderContext.height ) {
  41160. renderContext.scissorValue.height = Math.max( renderContext.height - renderContext.scissorValue.y, 0 );
  41161. }
  41162. //
  41163. this._background.update( sceneRef, renderList, renderContext );
  41164. //
  41165. renderContext.camera = camera;
  41166. this.backend.beginRender( renderContext );
  41167. // process render lists
  41168. const {
  41169. bundles,
  41170. lightsNode,
  41171. transparentDoublePass: transparentDoublePassObjects,
  41172. transparent: transparentObjects,
  41173. opaque: opaqueObjects
  41174. } = renderList;
  41175. if ( bundles.length > 0 ) this._renderBundles( bundles, sceneRef, lightsNode );
  41176. if ( this.opaque === true && opaqueObjects.length > 0 ) this._renderObjects( opaqueObjects, camera, sceneRef, lightsNode );
  41177. if ( this.transparent === true && transparentObjects.length > 0 ) this._renderTransparents( transparentObjects, transparentDoublePassObjects, camera, sceneRef, lightsNode );
  41178. // finish render pass
  41179. this.backend.finishRender( renderContext );
  41180. // restore render tree
  41181. nodeFrame.renderId = previousRenderId;
  41182. this._currentRenderContext = previousRenderContext;
  41183. this._currentRenderObjectFunction = previousRenderObjectFunction;
  41184. //
  41185. if ( frameBufferTarget !== null ) {
  41186. this.setRenderTarget( outputRenderTarget, activeCubeFace, activeMipmapLevel );
  41187. this._renderOutput( renderTarget );
  41188. }
  41189. //
  41190. sceneRef.onAfterRender( this, scene, camera, renderTarget );
  41191. //
  41192. this.inspector.finishRender( this.backend.getTimestampUID( renderContext ) );
  41193. //
  41194. return renderContext;
  41195. }
  41196. _setXRLayerSize( width, height ) {
  41197. // TODO: Find a better solution to resize the canvas when in XR.
  41198. this._canvasTarget._width = width;
  41199. this._canvasTarget._height = height;
  41200. this.setViewport( 0, 0, width, height );
  41201. }
  41202. /**
  41203. * The output pass performs tone mapping and color space conversion.
  41204. *
  41205. * @private
  41206. * @param {RenderTarget} renderTarget - The current render target.
  41207. */
  41208. _renderOutput( renderTarget ) {
  41209. const quad = this._quad;
  41210. if ( this._nodes.hasOutputChange( renderTarget.texture ) ) {
  41211. quad.material.fragmentNode = this._nodes.getOutputNode( renderTarget.texture );
  41212. quad.material.needsUpdate = true;
  41213. }
  41214. // a clear operation clears the intermediate renderTarget texture, but should not update the screen canvas.
  41215. const currentAutoClear = this.autoClear;
  41216. const currentXR = this.xr.enabled;
  41217. this.autoClear = false;
  41218. this.xr.enabled = false;
  41219. this._renderScene( quad, quad.camera, false );
  41220. this.autoClear = currentAutoClear;
  41221. this.xr.enabled = currentXR;
  41222. }
  41223. /**
  41224. * Returns the maximum available anisotropy for texture filtering.
  41225. *
  41226. * @return {number} The maximum available anisotropy.
  41227. */
  41228. getMaxAnisotropy() {
  41229. return this.backend.getMaxAnisotropy();
  41230. }
  41231. /**
  41232. * Returns the active cube face.
  41233. *
  41234. * @return {number} The active cube face.
  41235. */
  41236. getActiveCubeFace() {
  41237. return this._activeCubeFace;
  41238. }
  41239. /**
  41240. * Returns the active mipmap level.
  41241. *
  41242. * @return {number} The active mipmap level.
  41243. */
  41244. getActiveMipmapLevel() {
  41245. return this._activeMipmapLevel;
  41246. }
  41247. /**
  41248. * Applications are advised to always define the animation loop
  41249. * with this method and not manually with `requestAnimationFrame()`
  41250. * for best compatibility.
  41251. *
  41252. * @async
  41253. * @param {?onAnimationCallback} callback - The application's animation loop.
  41254. * @return {Promise} A Promise that resolves when the set has been executed.
  41255. */
  41256. async setAnimationLoop( callback ) {
  41257. if ( this._initialized === false ) await this.init();
  41258. this._animation.setAnimationLoop( callback );
  41259. }
  41260. /**
  41261. * Returns the current animation loop callback.
  41262. *
  41263. * @return {?Function} The current animation loop callback.
  41264. */
  41265. getAnimationLoop() {
  41266. return this._animation.getAnimationLoop();
  41267. }
  41268. /**
  41269. * Can be used to transfer buffer data from a storage buffer attribute
  41270. * from the GPU to the CPU in context of compute shaders.
  41271. *
  41272. * @async
  41273. * @param {StorageBufferAttribute} attribute - The storage buffer attribute.
  41274. * @return {Promise<ArrayBuffer>} A promise that resolves with the buffer data when the data are ready.
  41275. */
  41276. async getArrayBufferAsync( attribute ) {
  41277. return await this.backend.getArrayBufferAsync( attribute );
  41278. }
  41279. /**
  41280. * Returns the rendering context.
  41281. *
  41282. * @return {GPUCanvasContext|WebGL2RenderingContext} The rendering context.
  41283. */
  41284. getContext() {
  41285. return this.backend.getContext();
  41286. }
  41287. /**
  41288. * Returns the pixel ratio.
  41289. *
  41290. * @return {number} The pixel ratio.
  41291. */
  41292. getPixelRatio() {
  41293. return this._canvasTarget.getPixelRatio();
  41294. }
  41295. /**
  41296. * Returns the drawing buffer size in physical pixels. This method honors the pixel ratio.
  41297. *
  41298. * @param {Vector2} target - The method writes the result in this target object.
  41299. * @return {Vector2} The drawing buffer size.
  41300. */
  41301. getDrawingBufferSize( target ) {
  41302. return this._canvasTarget.getDrawingBufferSize( target );
  41303. }
  41304. /**
  41305. * Returns the renderer's size in logical pixels. This method does not honor the pixel ratio.
  41306. *
  41307. * @param {Vector2} target - The method writes the result in this target object.
  41308. * @return {Vector2} The renderer's size in logical pixels.
  41309. */
  41310. getSize( target ) {
  41311. return this._canvasTarget.getSize( target );
  41312. }
  41313. /**
  41314. * Sets the given pixel ratio and resizes the canvas if necessary.
  41315. *
  41316. * @param {number} [value=1] - The pixel ratio.
  41317. */
  41318. setPixelRatio( value = 1 ) {
  41319. this._canvasTarget.setPixelRatio( value );
  41320. }
  41321. /**
  41322. * This method allows to define the drawing buffer size by specifying
  41323. * width, height and pixel ratio all at once. The size of the drawing
  41324. * buffer is computed with this formula:
  41325. * ```js
  41326. * size.x = width * pixelRatio;
  41327. * size.y = height * pixelRatio;
  41328. * ```
  41329. *
  41330. * @param {number} width - The width in logical pixels.
  41331. * @param {number} height - The height in logical pixels.
  41332. * @param {number} pixelRatio - The pixel ratio.
  41333. */
  41334. setDrawingBufferSize( width, height, pixelRatio ) {
  41335. // Renderer can't be resized while presenting in XR.
  41336. if ( this.xr && this.xr.isPresenting ) return;
  41337. this._canvasTarget.setDrawingBufferSize( width, height, pixelRatio );
  41338. }
  41339. /**
  41340. * Sets the size of the renderer.
  41341. *
  41342. * @param {number} width - The width in logical pixels.
  41343. * @param {number} height - The height in logical pixels.
  41344. * @param {boolean} [updateStyle=true] - Whether to update the `style` attribute of the canvas or not.
  41345. */
  41346. setSize( width, height, updateStyle = true ) {
  41347. // Renderer can't be resized while presenting in XR.
  41348. if ( this.xr && this.xr.isPresenting ) return;
  41349. this._canvasTarget.setSize( width, height, updateStyle );
  41350. }
  41351. /**
  41352. * Defines a manual sort function for the opaque render list.
  41353. * Pass `null` to use the default sort.
  41354. *
  41355. * @param {Function} method - The sort function.
  41356. */
  41357. setOpaqueSort( method ) {
  41358. this._opaqueSort = method;
  41359. }
  41360. /**
  41361. * Defines a manual sort function for the transparent render list.
  41362. * Pass `null` to use the default sort.
  41363. *
  41364. * @param {Function} method - The sort function.
  41365. */
  41366. setTransparentSort( method ) {
  41367. this._transparentSort = method;
  41368. }
  41369. /**
  41370. * Returns the scissor rectangle.
  41371. *
  41372. * @param {Vector4} target - The method writes the result in this target object.
  41373. * @return {Vector4} The scissor rectangle.
  41374. */
  41375. getScissor( target ) {
  41376. return this._canvasTarget.getScissor( target );
  41377. }
  41378. /**
  41379. * Defines the scissor rectangle.
  41380. *
  41381. * @param {number | Vector4} x - The horizontal coordinate for the lower left corner of the box in logical pixel unit.
  41382. * Instead of passing four arguments, the method also works with a single four-dimensional vector.
  41383. * @param {number} y - The vertical coordinate for the lower left corner of the box in logical pixel unit.
  41384. * @param {number} width - The width of the scissor box in logical pixel unit.
  41385. * @param {number} height - The height of the scissor box in logical pixel unit.
  41386. */
  41387. setScissor( x, y, width, height ) {
  41388. this._canvasTarget.setScissor( x, y, width, height );
  41389. }
  41390. /**
  41391. * Returns the scissor test value.
  41392. *
  41393. * @return {boolean} Whether the scissor test should be enabled or not.
  41394. */
  41395. getScissorTest() {
  41396. return this._canvasTarget.getScissorTest();
  41397. }
  41398. /**
  41399. * Defines the scissor test.
  41400. *
  41401. * @param {boolean} boolean - Whether the scissor test should be enabled or not.
  41402. */
  41403. setScissorTest( boolean ) {
  41404. this._canvasTarget.setScissorTest( boolean );
  41405. // TODO: Move it to CanvasTarget event listener.
  41406. this.backend.setScissorTest( boolean );
  41407. }
  41408. /**
  41409. * Returns the viewport definition.
  41410. *
  41411. * @param {Vector4} target - The method writes the result in this target object.
  41412. * @return {Vector4} The viewport definition.
  41413. */
  41414. getViewport( target ) {
  41415. return this._canvasTarget.getViewport( target );
  41416. }
  41417. /**
  41418. * Defines the viewport.
  41419. *
  41420. * @param {number | Vector4} x - The horizontal coordinate for the lower left corner of the viewport origin in logical pixel unit.
  41421. * @param {number} y - The vertical coordinate for the lower left corner of the viewport origin in logical pixel unit.
  41422. * @param {number} width - The width of the viewport in logical pixel unit.
  41423. * @param {number} height - The height of the viewport in logical pixel unit.
  41424. * @param {number} minDepth - The minimum depth value of the viewport. WebGPU only.
  41425. * @param {number} maxDepth - The maximum depth value of the viewport. WebGPU only.
  41426. */
  41427. setViewport( x, y, width, height, minDepth = 0, maxDepth = 1 ) {
  41428. this._canvasTarget.setViewport( x, y, width, height, minDepth, maxDepth );
  41429. }
  41430. /**
  41431. * Returns the clear color.
  41432. *
  41433. * @param {Color} target - The method writes the result in this target object.
  41434. * @return {Color} The clear color.
  41435. */
  41436. getClearColor( target ) {
  41437. return target.copy( this._clearColor );
  41438. }
  41439. /**
  41440. * Defines the clear color and optionally the clear alpha.
  41441. *
  41442. * @param {Color} color - The clear color.
  41443. * @param {number} [alpha=1] - The clear alpha.
  41444. */
  41445. setClearColor( color, alpha = 1 ) {
  41446. this._clearColor.set( color );
  41447. this._clearColor.a = alpha;
  41448. }
  41449. /**
  41450. * Returns the clear alpha.
  41451. *
  41452. * @return {number} The clear alpha.
  41453. */
  41454. getClearAlpha() {
  41455. return this._clearColor.a;
  41456. }
  41457. /**
  41458. * Defines the clear alpha.
  41459. *
  41460. * @param {number} alpha - The clear alpha.
  41461. */
  41462. setClearAlpha( alpha ) {
  41463. this._clearColor.a = alpha;
  41464. }
  41465. /**
  41466. * Returns the clear depth.
  41467. *
  41468. * @return {number} The clear depth.
  41469. */
  41470. getClearDepth() {
  41471. return this._clearDepth;
  41472. }
  41473. /**
  41474. * Defines the clear depth.
  41475. *
  41476. * @param {number} depth - The clear depth.
  41477. */
  41478. setClearDepth( depth ) {
  41479. this._clearDepth = depth;
  41480. }
  41481. /**
  41482. * Returns the clear stencil.
  41483. *
  41484. * @return {number} The clear stencil.
  41485. */
  41486. getClearStencil() {
  41487. return this._clearStencil;
  41488. }
  41489. /**
  41490. * Defines the clear stencil.
  41491. *
  41492. * @param {number} stencil - The clear stencil.
  41493. */
  41494. setClearStencil( stencil ) {
  41495. this._clearStencil = stencil;
  41496. }
  41497. /**
  41498. * This method performs an occlusion query for the given 3D object.
  41499. * It returns `true` if the given 3D object is fully occluded by other
  41500. * 3D objects in the scene.
  41501. *
  41502. * @param {Object3D} object - The 3D object to test.
  41503. * @return {boolean} Whether the 3D object is fully occluded or not.
  41504. */
  41505. isOccluded( object ) {
  41506. const renderContext = this._currentRenderContext;
  41507. return renderContext && this.backend.isOccluded( renderContext, object );
  41508. }
  41509. /**
  41510. * Performs a manual clear operation. This method ignores `autoClear` properties.
  41511. *
  41512. * @param {boolean} [color=true] - Whether the color buffer should be cleared or not.
  41513. * @param {boolean} [depth=true] - Whether the depth buffer should be cleared or not.
  41514. * @param {boolean} [stencil=true] - Whether the stencil buffer should be cleared or not.
  41515. */
  41516. clear( color = true, depth = true, stencil = true ) {
  41517. if ( this._initialized === false ) {
  41518. throw new Error( 'Renderer: .clear() called before the backend is initialized. Use "await renderer.init();" before before using this method.' );
  41519. }
  41520. const renderTarget = this._renderTarget || this._getFrameBufferTarget();
  41521. let renderContext = null;
  41522. if ( renderTarget !== null ) {
  41523. this._textures.updateRenderTarget( renderTarget );
  41524. const renderTargetData = this._textures.get( renderTarget );
  41525. renderContext = this._renderContexts.getForClear( renderTarget );
  41526. renderContext.textures = renderTargetData.textures;
  41527. renderContext.depthTexture = renderTargetData.depthTexture;
  41528. renderContext.width = renderTargetData.width;
  41529. renderContext.height = renderTargetData.height;
  41530. renderContext.renderTarget = renderTarget;
  41531. renderContext.depth = renderTarget.depthBuffer;
  41532. renderContext.stencil = renderTarget.stencilBuffer;
  41533. // #30329
  41534. renderContext.clearColorValue = this.backend.getClearColor();
  41535. renderContext.activeCubeFace = this.getActiveCubeFace();
  41536. renderContext.activeMipmapLevel = this.getActiveMipmapLevel();
  41537. }
  41538. this.backend.clear( color, depth, stencil, renderContext );
  41539. if ( renderTarget !== null && this._renderTarget === null ) {
  41540. this._renderOutput( renderTarget );
  41541. }
  41542. }
  41543. /**
  41544. * Performs a manual clear operation of the color buffer. This method ignores `autoClear` properties.
  41545. */
  41546. clearColor() {
  41547. this.clear( true, false, false );
  41548. }
  41549. /**
  41550. * Performs a manual clear operation of the depth buffer. This method ignores `autoClear` properties.
  41551. */
  41552. clearDepth() {
  41553. this.clear( false, true, false );
  41554. }
  41555. /**
  41556. * Performs a manual clear operation of the stencil buffer. This method ignores `autoClear` properties.
  41557. */
  41558. clearStencil() {
  41559. this.clear( false, false, true );
  41560. }
  41561. /**
  41562. * Async version of {@link Renderer#clear}.
  41563. *
  41564. * @async
  41565. * @deprecated
  41566. * @param {boolean} [color=true] - Whether the color buffer should be cleared or not.
  41567. * @param {boolean} [depth=true] - Whether the depth buffer should be cleared or not.
  41568. * @param {boolean} [stencil=true] - Whether the stencil buffer should be cleared or not.
  41569. * @return {Promise} A Promise that resolves when the clear operation has been executed.
  41570. */
  41571. async clearAsync( color = true, depth = true, stencil = true ) {
  41572. warnOnce( 'Renderer: "clearAsync()" has been deprecated. Use "clear()" and "await renderer.init();" when creating the renderer.' ); // @deprecated r181
  41573. await this.init();
  41574. this.clear( color, depth, stencil );
  41575. }
  41576. /**
  41577. * Async version of {@link Renderer#clearColor}.
  41578. *
  41579. * @async
  41580. * @deprecated
  41581. * @return {Promise} A Promise that resolves when the clear operation has been executed.
  41582. */
  41583. async clearColorAsync() {
  41584. warnOnce( 'Renderer: "clearColorAsync()" has been deprecated. Use "clearColor()" and "await renderer.init();" when creating the renderer.' ); // @deprecated r181
  41585. this.clear( true, false, false );
  41586. }
  41587. /**
  41588. * Async version of {@link Renderer#clearDepth}.
  41589. *
  41590. * @async
  41591. * @deprecated
  41592. * @return {Promise} A Promise that resolves when the clear operation has been executed.
  41593. */
  41594. async clearDepthAsync() {
  41595. warnOnce( 'Renderer: "clearDepthAsync()" has been deprecated. Use "clearDepth()" and "await renderer.init();" when creating the renderer.' ); // @deprecated r181
  41596. this.clear( false, true, false );
  41597. }
  41598. /**
  41599. * Async version of {@link Renderer#clearStencil}.
  41600. *
  41601. * @async
  41602. * @deprecated
  41603. * @return {Promise} A Promise that resolves when the clear operation has been executed.
  41604. */
  41605. async clearStencilAsync() {
  41606. warnOnce( 'Renderer: "clearStencilAsync()" has been deprecated. Use "clearStencil()" and "await renderer.init();" when creating the renderer.' ); // @deprecated r181
  41607. this.clear( false, false, true );
  41608. }
  41609. /**
  41610. * Returns `true` if a framebuffer target is needed to perform tone mapping or color space conversion.
  41611. * If this is the case, the renderer allocates an internal render target for that purpose.
  41612. *
  41613. */
  41614. get needsFrameBufferTarget() {
  41615. const useToneMapping = this.currentToneMapping !== NoToneMapping;
  41616. const useColorSpace = this.currentColorSpace !== ColorManagement.workingColorSpace;
  41617. return useToneMapping || useColorSpace;
  41618. }
  41619. /**
  41620. * The number of samples used for multi-sample anti-aliasing (MSAA).
  41621. *
  41622. * @type {number}
  41623. * @default 0
  41624. */
  41625. get samples() {
  41626. return this._samples;
  41627. }
  41628. /**
  41629. * The current number of samples used for multi-sample anti-aliasing (MSAA).
  41630. *
  41631. * When rendering to a custom render target, the number of samples of that render target is used.
  41632. * If the renderer needs an internal framebuffer target for tone mapping or color space conversion,
  41633. * the number of samples is set to 0.
  41634. *
  41635. * @type {number}
  41636. */
  41637. get currentSamples() {
  41638. let samples = this._samples;
  41639. if ( this._renderTarget !== null ) {
  41640. samples = this._renderTarget.samples;
  41641. } else if ( this.needsFrameBufferTarget ) {
  41642. samples = 0;
  41643. }
  41644. return samples;
  41645. }
  41646. /**
  41647. * The current tone mapping of the renderer. When not producing screen output,
  41648. * the tone mapping is always `NoToneMapping`.
  41649. *
  41650. * @type {number}
  41651. */
  41652. get currentToneMapping() {
  41653. return this.isOutputTarget ? this.toneMapping : NoToneMapping;
  41654. }
  41655. /**
  41656. * The current color space of the renderer. When not producing screen output,
  41657. * the color space is always the working color space.
  41658. *
  41659. * @type {string}
  41660. */
  41661. get currentColorSpace() {
  41662. return this.isOutputTarget ? this.outputColorSpace : ColorManagement.workingColorSpace;
  41663. }
  41664. /**
  41665. * Returns `true` if the rendering settings are set to screen output.
  41666. *
  41667. * @returns {boolean} True if the current render target is the same of output render target or `null`, otherwise false.
  41668. */
  41669. get isOutputTarget() {
  41670. return this._renderTarget === this._outputRenderTarget || this._renderTarget === null;
  41671. }
  41672. /**
  41673. * Frees all internal resources of the renderer. Call this method if the renderer
  41674. * is no longer in use by your app.
  41675. */
  41676. dispose() {
  41677. if ( this._initialized === true ) {
  41678. this.info.dispose();
  41679. this.backend.dispose();
  41680. this._animation.dispose();
  41681. this._objects.dispose();
  41682. this._geometries.dispose();
  41683. this._pipelines.dispose();
  41684. this._nodes.dispose();
  41685. this._bindings.dispose();
  41686. this._renderLists.dispose();
  41687. this._renderContexts.dispose();
  41688. this._textures.dispose();
  41689. if ( this._frameBufferTarget !== null ) this._frameBufferTarget.dispose();
  41690. Object.values( this.backend.timestampQueryPool ).forEach( queryPool => {
  41691. if ( queryPool !== null ) queryPool.dispose();
  41692. } );
  41693. }
  41694. this.setRenderTarget( null );
  41695. this.setAnimationLoop( null );
  41696. }
  41697. /**
  41698. * Sets the given render target. Calling this method means the renderer does not
  41699. * target the default framebuffer (meaning the canvas) anymore but a custom framebuffer.
  41700. * Use `null` as the first argument to reset the state.
  41701. *
  41702. * @param {?RenderTarget} renderTarget - The render target to set.
  41703. * @param {number} [activeCubeFace=0] - The active cube face.
  41704. * @param {number} [activeMipmapLevel=0] - The active mipmap level.
  41705. */
  41706. setRenderTarget( renderTarget, activeCubeFace = 0, activeMipmapLevel = 0 ) {
  41707. this._renderTarget = renderTarget;
  41708. this._activeCubeFace = activeCubeFace;
  41709. this._activeMipmapLevel = activeMipmapLevel;
  41710. }
  41711. /**
  41712. * Returns the current render target.
  41713. *
  41714. * @return {?RenderTarget} The render target. Returns `null` if no render target is set.
  41715. */
  41716. getRenderTarget() {
  41717. return this._renderTarget;
  41718. }
  41719. /**
  41720. * Sets the output render target for the renderer.
  41721. *
  41722. * @param {Object} renderTarget - The render target to set as the output target.
  41723. */
  41724. setOutputRenderTarget( renderTarget ) {
  41725. this._outputRenderTarget = renderTarget;
  41726. }
  41727. /**
  41728. * Returns the current output target.
  41729. *
  41730. * @return {?RenderTarget} The current output render target. Returns `null` if no output target is set.
  41731. */
  41732. getOutputRenderTarget() {
  41733. return this._outputRenderTarget;
  41734. }
  41735. /**
  41736. * Sets the canvas target. The canvas target manages the HTML canvas
  41737. * or the offscreen canvas the renderer draws into.
  41738. *
  41739. * @param {CanvasTarget} canvasTarget - The canvas target.
  41740. */
  41741. setCanvasTarget( canvasTarget ) {
  41742. this._canvasTarget.removeEventListener( 'resize', this._onCanvasTargetResize );
  41743. this._canvasTarget = canvasTarget;
  41744. this._canvasTarget.addEventListener( 'resize', this._onCanvasTargetResize );
  41745. }
  41746. /**
  41747. * Returns the current canvas target.
  41748. *
  41749. * @return {CanvasTarget} The current canvas target.
  41750. */
  41751. getCanvasTarget() {
  41752. return this._canvasTarget;
  41753. }
  41754. /**
  41755. * Resets the renderer to the initial state before WebXR started.
  41756. *
  41757. * @private
  41758. */
  41759. _resetXRState() {
  41760. this.backend.setXRTarget( null );
  41761. this.setOutputRenderTarget( null );
  41762. this.setRenderTarget( null );
  41763. this._frameBufferTarget.dispose();
  41764. this._frameBufferTarget = null;
  41765. }
  41766. /**
  41767. * Callback for {@link Renderer#setRenderObjectFunction}.
  41768. *
  41769. * @callback renderObjectFunction
  41770. * @param {Object3D} object - The 3D object.
  41771. * @param {Scene} scene - The scene the 3D object belongs to.
  41772. * @param {Camera} camera - The camera the object should be rendered with.
  41773. * @param {BufferGeometry} geometry - The object's geometry.
  41774. * @param {Material} material - The object's material.
  41775. * @param {?Object} group - Only relevant for objects using multiple materials. This represents a group entry from the respective `BufferGeometry`.
  41776. * @param {LightsNode} lightsNode - The current lights node.
  41777. * @param {ClippingContext} clippingContext - The clipping context.
  41778. * @param {?string} [passId=null] - An optional ID for identifying the pass.
  41779. */
  41780. /**
  41781. * Sets the given render object function. Calling this method overwrites the default implementation
  41782. * which is {@link Renderer#renderObject}. Defining a custom function can be useful
  41783. * if you want to modify the way objects are rendered. For example you can define things like "every
  41784. * object that has material of a certain type should perform a pre-pass with a special overwrite material".
  41785. * The custom function must always call `renderObject()` in its implementation.
  41786. *
  41787. * Use `null` as the first argument to reset the state.
  41788. *
  41789. * @param {?renderObjectFunction} renderObjectFunction - The render object function.
  41790. */
  41791. setRenderObjectFunction( renderObjectFunction ) {
  41792. this._renderObjectFunction = renderObjectFunction;
  41793. }
  41794. /**
  41795. * Returns the current render object function.
  41796. *
  41797. * @return {?Function} The current render object function. Returns `null` if no function is set.
  41798. */
  41799. getRenderObjectFunction() {
  41800. return this._renderObjectFunction;
  41801. }
  41802. /**
  41803. * Execute a single or an array of compute nodes. This method can only be called
  41804. * if the renderer has been initialized.
  41805. *
  41806. * @param {Node|Array<Node>} computeNodes - The compute node(s).
  41807. * @param {number|Array<number>|IndirectStorageBufferAttribute} [dispatchSize=null]
  41808. * - A single number representing count, or
  41809. * - An array [x, y, z] representing dispatch size, or
  41810. * - A IndirectStorageBufferAttribute for indirect dispatch size.
  41811. * @return {Promise|undefined} A Promise that resolve when the compute has finished. Only returned when the renderer has not been initialized.
  41812. */
  41813. compute( computeNodes, dispatchSize = null ) {
  41814. if ( this._isDeviceLost === true ) return;
  41815. if ( this._initialized === false ) {
  41816. warn( 'Renderer: .compute() called before the backend is initialized. Try using .computeAsync() instead.' );
  41817. return this.computeAsync( computeNodes, dispatchSize );
  41818. }
  41819. //
  41820. const nodeFrame = this._nodes.nodeFrame;
  41821. const previousRenderId = nodeFrame.renderId;
  41822. //
  41823. this.info.calls ++;
  41824. this.info.compute.calls ++;
  41825. this.info.compute.frameCalls ++;
  41826. nodeFrame.renderId = this.info.calls;
  41827. //
  41828. this.backend.updateTimeStampUID( computeNodes );
  41829. this.inspector.beginCompute( this.backend.getTimestampUID( computeNodes ), computeNodes );
  41830. //
  41831. const backend = this.backend;
  41832. const pipelines = this._pipelines;
  41833. const bindings = this._bindings;
  41834. const nodes = this._nodes;
  41835. const computeList = Array.isArray( computeNodes ) ? computeNodes : [ computeNodes ];
  41836. if ( computeList[ 0 ] === undefined || computeList[ 0 ].isComputeNode !== true ) {
  41837. throw new Error( 'THREE.Renderer: .compute() expects a ComputeNode.' );
  41838. }
  41839. backend.beginCompute( computeNodes );
  41840. for ( const computeNode of computeList ) {
  41841. // onInit
  41842. if ( pipelines.has( computeNode ) === false ) {
  41843. const dispose = () => {
  41844. computeNode.removeEventListener( 'dispose', dispose );
  41845. pipelines.delete( computeNode );
  41846. bindings.deleteForCompute( computeNode );
  41847. nodes.delete( computeNode );
  41848. };
  41849. computeNode.addEventListener( 'dispose', dispose );
  41850. //
  41851. const onInitFn = computeNode.onInitFunction;
  41852. if ( onInitFn !== null ) {
  41853. onInitFn.call( computeNode, { renderer: this } );
  41854. }
  41855. }
  41856. nodes.updateForCompute( computeNode );
  41857. bindings.updateForCompute( computeNode );
  41858. const computeBindings = bindings.getForCompute( computeNode );
  41859. const computePipeline = pipelines.getForCompute( computeNode, computeBindings );
  41860. backend.compute( computeNodes, computeNode, computeBindings, computePipeline, dispatchSize );
  41861. }
  41862. backend.finishCompute( computeNodes );
  41863. //
  41864. nodeFrame.renderId = previousRenderId;
  41865. //
  41866. this.inspector.finishCompute( this.backend.getTimestampUID( computeNodes ) );
  41867. }
  41868. /**
  41869. * Execute a single or an array of compute nodes.
  41870. *
  41871. * @async
  41872. * @param {Node|Array<Node>} computeNodes - The compute node(s).
  41873. * @param {number|Array<number>|IndirectStorageBufferAttribute} [dispatchSize=null]
  41874. * - A single number representing count, or
  41875. * - An array [x, y, z] representing dispatch size, or
  41876. * - A IndirectStorageBufferAttribute for indirect dispatch size.
  41877. * @return {Promise} A Promise that resolve when the compute has finished.
  41878. */
  41879. async computeAsync( computeNodes, dispatchSize = null ) {
  41880. if ( this._initialized === false ) await this.init();
  41881. this.compute( computeNodes, dispatchSize );
  41882. }
  41883. /**
  41884. * Checks if the given feature is supported by the selected backend.
  41885. *
  41886. * @async
  41887. * @deprecated
  41888. * @param {string} name - The feature's name.
  41889. * @return {Promise<boolean>} A Promise that resolves with a bool that indicates whether the feature is supported or not.
  41890. */
  41891. async hasFeatureAsync( name ) {
  41892. warnOnce( 'Renderer: "hasFeatureAsync()" has been deprecated. Use "hasFeature()" and "await renderer.init();" when creating the renderer.' ); // @deprecated r181
  41893. await this.init();
  41894. return this.hasFeature( name );
  41895. }
  41896. async resolveTimestampsAsync( type = 'render' ) {
  41897. if ( this._initialized === false ) await this.init();
  41898. return this.backend.resolveTimestampsAsync( type );
  41899. }
  41900. /**
  41901. * Checks if the given feature is supported by the selected backend. If the
  41902. * renderer has not been initialized, this method always returns `false`.
  41903. *
  41904. * @param {string} name - The feature's name.
  41905. * @return {boolean} Whether the feature is supported or not.
  41906. */
  41907. hasFeature( name ) {
  41908. if ( this._initialized === false ) {
  41909. throw new Error( 'Renderer: .hasFeature() called before the backend is initialized. Use "await renderer.init();" before before using this method.' );
  41910. }
  41911. return this.backend.hasFeature( name );
  41912. }
  41913. /**
  41914. * Returns `true` when the renderer has been initialized.
  41915. *
  41916. * @return {boolean} Whether the renderer has been initialized or not.
  41917. */
  41918. hasInitialized() {
  41919. return this._initialized;
  41920. }
  41921. /**
  41922. * Initializes the given textures. Useful for preloading a texture rather than waiting until first render
  41923. * (which can cause noticeable lags due to decode and GPU upload overhead).
  41924. *
  41925. * @async
  41926. * @deprecated
  41927. * @param {Texture} texture - The texture.
  41928. * @return {Promise} A Promise that resolves when the texture has been initialized.
  41929. */
  41930. async initTextureAsync( texture ) {
  41931. warnOnce( 'Renderer: "initTextureAsync()" has been deprecated. Use "initTexture()" and "await renderer.init();" when creating the renderer.' ); // @deprecated r181
  41932. await this.init();
  41933. this.initTexture( texture );
  41934. }
  41935. /**
  41936. * Initializes the given texture. Useful for preloading a texture rather than waiting until first render
  41937. * (which can cause noticeable lags due to decode and GPU upload overhead).
  41938. *
  41939. * This method can only be used if the renderer has been initialized.
  41940. *
  41941. * @param {Texture} texture - The texture.
  41942. */
  41943. initTexture( texture ) {
  41944. if ( this._initialized === false ) {
  41945. throw new Error( 'Renderer: .initTexture() called before the backend is initialized. Use "await renderer.init();" before before using this method.' );
  41946. }
  41947. this._textures.updateTexture( texture );
  41948. }
  41949. /**
  41950. * Copies the current bound framebuffer into the given texture.
  41951. *
  41952. * @param {FramebufferTexture} framebufferTexture - The texture.
  41953. * @param {?(Vector2|Vector4)} [rectangle=null] - A two or four dimensional vector that defines the rectangular portion of the framebuffer that should be copied.
  41954. */
  41955. copyFramebufferToTexture( framebufferTexture, rectangle = null ) {
  41956. if ( rectangle !== null ) {
  41957. if ( rectangle.isVector2 ) {
  41958. rectangle = _vector4.set( rectangle.x, rectangle.y, framebufferTexture.image.width, framebufferTexture.image.height ).floor();
  41959. } else if ( rectangle.isVector4 ) {
  41960. rectangle = _vector4.copy( rectangle ).floor();
  41961. } else {
  41962. error( 'Renderer.copyFramebufferToTexture: Invalid rectangle.' );
  41963. return;
  41964. }
  41965. } else {
  41966. rectangle = _vector4.set( 0, 0, framebufferTexture.image.width, framebufferTexture.image.height );
  41967. }
  41968. //
  41969. let renderContext = this._currentRenderContext;
  41970. let renderTarget;
  41971. if ( renderContext !== null ) {
  41972. renderTarget = renderContext.renderTarget;
  41973. } else {
  41974. renderTarget = this._renderTarget || this._getFrameBufferTarget();
  41975. if ( renderTarget !== null ) {
  41976. this._textures.updateRenderTarget( renderTarget );
  41977. renderContext = this._textures.get( renderTarget );
  41978. }
  41979. }
  41980. //
  41981. this._textures.updateTexture( framebufferTexture, { renderTarget } );
  41982. this.backend.copyFramebufferToTexture( framebufferTexture, renderContext, rectangle );
  41983. this._inspector.copyFramebufferToTexture( framebufferTexture );
  41984. }
  41985. /**
  41986. * Copies data of the given source texture into a destination texture.
  41987. *
  41988. * @param {Texture} srcTexture - The source texture.
  41989. * @param {Texture} dstTexture - The destination texture.
  41990. * @param {Box2|Box3} [srcRegion=null] - A bounding box which describes the source region. Can be two or three-dimensional.
  41991. * @param {Vector2|Vector3} [dstPosition=null] - A vector that represents the origin of the destination region. Can be two or three-dimensional.
  41992. * @param {number} [srcLevel=0] - The source mip level to copy from.
  41993. * @param {number} [dstLevel=0] - The destination mip level to copy to.
  41994. */
  41995. copyTextureToTexture( srcTexture, dstTexture, srcRegion = null, dstPosition = null, srcLevel = 0, dstLevel = 0 ) {
  41996. this._textures.updateTexture( srcTexture );
  41997. this._textures.updateTexture( dstTexture );
  41998. this.backend.copyTextureToTexture( srcTexture, dstTexture, srcRegion, dstPosition, srcLevel, dstLevel );
  41999. this._inspector.copyTextureToTexture( srcTexture, dstTexture );
  42000. }
  42001. /**
  42002. * Reads pixel data from the given render target.
  42003. *
  42004. * @async
  42005. * @param {RenderTarget} renderTarget - The render target to read from.
  42006. * @param {number} x - The `x` coordinate of the copy region's origin.
  42007. * @param {number} y - The `y` coordinate of the copy region's origin.
  42008. * @param {number} width - The width of the copy region.
  42009. * @param {number} height - The height of the copy region.
  42010. * @param {number} [textureIndex=0] - The texture index of a MRT render target.
  42011. * @param {number} [faceIndex=0] - The active cube face index.
  42012. * @return {Promise<TypedArray>} A Promise that resolves when the read has been finished. The resolve provides the read data as a typed array.
  42013. */
  42014. async readRenderTargetPixelsAsync( renderTarget, x, y, width, height, textureIndex = 0, faceIndex = 0 ) {
  42015. return this.backend.copyTextureToBuffer( renderTarget.textures[ textureIndex ], x, y, width, height, faceIndex );
  42016. }
  42017. /**
  42018. * Analyzes the given 3D object's hierarchy and builds render lists from the
  42019. * processed hierarchy.
  42020. *
  42021. * @private
  42022. * @param {Object3D} object - The 3D object to process (usually a scene).
  42023. * @param {Camera} camera - The camera the object is rendered with.
  42024. * @param {number} groupOrder - The group order is derived from the `renderOrder` of groups and is used to group 3D objects within groups.
  42025. * @param {RenderList} renderList - The current render list.
  42026. * @param {ClippingContext} clippingContext - The current clipping context.
  42027. */
  42028. _projectObject( object, camera, groupOrder, renderList, clippingContext ) {
  42029. if ( object.visible === false ) return;
  42030. const visible = object.layers.test( camera.layers );
  42031. if ( visible ) {
  42032. if ( object.isGroup ) {
  42033. groupOrder = object.renderOrder;
  42034. if ( object.isClippingGroup && object.enabled ) clippingContext = clippingContext.getGroupContext( object );
  42035. } else if ( object.isLOD ) {
  42036. if ( object.autoUpdate === true ) object.update( camera );
  42037. } else if ( object.isLight ) {
  42038. renderList.pushLight( object );
  42039. } else if ( object.isSprite ) {
  42040. const frustum = camera.isArrayCamera ? _frustumArray : _frustum;
  42041. if ( ! object.frustumCulled || frustum.intersectsSprite( object, camera ) ) {
  42042. if ( this.sortObjects === true ) {
  42043. _vector4.setFromMatrixPosition( object.matrixWorld ).applyMatrix4( _projScreenMatrix );
  42044. }
  42045. const { geometry, material } = object;
  42046. if ( material.visible ) {
  42047. renderList.push( object, geometry, material, groupOrder, _vector4.z, null, clippingContext );
  42048. }
  42049. }
  42050. } else if ( object.isLineLoop ) {
  42051. error( 'Renderer: Objects of type THREE.LineLoop are not supported. Please use THREE.Line or THREE.LineSegments.' );
  42052. } else if ( object.isMesh || object.isLine || object.isPoints ) {
  42053. const frustum = camera.isArrayCamera ? _frustumArray : _frustum;
  42054. if ( ! object.frustumCulled || frustum.intersectsObject( object, camera ) ) {
  42055. const { geometry, material } = object;
  42056. if ( this.sortObjects === true ) {
  42057. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  42058. _vector4
  42059. .copy( geometry.boundingSphere.center )
  42060. .applyMatrix4( object.matrixWorld )
  42061. .applyMatrix4( _projScreenMatrix );
  42062. }
  42063. if ( Array.isArray( material ) ) {
  42064. const groups = geometry.groups;
  42065. for ( let i = 0, l = groups.length; i < l; i ++ ) {
  42066. const group = groups[ i ];
  42067. const groupMaterial = material[ group.materialIndex ];
  42068. if ( groupMaterial && groupMaterial.visible ) {
  42069. renderList.push( object, geometry, groupMaterial, groupOrder, _vector4.z, group, clippingContext );
  42070. }
  42071. }
  42072. } else if ( material.visible ) {
  42073. renderList.push( object, geometry, material, groupOrder, _vector4.z, null, clippingContext );
  42074. }
  42075. }
  42076. }
  42077. }
  42078. if ( object.isBundleGroup === true && this.backend.beginBundle !== undefined ) {
  42079. const baseRenderList = renderList;
  42080. // replace render list
  42081. renderList = this._renderLists.get( object, camera );
  42082. renderList.begin();
  42083. baseRenderList.pushBundle( {
  42084. bundleGroup: object,
  42085. camera,
  42086. renderList,
  42087. } );
  42088. renderList.finish();
  42089. }
  42090. const children = object.children;
  42091. for ( let i = 0, l = children.length; i < l; i ++ ) {
  42092. this._projectObject( children[ i ], camera, groupOrder, renderList, clippingContext );
  42093. }
  42094. }
  42095. /**
  42096. * Renders the given render bundles.
  42097. *
  42098. * @private
  42099. * @param {Array<Object>} bundles - Array with render bundle data.
  42100. * @param {Scene} sceneRef - The scene the render bundles belong to.
  42101. * @param {LightsNode} lightsNode - The current lights node.
  42102. */
  42103. _renderBundles( bundles, sceneRef, lightsNode ) {
  42104. for ( const bundle of bundles ) {
  42105. this._renderBundle( bundle, sceneRef, lightsNode );
  42106. }
  42107. }
  42108. /**
  42109. * Renders the transparent objects from the given render lists.
  42110. *
  42111. * @private
  42112. * @param {Array<Object>} renderList - The transparent render list.
  42113. * @param {Array<Object>} doublePassList - The list of transparent objects which require a double pass (e.g. because of transmission).
  42114. * @param {Camera} camera - The camera the render list should be rendered with.
  42115. * @param {Scene} scene - The scene the render list belongs to.
  42116. * @param {LightsNode} lightsNode - The current lights node.
  42117. */
  42118. _renderTransparents( renderList, doublePassList, camera, scene, lightsNode ) {
  42119. if ( doublePassList.length > 0 ) {
  42120. // render back side
  42121. for ( const { material } of doublePassList ) {
  42122. material.side = BackSide;
  42123. }
  42124. this._renderObjects( doublePassList, camera, scene, lightsNode, 'backSide' );
  42125. // render front side
  42126. for ( const { material } of doublePassList ) {
  42127. material.side = FrontSide;
  42128. }
  42129. this._renderObjects( renderList, camera, scene, lightsNode );
  42130. // restore
  42131. for ( const { material } of doublePassList ) {
  42132. material.side = DoubleSide;
  42133. }
  42134. } else {
  42135. this._renderObjects( renderList, camera, scene, lightsNode );
  42136. }
  42137. }
  42138. /**
  42139. * Renders the objects from the given render list.
  42140. *
  42141. * @private
  42142. * @param {Array<Object>} renderList - The render list.
  42143. * @param {Camera} camera - The camera the render list should be rendered with.
  42144. * @param {Scene} scene - The scene the render list belongs to.
  42145. * @param {LightsNode} lightsNode - The current lights node.
  42146. * @param {?string} [passId=null] - An optional ID for identifying the pass.
  42147. */
  42148. _renderObjects( renderList, camera, scene, lightsNode, passId = null ) {
  42149. for ( let i = 0, il = renderList.length; i < il; i ++ ) {
  42150. const { object, geometry, material, group, clippingContext } = renderList[ i ];
  42151. this._currentRenderObjectFunction( object, scene, camera, geometry, material, group, lightsNode, clippingContext, passId );
  42152. }
  42153. }
  42154. /**
  42155. * Retrieves shadow nodes for the given material. This is used to setup shadow passes.
  42156. * The result is cached per material and updated when the material's version changes.
  42157. *
  42158. * @private
  42159. * @param {Material} material
  42160. * @returns {Object} - The shadow nodes for the material.
  42161. */
  42162. _getShadowNodes( material ) {
  42163. const version = material.version;
  42164. let cache = this._cacheShadowNodes.get( material );
  42165. if ( cache === undefined || cache.version !== version ) {
  42166. const hasMap = material.map !== null;
  42167. const hasColorNode = material.colorNode && material.colorNode.isNode;
  42168. const hasCastShadowNode = material.castShadowNode && material.castShadowNode.isNode;
  42169. let positionNode = null;
  42170. let colorNode = null;
  42171. let depthNode = null;
  42172. if ( hasMap || hasColorNode || hasCastShadowNode ) {
  42173. let shadowRGB;
  42174. let shadowAlpha;
  42175. if ( hasCastShadowNode ) {
  42176. shadowRGB = material.castShadowNode.rgb;
  42177. shadowAlpha = material.castShadowNode.a;
  42178. } else {
  42179. shadowRGB = vec3( 0 );
  42180. shadowAlpha = float( 1 );
  42181. }
  42182. if ( hasMap ) {
  42183. shadowAlpha = shadowAlpha.mul( reference( 'map', 'texture', material ).a );
  42184. }
  42185. if ( hasColorNode ) {
  42186. shadowAlpha = shadowAlpha.mul( material.colorNode.a );
  42187. }
  42188. colorNode = vec4( shadowRGB, shadowAlpha );
  42189. }
  42190. if ( material.depthNode && material.depthNode.isNode ) {
  42191. depthNode = material.depthNode;
  42192. }
  42193. if ( material.castShadowPositionNode && material.castShadowPositionNode.isNode ) {
  42194. positionNode = material.castShadowPositionNode;
  42195. } else if ( material.positionNode && material.positionNode.isNode ) {
  42196. positionNode = material.positionNode;
  42197. }
  42198. cache = {
  42199. version,
  42200. colorNode,
  42201. depthNode,
  42202. positionNode
  42203. };
  42204. this._cacheShadowNodes.set( material, cache );
  42205. }
  42206. return cache;
  42207. }
  42208. /**
  42209. * This method represents the default render object function that manages the render lifecycle
  42210. * of the object.
  42211. *
  42212. * @param {Object3D} object - The 3D object.
  42213. * @param {Scene} scene - The scene the 3D object belongs to.
  42214. * @param {Camera} camera - The camera the object should be rendered with.
  42215. * @param {BufferGeometry} geometry - The object's geometry.
  42216. * @param {Material} material - The object's material.
  42217. * @param {?Object} group - Only relevant for objects using multiple materials. This represents a group entry from the respective `BufferGeometry`.
  42218. * @param {LightsNode} lightsNode - The current lights node.
  42219. * @param {?ClippingContext} clippingContext - The clipping context.
  42220. * @param {?string} [passId=null] - An optional ID for identifying the pass.
  42221. */
  42222. renderObject( object, scene, camera, geometry, material, group, lightsNode, clippingContext = null, passId = null ) {
  42223. let materialOverride = false;
  42224. let materialColorNode;
  42225. let materialDepthNode;
  42226. let materialPositionNode;
  42227. let materialSide;
  42228. //
  42229. object.onBeforeRender( this, scene, camera, geometry, material, group );
  42230. //
  42231. if ( material.allowOverride === true && scene.overrideMaterial !== null ) {
  42232. const overrideMaterial = scene.overrideMaterial;
  42233. materialOverride = true;
  42234. // store original nodes
  42235. materialColorNode = scene.overrideMaterial.colorNode;
  42236. materialDepthNode = scene.overrideMaterial.depthNode;
  42237. materialPositionNode = scene.overrideMaterial.positionNode;
  42238. materialSide = scene.overrideMaterial.side;
  42239. if ( material.positionNode && material.positionNode.isNode ) {
  42240. overrideMaterial.positionNode = material.positionNode;
  42241. }
  42242. overrideMaterial.alphaTest = material.alphaTest;
  42243. overrideMaterial.alphaMap = material.alphaMap;
  42244. overrideMaterial.transparent = material.transparent || material.transmission > 0 ||
  42245. ( material.transmissionNode && material.transmissionNode.isNode ) ||
  42246. ( material.backdropNode && material.backdropNode.isNode );
  42247. if ( overrideMaterial.isShadowPassMaterial ) {
  42248. const { colorNode, depthNode, positionNode } = this._getShadowNodes( material );
  42249. overrideMaterial.side = material.shadowSide === null ? material.side : material.shadowSide;
  42250. if ( colorNode !== null ) overrideMaterial.colorNode = colorNode;
  42251. if ( depthNode !== null ) overrideMaterial.depthNode = depthNode;
  42252. if ( positionNode !== null ) overrideMaterial.positionNode = positionNode;
  42253. }
  42254. material = overrideMaterial;
  42255. }
  42256. //
  42257. if ( material.transparent === true && material.side === DoubleSide && material.forceSinglePass === false ) {
  42258. material.side = BackSide;
  42259. this._handleObjectFunction( object, material, scene, camera, lightsNode, group, clippingContext, 'backSide' ); // create backSide pass id
  42260. material.side = FrontSide;
  42261. this._handleObjectFunction( object, material, scene, camera, lightsNode, group, clippingContext, passId ); // use default pass id
  42262. material.side = DoubleSide;
  42263. } else {
  42264. this._handleObjectFunction( object, material, scene, camera, lightsNode, group, clippingContext, passId );
  42265. }
  42266. //
  42267. if ( materialOverride ) {
  42268. scene.overrideMaterial.colorNode = materialColorNode;
  42269. scene.overrideMaterial.depthNode = materialDepthNode;
  42270. scene.overrideMaterial.positionNode = materialPositionNode;
  42271. scene.overrideMaterial.side = materialSide;
  42272. }
  42273. //
  42274. object.onAfterRender( this, scene, camera, geometry, material, group );
  42275. }
  42276. /**
  42277. * This method represents the default `_handleObjectFunction` implementation which creates
  42278. * a render object from the given data and performs the draw command with the selected backend.
  42279. *
  42280. * @private
  42281. * @param {Object3D} object - The 3D object.
  42282. * @param {Material} material - The object's material.
  42283. * @param {Scene} scene - The scene the 3D object belongs to.
  42284. * @param {Camera} camera - The camera the object should be rendered with.
  42285. * @param {LightsNode} lightsNode - The current lights node.
  42286. * @param {?{start: number, count: number}} group - Only relevant for objects using multiple materials. This represents a group entry from the respective `BufferGeometry`.
  42287. * @param {ClippingContext} clippingContext - The clipping context.
  42288. * @param {string} [passId] - An optional ID for identifying the pass.
  42289. */
  42290. _renderObjectDirect( object, material, scene, camera, lightsNode, group, clippingContext, passId ) {
  42291. const renderObject = this._objects.get( object, material, scene, camera, lightsNode, this._currentRenderContext, clippingContext, passId );
  42292. renderObject.drawRange = object.geometry.drawRange;
  42293. renderObject.group = group;
  42294. //
  42295. const needsRefresh = this._nodes.needsRefresh( renderObject );
  42296. if ( needsRefresh ) {
  42297. this._nodes.updateBefore( renderObject );
  42298. this._geometries.updateForRender( renderObject );
  42299. this._nodes.updateForRender( renderObject );
  42300. this._bindings.updateForRender( renderObject );
  42301. }
  42302. this._pipelines.updateForRender( renderObject );
  42303. //
  42304. if ( this._currentRenderBundle !== null ) {
  42305. const renderBundleData = this.backend.get( this._currentRenderBundle );
  42306. renderBundleData.renderObjects.push( renderObject );
  42307. renderObject.bundle = this._currentRenderBundle.bundleGroup;
  42308. }
  42309. this.backend.draw( renderObject, this.info );
  42310. if ( needsRefresh ) this._nodes.updateAfter( renderObject );
  42311. }
  42312. /**
  42313. * A different implementation for `_handleObjectFunction` which only makes sure the object is ready for rendering.
  42314. * Used in `compileAsync()`.
  42315. *
  42316. * @private
  42317. * @param {Object3D} object - The 3D object.
  42318. * @param {Material} material - The object's material.
  42319. * @param {Scene} scene - The scene the 3D object belongs to.
  42320. * @param {Camera} camera - The camera the object should be rendered with.
  42321. * @param {LightsNode} lightsNode - The current lights node.
  42322. * @param {?{start: number, count: number}} group - Only relevant for objects using multiple materials. This represents a group entry from the respective `BufferGeometry`.
  42323. * @param {ClippingContext} clippingContext - The clipping context.
  42324. * @param {string} [passId] - An optional ID for identifying the pass.
  42325. */
  42326. _createObjectPipeline( object, material, scene, camera, lightsNode, group, clippingContext, passId ) {
  42327. const renderObject = this._objects.get( object, material, scene, camera, lightsNode, this._currentRenderContext, clippingContext, passId );
  42328. renderObject.drawRange = object.geometry.drawRange;
  42329. renderObject.group = group;
  42330. //
  42331. this._nodes.updateBefore( renderObject );
  42332. this._geometries.updateForRender( renderObject );
  42333. this._nodes.updateForRender( renderObject );
  42334. this._bindings.updateForRender( renderObject );
  42335. this._pipelines.getForRender( renderObject, this._compilationPromises );
  42336. this._nodes.updateAfter( renderObject );
  42337. }
  42338. /**
  42339. * Callback when the canvas has been resized.
  42340. *
  42341. * @private
  42342. */
  42343. _onCanvasTargetResize() {
  42344. if ( this._initialized ) this.backend.updateSize();
  42345. }
  42346. /**
  42347. * Alias for `compileAsync()`.
  42348. *
  42349. * @method
  42350. * @param {Object3D} scene - The scene or 3D object to precompile.
  42351. * @param {Camera} camera - The camera that is used to render the scene.
  42352. * @param {Scene} targetScene - If the first argument is a 3D object, this parameter must represent the scene the 3D object is going to be added.
  42353. * @return {function(Object3D, Camera, ?Scene): Promise|undefined} A Promise that resolves when the compile has been finished.
  42354. */
  42355. get compile() {
  42356. return this.compileAsync;
  42357. }
  42358. }
  42359. /**
  42360. * A binding represents the connection between a resource (like a texture, sampler
  42361. * or uniform buffer) and the resource definition in a shader stage.
  42362. *
  42363. * This module is an abstract base class for all concrete bindings types.
  42364. *
  42365. * @abstract
  42366. * @private
  42367. */
  42368. class Binding {
  42369. /**
  42370. * Constructs a new binding.
  42371. *
  42372. * @param {string} [name=''] - The binding's name.
  42373. */
  42374. constructor( name = '' ) {
  42375. /**
  42376. * The binding's name.
  42377. *
  42378. * @type {string}
  42379. */
  42380. this.name = name;
  42381. /**
  42382. * A bitmask that defines in what shader stages the
  42383. * binding's resource is accessible.
  42384. *
  42385. * @type {number}
  42386. */
  42387. this.visibility = 0;
  42388. }
  42389. /**
  42390. * Makes sure binding's resource is visible for the given shader stage.
  42391. *
  42392. * @param {number} visibility - The shader stage.
  42393. */
  42394. setVisibility( visibility ) {
  42395. this.visibility |= visibility;
  42396. }
  42397. /**
  42398. * Clones the binding.
  42399. *
  42400. * @return {Binding} The cloned binding.
  42401. */
  42402. clone() {
  42403. return Object.assign( new this.constructor(), this );
  42404. }
  42405. }
  42406. /**
  42407. * This function is usually called with the length in bytes of an array buffer.
  42408. * It returns an padded value which ensure chunk size alignment according to STD140 layout.
  42409. *
  42410. * @function
  42411. * @param {number} floatLength - The buffer length.
  42412. * @return {number} The padded length.
  42413. */
  42414. function getFloatLength( floatLength ) {
  42415. // ensure chunk size alignment (STD140 layout)
  42416. return floatLength + ( ( GPU_CHUNK_BYTES - ( floatLength % GPU_CHUNK_BYTES ) ) % GPU_CHUNK_BYTES );
  42417. }
  42418. /**
  42419. * Represents a buffer binding type.
  42420. *
  42421. * @private
  42422. * @abstract
  42423. * @augments Binding
  42424. */
  42425. class Buffer extends Binding {
  42426. /**
  42427. * Constructs a new buffer.
  42428. *
  42429. * @param {string} name - The buffer's name.
  42430. * @param {TypedArray} [buffer=null] - The buffer.
  42431. */
  42432. constructor( name, buffer = null ) {
  42433. super( name );
  42434. /**
  42435. * This flag can be used for type testing.
  42436. *
  42437. * @type {boolean}
  42438. * @readonly
  42439. * @default true
  42440. */
  42441. this.isBuffer = true;
  42442. /**
  42443. * The bytes per element.
  42444. *
  42445. * @type {number}
  42446. */
  42447. this.bytesPerElement = Float32Array.BYTES_PER_ELEMENT;
  42448. /**
  42449. * A reference to the internal buffer.
  42450. *
  42451. * @private
  42452. * @type {TypedArray}
  42453. */
  42454. this._buffer = buffer;
  42455. }
  42456. /**
  42457. * The buffer's byte length.
  42458. *
  42459. * @type {number}
  42460. * @readonly
  42461. */
  42462. get byteLength() {
  42463. return getFloatLength( this._buffer.byteLength );
  42464. }
  42465. /**
  42466. * A reference to the internal buffer.
  42467. *
  42468. * @type {Float32Array}
  42469. * @readonly
  42470. */
  42471. get buffer() {
  42472. return this._buffer;
  42473. }
  42474. /**
  42475. * Updates the binding.
  42476. *
  42477. * @return {boolean} Whether the buffer has been updated and must be
  42478. * uploaded to the GPU.
  42479. */
  42480. update() {
  42481. return true;
  42482. }
  42483. }
  42484. /**
  42485. * Represents a uniform buffer binding type.
  42486. *
  42487. * @private
  42488. * @augments Buffer
  42489. */
  42490. class UniformBuffer extends Buffer {
  42491. /**
  42492. * Constructs a new uniform buffer.
  42493. *
  42494. * @param {string} name - The buffer's name.
  42495. * @param {TypedArray} [buffer=null] - The buffer.
  42496. */
  42497. constructor( name, buffer = null ) {
  42498. super( name, buffer );
  42499. /**
  42500. * This flag can be used for type testing.
  42501. *
  42502. * @type {boolean}
  42503. * @readonly
  42504. * @default true
  42505. */
  42506. this.isUniformBuffer = true;
  42507. }
  42508. }
  42509. let _id$4 = 0;
  42510. /**
  42511. * A special form of uniform buffer binding type.
  42512. * It's buffer value is managed by a node object.
  42513. *
  42514. * @private
  42515. * @augments UniformBuffer
  42516. */
  42517. class NodeUniformBuffer extends UniformBuffer {
  42518. /**
  42519. * Constructs a new node-based uniform buffer.
  42520. *
  42521. * @param {BufferNode} nodeUniform - The uniform buffer node.
  42522. * @param {UniformGroupNode} groupNode - The uniform group node.
  42523. */
  42524. constructor( nodeUniform, groupNode ) {
  42525. super( 'UniformBuffer_' + _id$4 ++, nodeUniform ? nodeUniform.value : null );
  42526. /**
  42527. * The uniform buffer node.
  42528. *
  42529. * @type {BufferNode}
  42530. */
  42531. this.nodeUniform = nodeUniform;
  42532. /**
  42533. * The uniform group node.
  42534. *
  42535. * @type {UniformGroupNode}
  42536. */
  42537. this.groupNode = groupNode;
  42538. }
  42539. /**
  42540. * The uniform buffer.
  42541. *
  42542. * @type {Float32Array}
  42543. */
  42544. get buffer() {
  42545. return this.nodeUniform.value;
  42546. }
  42547. }
  42548. /**
  42549. * This class represents a uniform buffer binding but with
  42550. * an API that allows to maintain individual uniform objects.
  42551. *
  42552. * @private
  42553. * @augments UniformBuffer
  42554. */
  42555. class UniformsGroup extends UniformBuffer {
  42556. /**
  42557. * Constructs a new uniforms group.
  42558. *
  42559. * @param {string} name - The group's name.
  42560. */
  42561. constructor( name ) {
  42562. super( name );
  42563. /**
  42564. * This flag can be used for type testing.
  42565. *
  42566. * @type {boolean}
  42567. * @readonly
  42568. * @default true
  42569. */
  42570. this.isUniformsGroup = true;
  42571. /**
  42572. * An array with the raw uniform values.
  42573. *
  42574. * @private
  42575. * @type {?Array<number>}
  42576. * @default null
  42577. */
  42578. this._values = null;
  42579. /**
  42580. * An array of uniform objects.
  42581. *
  42582. * The order of uniforms in this array must match the order of uniforms in the shader.
  42583. *
  42584. * @type {Array<Uniform>}
  42585. */
  42586. this.uniforms = [];
  42587. }
  42588. /**
  42589. * Adds a uniform to this group.
  42590. *
  42591. * @param {Uniform} uniform - The uniform to add.
  42592. * @return {UniformsGroup} A reference to this group.
  42593. */
  42594. addUniform( uniform ) {
  42595. this.uniforms.push( uniform );
  42596. return this;
  42597. }
  42598. /**
  42599. * Removes a uniform from this group.
  42600. *
  42601. * @param {Uniform} uniform - The uniform to remove.
  42602. * @return {UniformsGroup} A reference to this group.
  42603. */
  42604. removeUniform( uniform ) {
  42605. const index = this.uniforms.indexOf( uniform );
  42606. if ( index !== -1 ) {
  42607. this.uniforms.splice( index, 1 );
  42608. }
  42609. return this;
  42610. }
  42611. /**
  42612. * An array with the raw uniform values.
  42613. *
  42614. * @type {Array<number>}
  42615. */
  42616. get values() {
  42617. if ( this._values === null ) {
  42618. this._values = Array.from( this.buffer );
  42619. }
  42620. return this._values;
  42621. }
  42622. /**
  42623. * A Float32 array buffer with the uniform values.
  42624. *
  42625. * @type {Float32Array}
  42626. */
  42627. get buffer() {
  42628. let buffer = this._buffer;
  42629. if ( buffer === null ) {
  42630. const byteLength = this.byteLength;
  42631. buffer = new Float32Array( new ArrayBuffer( byteLength ) );
  42632. this._buffer = buffer;
  42633. }
  42634. return buffer;
  42635. }
  42636. /**
  42637. * The byte length of the buffer with correct buffer alignment.
  42638. *
  42639. * @type {number}
  42640. */
  42641. get byteLength() {
  42642. const bytesPerElement = this.bytesPerElement;
  42643. let offset = 0; // global buffer offset in bytes
  42644. for ( let i = 0, l = this.uniforms.length; i < l; i ++ ) {
  42645. const uniform = this.uniforms[ i ];
  42646. const boundary = uniform.boundary;
  42647. const itemSize = uniform.itemSize * bytesPerElement; // size of the uniform in bytes
  42648. const chunkOffset = offset % GPU_CHUNK_BYTES; // offset in the current chunk
  42649. const chunkPadding = chunkOffset % boundary; // required padding to match boundary
  42650. const chunkStart = chunkOffset + chunkPadding; // start position in the current chunk for the data
  42651. offset += chunkPadding;
  42652. // Check for chunk overflow
  42653. if ( chunkStart !== 0 && ( GPU_CHUNK_BYTES - chunkStart ) < itemSize ) {
  42654. // Add padding to the end of the chunk
  42655. offset += ( GPU_CHUNK_BYTES - chunkStart );
  42656. }
  42657. uniform.offset = offset / bytesPerElement;
  42658. offset += itemSize;
  42659. }
  42660. return Math.ceil( offset / GPU_CHUNK_BYTES ) * GPU_CHUNK_BYTES;
  42661. }
  42662. /**
  42663. * Updates this group by updating each uniform object of
  42664. * the internal uniform list. The uniform objects check if their
  42665. * values has actually changed so this method only returns
  42666. * `true` if there is a real value change.
  42667. *
  42668. * @return {boolean} Whether the uniforms have been updated and
  42669. * must be uploaded to the GPU.
  42670. */
  42671. update() {
  42672. let updated = false;
  42673. for ( const uniform of this.uniforms ) {
  42674. if ( this.updateByType( uniform ) === true ) {
  42675. updated = true;
  42676. }
  42677. }
  42678. return updated;
  42679. }
  42680. /**
  42681. * Updates a given uniform by calling an update method matching
  42682. * the uniforms type.
  42683. *
  42684. * @param {Uniform} uniform - The uniform to update.
  42685. * @return {boolean} Whether the uniform has been updated or not.
  42686. */
  42687. updateByType( uniform ) {
  42688. if ( uniform.isNumberUniform ) return this.updateNumber( uniform );
  42689. if ( uniform.isVector2Uniform ) return this.updateVector2( uniform );
  42690. if ( uniform.isVector3Uniform ) return this.updateVector3( uniform );
  42691. if ( uniform.isVector4Uniform ) return this.updateVector4( uniform );
  42692. if ( uniform.isColorUniform ) return this.updateColor( uniform );
  42693. if ( uniform.isMatrix3Uniform ) return this.updateMatrix3( uniform );
  42694. if ( uniform.isMatrix4Uniform ) return this.updateMatrix4( uniform );
  42695. error( 'WebGPUUniformsGroup: Unsupported uniform type.', uniform );
  42696. }
  42697. /**
  42698. * Updates a given Number uniform.
  42699. *
  42700. * @param {NumberUniform} uniform - The Number uniform.
  42701. * @return {boolean} Whether the uniform has been updated or not.
  42702. */
  42703. updateNumber( uniform ) {
  42704. let updated = false;
  42705. const a = this.values;
  42706. const v = uniform.getValue();
  42707. const offset = uniform.offset;
  42708. const type = uniform.getType();
  42709. if ( a[ offset ] !== v ) {
  42710. const b = this._getBufferForType( type );
  42711. b[ offset ] = a[ offset ] = v;
  42712. updated = true;
  42713. }
  42714. return updated;
  42715. }
  42716. /**
  42717. * Updates a given Vector2 uniform.
  42718. *
  42719. * @param {Vector2Uniform} uniform - The Vector2 uniform.
  42720. * @return {boolean} Whether the uniform has been updated or not.
  42721. */
  42722. updateVector2( uniform ) {
  42723. let updated = false;
  42724. const a = this.values;
  42725. const v = uniform.getValue();
  42726. const offset = uniform.offset;
  42727. const type = uniform.getType();
  42728. if ( a[ offset + 0 ] !== v.x || a[ offset + 1 ] !== v.y ) {
  42729. const b = this._getBufferForType( type );
  42730. b[ offset + 0 ] = a[ offset + 0 ] = v.x;
  42731. b[ offset + 1 ] = a[ offset + 1 ] = v.y;
  42732. updated = true;
  42733. }
  42734. return updated;
  42735. }
  42736. /**
  42737. * Updates a given Vector3 uniform.
  42738. *
  42739. * @param {Vector3Uniform} uniform - The Vector3 uniform.
  42740. * @return {boolean} Whether the uniform has been updated or not.
  42741. */
  42742. updateVector3( uniform ) {
  42743. let updated = false;
  42744. const a = this.values;
  42745. const v = uniform.getValue();
  42746. const offset = uniform.offset;
  42747. const type = uniform.getType();
  42748. if ( a[ offset + 0 ] !== v.x || a[ offset + 1 ] !== v.y || a[ offset + 2 ] !== v.z ) {
  42749. const b = this._getBufferForType( type );
  42750. b[ offset + 0 ] = a[ offset + 0 ] = v.x;
  42751. b[ offset + 1 ] = a[ offset + 1 ] = v.y;
  42752. b[ offset + 2 ] = a[ offset + 2 ] = v.z;
  42753. updated = true;
  42754. }
  42755. return updated;
  42756. }
  42757. /**
  42758. * Updates a given Vector4 uniform.
  42759. *
  42760. * @param {Vector4Uniform} uniform - The Vector4 uniform.
  42761. * @return {boolean} Whether the uniform has been updated or not.
  42762. */
  42763. updateVector4( uniform ) {
  42764. let updated = false;
  42765. const a = this.values;
  42766. const v = uniform.getValue();
  42767. const offset = uniform.offset;
  42768. const type = uniform.getType();
  42769. if ( a[ offset + 0 ] !== v.x || a[ offset + 1 ] !== v.y || a[ offset + 2 ] !== v.z || a[ offset + 4 ] !== v.w ) {
  42770. const b = this._getBufferForType( type );
  42771. b[ offset + 0 ] = a[ offset + 0 ] = v.x;
  42772. b[ offset + 1 ] = a[ offset + 1 ] = v.y;
  42773. b[ offset + 2 ] = a[ offset + 2 ] = v.z;
  42774. b[ offset + 3 ] = a[ offset + 3 ] = v.w;
  42775. updated = true;
  42776. }
  42777. return updated;
  42778. }
  42779. /**
  42780. * Updates a given Color uniform.
  42781. *
  42782. * @param {ColorUniform} uniform - The Color uniform.
  42783. * @return {boolean} Whether the uniform has been updated or not.
  42784. */
  42785. updateColor( uniform ) {
  42786. let updated = false;
  42787. const a = this.values;
  42788. const c = uniform.getValue();
  42789. const offset = uniform.offset;
  42790. if ( a[ offset + 0 ] !== c.r || a[ offset + 1 ] !== c.g || a[ offset + 2 ] !== c.b ) {
  42791. const b = this.buffer;
  42792. b[ offset + 0 ] = a[ offset + 0 ] = c.r;
  42793. b[ offset + 1 ] = a[ offset + 1 ] = c.g;
  42794. b[ offset + 2 ] = a[ offset + 2 ] = c.b;
  42795. updated = true;
  42796. }
  42797. return updated;
  42798. }
  42799. /**
  42800. * Updates a given Matrix3 uniform.
  42801. *
  42802. * @param {Matrix3Uniform} uniform - The Matrix3 uniform.
  42803. * @return {boolean} Whether the uniform has been updated or not.
  42804. */
  42805. updateMatrix3( uniform ) {
  42806. let updated = false;
  42807. const a = this.values;
  42808. const e = uniform.getValue().elements;
  42809. const offset = uniform.offset;
  42810. if ( a[ offset + 0 ] !== e[ 0 ] || a[ offset + 1 ] !== e[ 1 ] || a[ offset + 2 ] !== e[ 2 ] ||
  42811. a[ offset + 4 ] !== e[ 3 ] || a[ offset + 5 ] !== e[ 4 ] || a[ offset + 6 ] !== e[ 5 ] ||
  42812. a[ offset + 8 ] !== e[ 6 ] || a[ offset + 9 ] !== e[ 7 ] || a[ offset + 10 ] !== e[ 8 ] ) {
  42813. const b = this.buffer;
  42814. b[ offset + 0 ] = a[ offset + 0 ] = e[ 0 ];
  42815. b[ offset + 1 ] = a[ offset + 1 ] = e[ 1 ];
  42816. b[ offset + 2 ] = a[ offset + 2 ] = e[ 2 ];
  42817. b[ offset + 4 ] = a[ offset + 4 ] = e[ 3 ];
  42818. b[ offset + 5 ] = a[ offset + 5 ] = e[ 4 ];
  42819. b[ offset + 6 ] = a[ offset + 6 ] = e[ 5 ];
  42820. b[ offset + 8 ] = a[ offset + 8 ] = e[ 6 ];
  42821. b[ offset + 9 ] = a[ offset + 9 ] = e[ 7 ];
  42822. b[ offset + 10 ] = a[ offset + 10 ] = e[ 8 ];
  42823. updated = true;
  42824. }
  42825. return updated;
  42826. }
  42827. /**
  42828. * Updates a given Matrix4 uniform.
  42829. *
  42830. * @param {Matrix4Uniform} uniform - The Matrix4 uniform.
  42831. * @return {boolean} Whether the uniform has been updated or not.
  42832. */
  42833. updateMatrix4( uniform ) {
  42834. let updated = false;
  42835. const a = this.values;
  42836. const e = uniform.getValue().elements;
  42837. const offset = uniform.offset;
  42838. if ( arraysEqual( a, e, offset ) === false ) {
  42839. const b = this.buffer;
  42840. b.set( e, offset );
  42841. setArray( a, e, offset );
  42842. updated = true;
  42843. }
  42844. return updated;
  42845. }
  42846. /**
  42847. * Returns a typed array that matches the given data type.
  42848. *
  42849. * @private
  42850. * @param {string} type - The data type.
  42851. * @return {TypedArray} The typed array.
  42852. */
  42853. _getBufferForType( type ) {
  42854. if ( type === 'int' || type === 'ivec2' || type === 'ivec3' || type === 'ivec4' ) return new Int32Array( this.buffer.buffer );
  42855. if ( type === 'uint' || type === 'uvec2' || type === 'uvec3' || type === 'uvec4' ) return new Uint32Array( this.buffer.buffer );
  42856. return this.buffer;
  42857. }
  42858. }
  42859. /**
  42860. * Sets the values of the second array to the first array.
  42861. *
  42862. * @private
  42863. * @param {TypedArray} a - The first array.
  42864. * @param {TypedArray} b - The second array.
  42865. * @param {number} offset - An index offset for the first array.
  42866. */
  42867. function setArray( a, b, offset ) {
  42868. for ( let i = 0, l = b.length; i < l; i ++ ) {
  42869. a[ offset + i ] = b[ i ];
  42870. }
  42871. }
  42872. /**
  42873. * Returns `true` if the given arrays are equal.
  42874. *
  42875. * @private
  42876. * @param {TypedArray} a - The first array.
  42877. * @param {TypedArray} b - The second array.
  42878. * @param {number} offset - An index offset for the first array.
  42879. * @return {boolean} Whether the given arrays are equal or not.
  42880. */
  42881. function arraysEqual( a, b, offset ) {
  42882. for ( let i = 0, l = b.length; i < l; i ++ ) {
  42883. if ( a[ offset + i ] !== b[ i ] ) return false;
  42884. }
  42885. return true;
  42886. }
  42887. let _id$3 = 0;
  42888. /**
  42889. * A special form of uniforms group that represents
  42890. * the individual uniforms as node-based uniforms.
  42891. *
  42892. * @private
  42893. * @augments UniformsGroup
  42894. */
  42895. class NodeUniformsGroup extends UniformsGroup {
  42896. /**
  42897. * Constructs a new node-based uniforms group.
  42898. *
  42899. * @param {string} name - The group's name.
  42900. * @param {UniformGroupNode} groupNode - The uniform group node.
  42901. */
  42902. constructor( name, groupNode ) {
  42903. super( name );
  42904. /**
  42905. * The group's ID.
  42906. *
  42907. * @type {number}
  42908. */
  42909. this.id = _id$3 ++;
  42910. /**
  42911. * The uniform group node.
  42912. *
  42913. * @type {UniformGroupNode}
  42914. */
  42915. this.groupNode = groupNode;
  42916. /**
  42917. * This flag can be used for type testing.
  42918. *
  42919. * @type {boolean}
  42920. * @readonly
  42921. * @default true
  42922. */
  42923. this.isNodeUniformsGroup = true;
  42924. }
  42925. }
  42926. /**
  42927. * Represents a sampler binding type.
  42928. *
  42929. * @private
  42930. * @augments Binding
  42931. */
  42932. class Sampler extends Binding {
  42933. /**
  42934. * Constructs a new sampler.
  42935. *
  42936. * @param {string} name - The samplers's name.
  42937. * @param {?Texture} texture - The texture this binding is referring to.
  42938. */
  42939. constructor( name, texture ) {
  42940. super( name );
  42941. /**
  42942. * The texture the sampler is referring to.
  42943. *
  42944. * @private
  42945. * @type {?Texture}
  42946. */
  42947. this._texture = null;
  42948. /**
  42949. * An event listener which is added to {@link texture}'s dispose event.
  42950. *
  42951. * @private
  42952. * @type {Function}
  42953. */
  42954. this._onTextureDispose = () => {
  42955. this.generation = null;
  42956. this.version = 0;
  42957. };
  42958. // Assignment to the texture via a setter must occur after "_onTextureDispose" is initialized.
  42959. this.texture = texture;
  42960. /**
  42961. * The binding's version.
  42962. *
  42963. * @type {number}
  42964. */
  42965. this.version = texture ? texture.version : 0;
  42966. /**
  42967. * The binding's generation which is an additional version
  42968. * qualifier.
  42969. *
  42970. * @type {?number}
  42971. * @default null
  42972. */
  42973. this.generation = null;
  42974. /**
  42975. * The binding's sampler key.
  42976. *
  42977. * @type {string}
  42978. * @default ''
  42979. */
  42980. this.samplerKey = '';
  42981. /**
  42982. * This flag can be used for type testing.
  42983. *
  42984. * @type {boolean}
  42985. * @readonly
  42986. * @default true
  42987. */
  42988. this.isSampler = true;
  42989. }
  42990. /**
  42991. * Sets the texture of this sampler.
  42992. *
  42993. * @param {Texture} value - The texture to set.
  42994. */
  42995. set texture( value ) {
  42996. if ( this._texture === value ) return;
  42997. if ( this._texture ) {
  42998. this._texture.removeEventListener( 'dispose', this._onTextureDispose );
  42999. }
  43000. this._texture = value;
  43001. this.generation = null;
  43002. this.version = 0;
  43003. if ( this._texture ) {
  43004. this._texture.addEventListener( 'dispose', this._onTextureDispose );
  43005. }
  43006. }
  43007. /**
  43008. * Gets the texture of this sampler.
  43009. * @return {?Texture} The texture.
  43010. */
  43011. get texture() {
  43012. return this._texture;
  43013. }
  43014. /**
  43015. * Updates the binding.
  43016. *
  43017. * @return {boolean} Whether the texture has been updated and must be
  43018. * uploaded to the GPU.
  43019. */
  43020. update() {
  43021. const { texture, version } = this;
  43022. if ( version !== texture.version ) {
  43023. this.version = texture.version;
  43024. return true;
  43025. }
  43026. return false;
  43027. }
  43028. clone() {
  43029. const clonedSampler = super.clone();
  43030. // fix dispose handler for cloned instances
  43031. // TODO: Find better solution, see #31747
  43032. clonedSampler._texture = null;
  43033. clonedSampler._onTextureDispose = () => {
  43034. clonedSampler.generation = null;
  43035. clonedSampler.version = 0;
  43036. };
  43037. clonedSampler.texture = this.texture;
  43038. return clonedSampler;
  43039. }
  43040. }
  43041. let _id$2 = 0;
  43042. /**
  43043. * Represents a sampled texture binding type.
  43044. *
  43045. * @private
  43046. * @augments Sampler
  43047. */
  43048. class SampledTexture extends Sampler {
  43049. /**
  43050. * Constructs a new sampled texture.
  43051. *
  43052. * @param {string} name - The sampled texture's name.
  43053. * @param {?Texture} texture - The texture this binding is referring to.
  43054. */
  43055. constructor( name, texture ) {
  43056. super( name, texture );
  43057. /**
  43058. * This identifier.
  43059. *
  43060. * @type {number}
  43061. */
  43062. this.id = _id$2 ++;
  43063. /**
  43064. * Whether the texture is a storage texture or not.
  43065. *
  43066. * @type {boolean}
  43067. * @default false
  43068. */
  43069. this.store = false;
  43070. /**
  43071. * The mip level to bind for storage textures.
  43072. *
  43073. * @type {number}
  43074. * @default 0
  43075. */
  43076. this.mipLevel = 0;
  43077. /**
  43078. * This flag can be used for type testing.
  43079. *
  43080. * @type {boolean}
  43081. * @readonly
  43082. * @default true
  43083. */
  43084. this.isSampledTexture = true;
  43085. }
  43086. }
  43087. /**
  43088. * A special form of sampled texture binding type.
  43089. * It's texture value is managed by a node object.
  43090. *
  43091. * @private
  43092. * @augments SampledTexture
  43093. */
  43094. class NodeSampledTexture extends SampledTexture {
  43095. /**
  43096. * Constructs a new node-based sampled texture.
  43097. *
  43098. * @param {string} name - The textures's name.
  43099. * @param {TextureNode} textureNode - The texture node.
  43100. * @param {UniformGroupNode} groupNode - The uniform group node.
  43101. * @param {?string} [access=null] - The access type.
  43102. */
  43103. constructor( name, textureNode, groupNode, access = null ) {
  43104. super( name, textureNode ? textureNode.value : null );
  43105. /**
  43106. * The texture node.
  43107. *
  43108. * @type {TextureNode}
  43109. */
  43110. this.textureNode = textureNode;
  43111. /**
  43112. * The uniform group node.
  43113. *
  43114. * @type {UniformGroupNode}
  43115. */
  43116. this.groupNode = groupNode;
  43117. /**
  43118. * The access type.
  43119. *
  43120. * @type {?string}
  43121. * @default null
  43122. */
  43123. this.access = access;
  43124. }
  43125. /**
  43126. * Updates the binding.
  43127. *
  43128. * @return {boolean} Whether the texture has been updated and must be
  43129. * uploaded to the GPU.
  43130. */
  43131. update() {
  43132. const { textureNode } = this;
  43133. if ( this.texture !== textureNode.value ) {
  43134. this.texture = textureNode.value;
  43135. return true;
  43136. }
  43137. return super.update();
  43138. }
  43139. }
  43140. /**
  43141. * A special form of sampled cube texture binding type.
  43142. * It's texture value is managed by a node object.
  43143. *
  43144. * @private
  43145. * @augments NodeSampledTexture
  43146. */
  43147. class NodeSampledCubeTexture extends NodeSampledTexture {
  43148. /**
  43149. * Constructs a new node-based sampled cube texture.
  43150. *
  43151. * @param {string} name - The textures's name.
  43152. * @param {TextureNode} textureNode - The texture node.
  43153. * @param {UniformGroupNode} groupNode - The uniform group node.
  43154. * @param {?string} [access=null] - The access type.
  43155. */
  43156. constructor( name, textureNode, groupNode, access = null ) {
  43157. super( name, textureNode, groupNode, access );
  43158. /**
  43159. * This flag can be used for type testing.
  43160. *
  43161. * @type {boolean}
  43162. * @readonly
  43163. * @default true
  43164. */
  43165. this.isSampledCubeTexture = true;
  43166. }
  43167. }
  43168. /**
  43169. * A special form of sampled 3D texture binding type.
  43170. * It's texture value is managed by a node object.
  43171. *
  43172. * @private
  43173. * @augments NodeSampledTexture
  43174. */
  43175. class NodeSampledTexture3D extends NodeSampledTexture {
  43176. /**
  43177. * Constructs a new node-based sampled 3D texture.
  43178. *
  43179. * @param {string} name - The textures's name.
  43180. * @param {TextureNode} textureNode - The texture node.
  43181. * @param {UniformGroupNode} groupNode - The uniform group node.
  43182. * @param {?string} [access=null] - The access type.
  43183. */
  43184. constructor( name, textureNode, groupNode, access = null ) {
  43185. super( name, textureNode, groupNode, access );
  43186. /**
  43187. * This flag can be used for type testing.
  43188. *
  43189. * @type {boolean}
  43190. * @readonly
  43191. * @default true
  43192. */
  43193. this.isSampledTexture3D = true;
  43194. }
  43195. }
  43196. const glslPolyfills = {
  43197. bitcast_int_uint: new CodeNode( /* glsl */'uint tsl_bitcast_uint_to_int ( int x ) { return floatBitsToInt( uintBitsToFloat( x ) ); }' ),
  43198. bitcast_uint_int: new CodeNode( /* glsl */'uint tsl_bitcast_int_to_uint ( int x ) { return floatBitsToUint( intBitsToFloat ( x ) ); }' )
  43199. };
  43200. const glslMethods = {
  43201. textureDimensions: 'textureSize',
  43202. equals: 'equal',
  43203. bitcast_float_int: 'floatBitsToInt',
  43204. bitcast_int_float: 'intBitsToFloat',
  43205. bitcast_uint_float: 'uintBitsToFloat',
  43206. bitcast_float_uint: 'floatBitsToUint',
  43207. bitcast_uint_int: 'tsl_bitcast_uint_to_int',
  43208. bitcast_int_uint: 'tsl_bitcast_int_to_uint'
  43209. };
  43210. const precisionLib = {
  43211. low: 'lowp',
  43212. medium: 'mediump',
  43213. high: 'highp'
  43214. };
  43215. const supports$1 = {
  43216. swizzleAssign: true,
  43217. storageBuffer: false
  43218. };
  43219. const interpolationTypeMap = {
  43220. perspective: 'smooth',
  43221. linear: 'noperspective'
  43222. };
  43223. const interpolationModeMap = {
  43224. 'centroid': 'centroid'
  43225. };
  43226. const defaultPrecisions = `
  43227. precision highp float;
  43228. precision highp int;
  43229. precision highp sampler2D;
  43230. precision highp sampler3D;
  43231. precision highp samplerCube;
  43232. precision highp sampler2DArray;
  43233. precision highp usampler2D;
  43234. precision highp usampler3D;
  43235. precision highp usamplerCube;
  43236. precision highp usampler2DArray;
  43237. precision highp isampler2D;
  43238. precision highp isampler3D;
  43239. precision highp isamplerCube;
  43240. precision highp isampler2DArray;
  43241. precision lowp sampler2DShadow;
  43242. precision lowp sampler2DArrayShadow;
  43243. precision lowp samplerCubeShadow;
  43244. `;
  43245. /**
  43246. * A node builder targeting GLSL.
  43247. *
  43248. * This module generates GLSL shader code from node materials and also
  43249. * generates the respective bindings and vertex buffer definitions. These
  43250. * data are later used by the renderer to create render and compute pipelines
  43251. * for render objects.
  43252. *
  43253. * @augments NodeBuilder
  43254. */
  43255. class GLSLNodeBuilder extends NodeBuilder {
  43256. /**
  43257. * Constructs a new GLSL node builder renderer.
  43258. *
  43259. * @param {Object3D} object - The 3D object.
  43260. * @param {Renderer} renderer - The renderer.
  43261. */
  43262. constructor( object, renderer ) {
  43263. super( object, renderer, new GLSLNodeParser() );
  43264. /**
  43265. * A dictionary holds for each shader stage ('vertex', 'fragment', 'compute')
  43266. * another dictionary which manages UBOs per group ('render','frame','object').
  43267. *
  43268. * @type {Object<string,Object<string,NodeUniformsGroup>>}
  43269. */
  43270. this.uniformGroups = {};
  43271. /**
  43272. * An array that holds objects defining the varying and attribute data in
  43273. * context of Transform Feedback.
  43274. *
  43275. * @type {Array<Object<string,AttributeNode|string>>}
  43276. */
  43277. this.transforms = [];
  43278. /**
  43279. * A dictionary that holds for each shader stage a Map of used extensions.
  43280. *
  43281. * @type {Object<string,Map<string,Object>>}
  43282. */
  43283. this.extensions = {};
  43284. /**
  43285. * A dictionary that holds for each shader stage an Array of used builtins.
  43286. *
  43287. * @type {Object<string,Array<string>>}
  43288. */
  43289. this.builtins = { vertex: [], fragment: [], compute: [] };
  43290. }
  43291. /**
  43292. * Checks if the given texture requires a manual conversion to the working color space.
  43293. *
  43294. * @param {Texture} texture - The texture to check.
  43295. * @return {boolean} Whether the given texture requires a conversion to working color space or not.
  43296. */
  43297. needsToWorkingColorSpace( texture ) {
  43298. return texture.isVideoTexture === true && texture.colorSpace !== NoColorSpace;
  43299. }
  43300. /**
  43301. * Includes the given method name into the current
  43302. * function node.
  43303. *
  43304. * @private
  43305. * @param {string} name - The method name to include.
  43306. * @return {CodeNode} The respective code node.
  43307. */
  43308. _include( name ) {
  43309. const codeNode = glslPolyfills[ name ];
  43310. codeNode.build( this );
  43311. this.addInclude( codeNode );
  43312. return codeNode;
  43313. }
  43314. /**
  43315. * Returns the native shader method name for a given generic name.
  43316. *
  43317. * @param {string} method - The method name to resolve.
  43318. * @return {string} The resolved GLSL method name.
  43319. */
  43320. getMethod( method ) {
  43321. if ( glslPolyfills[ method ] !== undefined ) {
  43322. this._include( method );
  43323. }
  43324. return glslMethods[ method ] || method;
  43325. }
  43326. /**
  43327. * Returns the bitcast method name for a given input and outputType.
  43328. *
  43329. * @param {string} type - The output type to bitcast to.
  43330. * @param {string} inputType - The input type of the.
  43331. * @return {string} The resolved WGSL bitcast invocation.
  43332. */
  43333. getBitcastMethod( type, inputType ) {
  43334. return this.getMethod( `bitcast_${ inputType }_${ type }` );
  43335. }
  43336. /**
  43337. * Returns the native snippet for a ternary operation.
  43338. *
  43339. * @param {string} condSnippet - The condition determining which expression gets resolved.
  43340. * @param {string} ifSnippet - The expression to resolve to if the condition is true.
  43341. * @param {string} elseSnippet - The expression to resolve to if the condition is false.
  43342. * @return {string} The resolved method name.
  43343. */
  43344. getTernary( condSnippet, ifSnippet, elseSnippet ) {
  43345. return `${condSnippet} ? ${ifSnippet} : ${elseSnippet}`;
  43346. }
  43347. /**
  43348. * Returns the output struct name. Not relevant for GLSL.
  43349. *
  43350. * @return {string}
  43351. */
  43352. getOutputStructName() {
  43353. return '';
  43354. }
  43355. /**
  43356. * Builds the given shader node.
  43357. *
  43358. * @param {ShaderNodeInternal} shaderNode - The shader node.
  43359. * @return {string} The GLSL function code.
  43360. */
  43361. buildFunctionCode( shaderNode ) {
  43362. const layout = shaderNode.layout;
  43363. const flowData = this.flowShaderNode( shaderNode );
  43364. const parameters = [];
  43365. for ( const input of layout.inputs ) {
  43366. parameters.push( this.getType( input.type ) + ' ' + input.name );
  43367. }
  43368. //
  43369. const code = `${ this.getType( layout.type ) } ${ layout.name }( ${ parameters.join( ', ' ) } ) {
  43370. ${ flowData.vars }
  43371. ${ flowData.code }
  43372. return ${ flowData.result };
  43373. }`;
  43374. //
  43375. return code;
  43376. }
  43377. /**
  43378. * Setups the Pixel Buffer Object (PBO) for the given storage
  43379. * buffer node.
  43380. *
  43381. * @param {StorageBufferNode} storageBufferNode - The storage buffer node.
  43382. */
  43383. setupPBO( storageBufferNode ) {
  43384. const attribute = storageBufferNode.value;
  43385. if ( attribute.pbo === undefined ) {
  43386. const originalArray = attribute.array;
  43387. const numElements = attribute.count * attribute.itemSize;
  43388. const { itemSize } = attribute;
  43389. const isInteger = attribute.array.constructor.name.toLowerCase().includes( 'int' );
  43390. let format = isInteger ? RedIntegerFormat : RedFormat;
  43391. if ( itemSize === 2 ) {
  43392. format = isInteger ? RGIntegerFormat : RGFormat;
  43393. } else if ( itemSize === 3 ) {
  43394. format = isInteger ? RGBIntegerFormat : RGBFormat;
  43395. } else if ( itemSize === 4 ) {
  43396. format = isInteger ? RGBAIntegerFormat : RGBAFormat;
  43397. }
  43398. const typeMap = {
  43399. Float32Array: FloatType,
  43400. Uint8Array: UnsignedByteType,
  43401. Uint16Array: UnsignedShortType,
  43402. Uint32Array: UnsignedIntType,
  43403. Int8Array: ByteType,
  43404. Int16Array: ShortType,
  43405. Int32Array: IntType,
  43406. Uint8ClampedArray: UnsignedByteType,
  43407. };
  43408. const width = Math.pow( 2, Math.ceil( Math.log2( Math.sqrt( numElements / itemSize ) ) ) );
  43409. let height = Math.ceil( ( numElements / itemSize ) / width );
  43410. if ( width * height * itemSize < numElements ) height ++; // Ensure enough space
  43411. const newSize = width * height * itemSize;
  43412. const newArray = new originalArray.constructor( newSize );
  43413. newArray.set( originalArray, 0 );
  43414. attribute.array = newArray;
  43415. const pboTexture = new DataTexture( attribute.array, width, height, format, typeMap[ attribute.array.constructor.name ] || FloatType );
  43416. pboTexture.needsUpdate = true;
  43417. pboTexture.isPBOTexture = true;
  43418. const pbo = new TextureNode( pboTexture, null, null );
  43419. pbo.setPrecision( 'high' );
  43420. attribute.pboNode = pbo;
  43421. attribute.pbo = pbo.value;
  43422. this.getUniformFromNode( attribute.pboNode, 'texture', this.shaderStage, this.context.nodeName );
  43423. }
  43424. }
  43425. /**
  43426. * Returns a GLSL snippet that represents the property name of the given node.
  43427. *
  43428. * @param {Node} node - The node.
  43429. * @param {string} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  43430. * @return {string} The property name.
  43431. */
  43432. getPropertyName( node, shaderStage = this.shaderStage ) {
  43433. if ( node.isNodeUniform && node.node.isTextureNode !== true && node.node.isBufferNode !== true ) {
  43434. return shaderStage.charAt( 0 ) + '_' + node.name;
  43435. }
  43436. return super.getPropertyName( node, shaderStage );
  43437. }
  43438. /**
  43439. * Setups the Pixel Buffer Object (PBO) for the given storage
  43440. * buffer node.
  43441. *
  43442. * @param {StorageArrayElementNode} storageArrayElementNode - The storage array element node.
  43443. * @return {string} The property name.
  43444. */
  43445. generatePBO( storageArrayElementNode ) {
  43446. const { node, indexNode } = storageArrayElementNode;
  43447. const attribute = node.value;
  43448. if ( this.renderer.backend.has( attribute ) ) {
  43449. const attributeData = this.renderer.backend.get( attribute );
  43450. attributeData.pbo = attribute.pbo;
  43451. }
  43452. const nodeUniform = this.getUniformFromNode( attribute.pboNode, 'texture', this.shaderStage, this.context.nodeName );
  43453. const textureName = this.getPropertyName( nodeUniform );
  43454. this.increaseUsage( indexNode ); // force cache generate to be used as index in x,y
  43455. const indexSnippet = indexNode.build( this, 'uint' );
  43456. const elementNodeData = this.getDataFromNode( storageArrayElementNode );
  43457. let propertyName = elementNodeData.propertyName;
  43458. if ( propertyName === undefined ) {
  43459. // property element
  43460. const nodeVar = this.getVarFromNode( storageArrayElementNode );
  43461. propertyName = this.getPropertyName( nodeVar );
  43462. // property size
  43463. const bufferNodeData = this.getDataFromNode( node );
  43464. let propertySizeName = bufferNodeData.propertySizeName;
  43465. if ( propertySizeName === undefined ) {
  43466. propertySizeName = propertyName + 'Size';
  43467. this.getVarFromNode( node, propertySizeName, 'uint' );
  43468. this.addLineFlowCode( `${ propertySizeName } = uint( textureSize( ${ textureName }, 0 ).x )`, storageArrayElementNode );
  43469. bufferNodeData.propertySizeName = propertySizeName;
  43470. }
  43471. //
  43472. const { itemSize } = attribute;
  43473. const channel = '.' + vectorComponents.join( '' ).slice( 0, itemSize );
  43474. const uvSnippet = `ivec2(${indexSnippet} % ${ propertySizeName }, ${indexSnippet} / ${ propertySizeName })`;
  43475. const snippet = this.generateTextureLoad( null, textureName, uvSnippet, '0', null, null );
  43476. //
  43477. let prefix = 'vec4';
  43478. if ( attribute.pbo.type === UnsignedIntType ) {
  43479. prefix = 'uvec4';
  43480. } else if ( attribute.pbo.type === IntType ) {
  43481. prefix = 'ivec4';
  43482. }
  43483. this.addLineFlowCode( `${ propertyName } = ${prefix}(${ snippet })${channel}`, storageArrayElementNode );
  43484. elementNodeData.propertyName = propertyName;
  43485. }
  43486. return propertyName;
  43487. }
  43488. /**
  43489. * Generates the GLSL snippet that reads a single texel from a texture without sampling or filtering.
  43490. *
  43491. * @param {?Texture} texture - The texture.
  43492. * @param {string} textureProperty - The name of the texture uniform in the shader.
  43493. * @param {string} uvIndexSnippet - A GLSL snippet that represents texture coordinates used for sampling.
  43494. * @param {?string} levelSnippet - A GLSL snippet that represents the mip level, with level 0 containing a full size version of the texture.
  43495. * @param {?string} depthSnippet - A GLSL snippet that represents the 0-based texture array index to sample.
  43496. * @param {?string} offsetSnippet - A GLSL snippet that represents the offset that will be applied to the unnormalized texture coordinate before sampling the texture.
  43497. * @return {string} The GLSL snippet.
  43498. */
  43499. generateTextureLoad( texture, textureProperty, uvIndexSnippet, levelSnippet, depthSnippet, offsetSnippet ) {
  43500. if ( levelSnippet === null ) levelSnippet = '0';
  43501. let snippet;
  43502. if ( depthSnippet ) {
  43503. if ( offsetSnippet ) {
  43504. snippet = `texelFetchOffset( ${ textureProperty }, ivec3( ${ uvIndexSnippet }, ${ depthSnippet } ), ${ levelSnippet }, ${ offsetSnippet } )`;
  43505. } else {
  43506. snippet = `texelFetch( ${ textureProperty }, ivec3( ${ uvIndexSnippet }, ${ depthSnippet } ), ${ levelSnippet } )`;
  43507. }
  43508. } else {
  43509. if ( offsetSnippet ) {
  43510. snippet = `texelFetchOffset( ${ textureProperty }, ${ uvIndexSnippet }, ${ levelSnippet }, ${ offsetSnippet } )`;
  43511. } else {
  43512. snippet = `texelFetch( ${ textureProperty }, ${ uvIndexSnippet }, ${ levelSnippet } )`;
  43513. }
  43514. }
  43515. if ( texture !== null && texture.isDepthTexture ) {
  43516. snippet += '.x';
  43517. }
  43518. return snippet;
  43519. }
  43520. /**
  43521. * Generates the GLSL snippet for sampling/loading the given texture.
  43522. *
  43523. * @param {Texture} texture - The texture.
  43524. * @param {string} textureProperty - The name of the texture uniform in the shader.
  43525. * @param {string} uvSnippet - A GLSL snippet that represents texture coordinates used for sampling.
  43526. * @param {?string} depthSnippet - A GLSL snippet that represents the 0-based texture array index to sample.
  43527. * @param {?string} offsetSnippet - A GLSL snippet that represents the offset that will be applied to the unnormalized texture coordinate before sampling the texture.
  43528. * @return {string} The GLSL snippet.
  43529. */
  43530. generateTexture( texture, textureProperty, uvSnippet, depthSnippet, offsetSnippet ) {
  43531. if ( depthSnippet ) uvSnippet = `vec3( ${ uvSnippet }, ${ depthSnippet } )`;
  43532. if ( texture.isDepthTexture ) {
  43533. if ( offsetSnippet ) return `textureOffset( ${ textureProperty }, ${ uvSnippet }, ${ offsetSnippet } ).x`;
  43534. return `texture( ${ textureProperty }, ${ uvSnippet } ).x`;
  43535. }
  43536. if ( offsetSnippet ) return `textureOffset( ${ textureProperty }, ${ uvSnippet }, ${ offsetSnippet } )`;
  43537. return `texture( ${ textureProperty }, ${ uvSnippet } )`;
  43538. }
  43539. /**
  43540. * Generates the GLSL snippet when sampling textures with explicit mip level.
  43541. *
  43542. * @param {Texture} texture - The texture.
  43543. * @param {string} textureProperty - The name of the texture uniform in the shader.
  43544. * @param {string} uvSnippet - A GLSL snippet that represents texture coordinates used for sampling.
  43545. * @param {string} levelSnippet - A GLSL snippet that represents the mip level, with level 0 containing a full size version of the texture.
  43546. * @param {?string} offsetSnippet - A GLSL snippet that represents the offset that will be applied to the unnormalized texture coordinate before sampling the texture.
  43547. * @return {string} The GLSL snippet.
  43548. */
  43549. generateTextureLevel( texture, textureProperty, uvSnippet, levelSnippet, offsetSnippet ) {
  43550. if ( offsetSnippet ) {
  43551. return `textureLodOffset( ${ textureProperty }, ${ uvSnippet }, ${ levelSnippet }, ${ offsetSnippet } )`;
  43552. }
  43553. return `textureLod( ${ textureProperty }, ${ uvSnippet }, ${ levelSnippet } )`;
  43554. }
  43555. /**
  43556. * Generates the GLSL snippet when sampling textures with a bias to the mip level.
  43557. *
  43558. * @param {Texture} texture - The texture.
  43559. * @param {string} textureProperty - The name of the texture uniform in the shader.
  43560. * @param {string} uvSnippet - A GLSL snippet that represents texture coordinates used for sampling.
  43561. * @param {string} biasSnippet - A GLSL snippet that represents the bias to apply to the mip level before sampling.
  43562. * @param {?string} offsetSnippet - A GLSL snippet that represents the offset that will be applied to the unnormalized texture coordinate before sampling the texture.
  43563. * @return {string} The GLSL snippet.
  43564. */
  43565. generateTextureBias( texture, textureProperty, uvSnippet, biasSnippet, offsetSnippet ) {
  43566. if ( offsetSnippet ) {
  43567. return `textureOffset( ${ textureProperty }, ${ uvSnippet }, ${ offsetSnippet }, ${ biasSnippet } )`;
  43568. }
  43569. return `texture( ${ textureProperty }, ${ uvSnippet }, ${ biasSnippet } )`;
  43570. }
  43571. /**
  43572. * Generates the GLSL snippet for sampling/loading the given texture using explicit gradients.
  43573. *
  43574. * @param {Texture} texture - The texture.
  43575. * @param {string} textureProperty - The name of the texture uniform in the shader.
  43576. * @param {string} uvSnippet - A GLSL snippet that represents texture coordinates used for sampling.
  43577. * @param {Array<string>} gradSnippet - An array holding both gradient GLSL snippets.
  43578. * @param {?string} offsetSnippet - A GLSL snippet that represents the offset that will be applied to the unnormalized texture coordinate before sampling the texture.
  43579. * @return {string} The GLSL snippet.
  43580. */
  43581. generateTextureGrad( texture, textureProperty, uvSnippet, gradSnippet, offsetSnippet ) {
  43582. if ( offsetSnippet ) {
  43583. return `textureGradOffset( ${ textureProperty }, ${ uvSnippet }, ${ gradSnippet[ 0 ] }, ${ gradSnippet[ 1 ] }, ${ offsetSnippet } )`;
  43584. }
  43585. return `textureGrad( ${ textureProperty }, ${ uvSnippet }, ${ gradSnippet[ 0 ] }, ${ gradSnippet[ 1 ] } )`;
  43586. }
  43587. /**
  43588. * Generates the GLSL snippet for sampling a depth texture and comparing the sampled depth values
  43589. * against a reference value.
  43590. *
  43591. * @param {Texture} texture - The texture.
  43592. * @param {string} textureProperty - The name of the texture uniform in the shader.
  43593. * @param {string} uvSnippet - A GLSL snippet that represents texture coordinates used for sampling.
  43594. * @param {string} compareSnippet - A GLSL snippet that represents the reference value.
  43595. * @param {?string} depthSnippet - A GLSL snippet that represents 0-based texture array index to sample.
  43596. * @param {?string} offsetSnippet - A GLSL snippet that represents the offset that will be applied to the unnormalized texture coordinate before sampling the texture.
  43597. * @param {string} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  43598. * @return {string} The GLSL snippet.
  43599. */
  43600. generateTextureCompare( texture, textureProperty, uvSnippet, compareSnippet, depthSnippet, offsetSnippet, shaderStage = this.shaderStage ) {
  43601. if ( shaderStage === 'fragment' ) {
  43602. if ( depthSnippet ) {
  43603. if ( offsetSnippet ) {
  43604. return `textureOffset( ${ textureProperty }, vec4( ${ uvSnippet }, ${ depthSnippet }, ${ compareSnippet } ), ${ offsetSnippet } )`;
  43605. }
  43606. return `texture( ${ textureProperty }, vec4( ${ uvSnippet }, ${ depthSnippet }, ${ compareSnippet } ) )`;
  43607. }
  43608. if ( offsetSnippet ) {
  43609. return `textureOffset( ${ textureProperty }, vec3( ${ uvSnippet }, ${ compareSnippet } ), ${ offsetSnippet } )`;
  43610. }
  43611. return `texture( ${ textureProperty }, vec3( ${ uvSnippet }, ${ compareSnippet } ) )`;
  43612. } else {
  43613. error( `WebGPURenderer: THREE.DepthTexture.compareFunction() does not support ${ shaderStage } shader.` );
  43614. }
  43615. }
  43616. /**
  43617. * Returns the variables of the given shader stage as a GLSL string.
  43618. *
  43619. * @param {string} shaderStage - The shader stage.
  43620. * @return {string} The GLSL snippet that defines the variables.
  43621. */
  43622. getVars( shaderStage ) {
  43623. const snippets = [];
  43624. const vars = this.vars[ shaderStage ];
  43625. if ( vars !== undefined ) {
  43626. for ( const variable of vars ) {
  43627. snippets.push( `${ this.getVar( variable.type, variable.name, variable.count ) };` );
  43628. }
  43629. }
  43630. return snippets.join( '\n\t' );
  43631. }
  43632. /**
  43633. * Returns the uniforms of the given shader stage as a GLSL string.
  43634. *
  43635. * @param {string} shaderStage - The shader stage.
  43636. * @return {string} The GLSL snippet that defines the uniforms.
  43637. */
  43638. getUniforms( shaderStage ) {
  43639. const uniforms = this.uniforms[ shaderStage ];
  43640. const bindingSnippets = [];
  43641. const uniformGroups = {};
  43642. for ( const uniform of uniforms ) {
  43643. let snippet = null;
  43644. let group = false;
  43645. if ( uniform.type === 'texture' || uniform.type === 'texture3D' ) {
  43646. const texture = uniform.node.value;
  43647. let typePrefix = '';
  43648. if ( texture.isDataTexture === true || texture.isData3DTexture === true ) {
  43649. if ( texture.type === UnsignedIntType ) {
  43650. typePrefix = 'u';
  43651. } else if ( texture.type === IntType ) {
  43652. typePrefix = 'i';
  43653. }
  43654. }
  43655. if ( uniform.type === 'texture3D' && texture.isArrayTexture === false ) {
  43656. snippet = `${typePrefix}sampler3D ${ uniform.name };`;
  43657. } else if ( texture.compareFunction ) {
  43658. if ( texture.isArrayTexture === true ) {
  43659. snippet = `sampler2DArrayShadow ${ uniform.name };`;
  43660. } else {
  43661. snippet = `sampler2DShadow ${ uniform.name };`;
  43662. }
  43663. } else if ( texture.isArrayTexture === true || texture.isDataArrayTexture === true || texture.isCompressedArrayTexture === true ) {
  43664. snippet = `${typePrefix}sampler2DArray ${ uniform.name };`;
  43665. } else {
  43666. snippet = `${typePrefix}sampler2D ${ uniform.name };`;
  43667. }
  43668. } else if ( uniform.type === 'cubeTexture' ) {
  43669. snippet = `samplerCube ${ uniform.name };`;
  43670. } else if ( uniform.type === 'buffer' ) {
  43671. const bufferNode = uniform.node;
  43672. const bufferType = this.getType( bufferNode.bufferType );
  43673. const bufferCount = bufferNode.bufferCount;
  43674. const bufferCountSnippet = bufferCount > 0 ? bufferCount : '';
  43675. snippet = `${bufferNode.name} {\n\t${ bufferType } ${ uniform.name }[${ bufferCountSnippet }];\n};\n`;
  43676. } else {
  43677. const vectorType = this.getVectorType( uniform.type );
  43678. snippet = `${ vectorType } ${ this.getPropertyName( uniform, shaderStage ) };`;
  43679. group = true;
  43680. }
  43681. const precision = uniform.node.precision;
  43682. if ( precision !== null ) {
  43683. snippet = precisionLib[ precision ] + ' ' + snippet;
  43684. }
  43685. if ( group ) {
  43686. snippet = '\t' + snippet;
  43687. const groupName = uniform.groupNode.name;
  43688. const groupSnippets = uniformGroups[ groupName ] || ( uniformGroups[ groupName ] = [] );
  43689. groupSnippets.push( snippet );
  43690. } else {
  43691. snippet = 'uniform ' + snippet;
  43692. bindingSnippets.push( snippet );
  43693. }
  43694. }
  43695. let output = '';
  43696. for ( const name in uniformGroups ) {
  43697. const groupSnippets = uniformGroups[ name ];
  43698. output += this._getGLSLUniformStruct( shaderStage + '_' + name, groupSnippets.join( '\n' ) ) + '\n';
  43699. }
  43700. output += bindingSnippets.join( '\n' );
  43701. return output;
  43702. }
  43703. /**
  43704. * Returns the type for a given buffer attribute.
  43705. *
  43706. * @param {BufferAttribute} attribute - The buffer attribute.
  43707. * @return {string} The type.
  43708. */
  43709. getTypeFromAttribute( attribute ) {
  43710. let nodeType = super.getTypeFromAttribute( attribute );
  43711. if ( /^[iu]/.test( nodeType ) && attribute.gpuType !== IntType ) {
  43712. let dataAttribute = attribute;
  43713. if ( attribute.isInterleavedBufferAttribute ) dataAttribute = attribute.data;
  43714. const array = dataAttribute.array;
  43715. if ( ( array instanceof Uint32Array || array instanceof Int32Array ) === false ) {
  43716. nodeType = nodeType.slice( 1 );
  43717. }
  43718. }
  43719. return nodeType;
  43720. }
  43721. /**
  43722. * Returns the shader attributes of the given shader stage as a GLSL string.
  43723. *
  43724. * @param {string} shaderStage - The shader stage.
  43725. * @return {string} The GLSL snippet that defines the shader attributes.
  43726. */
  43727. getAttributes( shaderStage ) {
  43728. let snippet = '';
  43729. if ( shaderStage === 'vertex' || shaderStage === 'compute' ) {
  43730. const attributes = this.getAttributesArray();
  43731. let location = 0;
  43732. for ( const attribute of attributes ) {
  43733. snippet += `layout( location = ${ location ++ } ) in ${ attribute.type } ${ attribute.name };\n`;
  43734. }
  43735. }
  43736. return snippet;
  43737. }
  43738. /**
  43739. * Returns the members of the given struct type node as a GLSL string.
  43740. *
  43741. * @param {StructTypeNode} struct - The struct type node.
  43742. * @return {string} The GLSL snippet that defines the struct members.
  43743. */
  43744. getStructMembers( struct ) {
  43745. const snippets = [];
  43746. for ( const member of struct.members ) {
  43747. snippets.push( `\t${ member.type } ${ member.name };` );
  43748. }
  43749. return snippets.join( '\n' );
  43750. }
  43751. /**
  43752. * Returns the structs of the given shader stage as a GLSL string.
  43753. *
  43754. * @param {string} shaderStage - The shader stage.
  43755. * @return {string} The GLSL snippet that defines the structs.
  43756. */
  43757. getStructs( shaderStage ) {
  43758. const snippets = [];
  43759. const structs = this.structs[ shaderStage ];
  43760. const outputSnippet = [];
  43761. for ( const struct of structs ) {
  43762. if ( struct.output ) {
  43763. for ( const member of struct.members ) {
  43764. outputSnippet.push( `layout( location = ${ member.index } ) out ${ member.type } ${ member.name };` );
  43765. }
  43766. } else {
  43767. let snippet = 'struct ' + struct.name + ' {\n';
  43768. snippet += this.getStructMembers( struct );
  43769. snippet += '\n};\n';
  43770. snippets.push( snippet );
  43771. }
  43772. }
  43773. if ( outputSnippet.length === 0 ) {
  43774. outputSnippet.push( 'layout( location = 0 ) out vec4 fragColor;' );
  43775. }
  43776. return '\n' + outputSnippet.join( '\n' ) + '\n\n' + snippets.join( '\n' );
  43777. }
  43778. /**
  43779. * Returns the varyings of the given shader stage as a GLSL string.
  43780. *
  43781. * @param {string} shaderStage - The shader stage.
  43782. * @return {string} The GLSL snippet that defines the varyings.
  43783. */
  43784. getVaryings( shaderStage ) {
  43785. let snippet = '';
  43786. const varyings = this.varyings;
  43787. if ( shaderStage === 'vertex' || shaderStage === 'compute' ) {
  43788. for ( const varying of varyings ) {
  43789. if ( shaderStage === 'compute' ) varying.needsInterpolation = true;
  43790. const type = this.getType( varying.type );
  43791. if ( varying.needsInterpolation ) {
  43792. if ( varying.interpolationType ) {
  43793. const interpolationType = interpolationTypeMap[ varying.interpolationType ] || varying.interpolationType;
  43794. const sampling = interpolationModeMap[ varying.interpolationSampling ] || '';
  43795. snippet += `${ interpolationType } ${ sampling } out ${ type } ${ varying.name };\n`;
  43796. } else {
  43797. const flat = type.includes( 'int' ) || type.includes( 'uv' ) || type.includes( 'iv' ) ? 'flat ' : '';
  43798. snippet += `${ flat }out ${ type } ${ varying.name };\n`;
  43799. }
  43800. } else {
  43801. snippet += `${type} ${varying.name};\n`; // generate variable (no varying required)
  43802. }
  43803. }
  43804. } else if ( shaderStage === 'fragment' ) {
  43805. for ( const varying of varyings ) {
  43806. if ( varying.needsInterpolation ) {
  43807. const type = this.getType( varying.type );
  43808. if ( varying.interpolationType ) {
  43809. const interpolationType = interpolationTypeMap[ varying.interpolationType ] || varying.interpolationType;
  43810. const sampling = interpolationModeMap[ varying.interpolationSampling ] || '';
  43811. snippet += `${ interpolationType } ${ sampling } in ${ type } ${ varying.name };\n`;
  43812. } else {
  43813. const flat = type.includes( 'int' ) || type.includes( 'uv' ) || type.includes( 'iv' ) ? 'flat ' : '';
  43814. snippet += `${ flat }in ${ type } ${ varying.name };\n`;
  43815. }
  43816. }
  43817. }
  43818. }
  43819. for ( const builtin of this.builtins[ shaderStage ] ) {
  43820. snippet += `${builtin};\n`;
  43821. }
  43822. return snippet;
  43823. }
  43824. /**
  43825. * Returns the vertex index builtin.
  43826. *
  43827. * @return {string} The vertex index.
  43828. */
  43829. getVertexIndex() {
  43830. return 'uint( gl_VertexID )';
  43831. }
  43832. /**
  43833. * Contextually returns either the vertex stage instance index builtin
  43834. * or the linearized index of an compute invocation within a grid of workgroups.
  43835. *
  43836. * @return {string} The instance index.
  43837. */
  43838. getInstanceIndex() {
  43839. return 'uint( gl_InstanceID )';
  43840. }
  43841. /**
  43842. * Returns a builtin representing the index of an invocation within its workgroup.
  43843. *
  43844. * @return {string} The invocation local index.
  43845. */
  43846. getInvocationLocalIndex() {
  43847. const workgroupSize = this.object.workgroupSize;
  43848. const size = workgroupSize.reduce( ( acc, curr ) => acc * curr, 1 );
  43849. return `uint( gl_InstanceID ) % ${size}u`;
  43850. }
  43851. /**
  43852. * Returns a builtin representing the size of a subgroup within the current shader.
  43853. */
  43854. getSubgroupSize() {
  43855. error( 'GLSLNodeBuilder: WebGLBackend does not support the subgroupSize node' );
  43856. }
  43857. /**
  43858. * Returns a builtin representing the index of an invocation within its subgroup.
  43859. */
  43860. getInvocationSubgroupIndex() {
  43861. error( 'GLSLNodeBuilder: WebGLBackend does not support the invocationSubgroupIndex node' );
  43862. }
  43863. /**
  43864. * Returns a builtin representing the index of the current invocation's subgroup within its workgroup.
  43865. */
  43866. getSubgroupIndex() {
  43867. error( 'GLSLNodeBuilder: WebGLBackend does not support the subgroupIndex node' );
  43868. }
  43869. /**
  43870. * Returns the draw index builtin.
  43871. *
  43872. * @return {?string} The drawIndex shader string. Returns `null` if `WEBGL_multi_draw` isn't supported by the device.
  43873. */
  43874. getDrawIndex() {
  43875. const extensions = this.renderer.backend.extensions;
  43876. if ( extensions.has( 'WEBGL_multi_draw' ) ) {
  43877. return 'uint( gl_DrawID )';
  43878. }
  43879. return null;
  43880. }
  43881. /**
  43882. * Returns the front facing builtin.
  43883. *
  43884. * @return {string} The front facing builtin.
  43885. */
  43886. getFrontFacing() {
  43887. return 'gl_FrontFacing';
  43888. }
  43889. /**
  43890. * Returns the frag coord builtin.
  43891. *
  43892. * @return {string} The frag coord builtin.
  43893. */
  43894. getFragCoord() {
  43895. return 'gl_FragCoord.xy';
  43896. }
  43897. /**
  43898. * Returns the frag depth builtin.
  43899. *
  43900. * @return {string} The frag depth builtin.
  43901. */
  43902. getFragDepth() {
  43903. return 'gl_FragDepth';
  43904. }
  43905. /**
  43906. * Enables the given extension.
  43907. *
  43908. * @param {string} name - The extension name.
  43909. * @param {string} behavior - The extension behavior.
  43910. * @param {string} [shaderStage=this.shaderStage] - The shader stage.
  43911. */
  43912. enableExtension( name, behavior, shaderStage = this.shaderStage ) {
  43913. const map = this.extensions[ shaderStage ] || ( this.extensions[ shaderStage ] = new Map() );
  43914. if ( map.has( name ) === false ) {
  43915. map.set( name, {
  43916. name,
  43917. behavior
  43918. } );
  43919. }
  43920. }
  43921. /**
  43922. * Returns the enabled extensions of the given shader stage as a GLSL string.
  43923. *
  43924. * @param {string} shaderStage - The shader stage.
  43925. * @return {string} The GLSL snippet that defines the enabled extensions.
  43926. */
  43927. getExtensions( shaderStage ) {
  43928. const snippets = [];
  43929. if ( shaderStage === 'vertex' ) {
  43930. const ext = this.renderer.backend.extensions;
  43931. const isBatchedMesh = this.object.isBatchedMesh;
  43932. if ( isBatchedMesh && ext.has( 'WEBGL_multi_draw' ) ) {
  43933. this.enableExtension( 'GL_ANGLE_multi_draw', 'require', shaderStage );
  43934. }
  43935. }
  43936. const extensions = this.extensions[ shaderStage ];
  43937. if ( extensions !== undefined ) {
  43938. for ( const { name, behavior } of extensions.values() ) {
  43939. snippets.push( `#extension ${name} : ${behavior}` );
  43940. }
  43941. }
  43942. return snippets.join( '\n' );
  43943. }
  43944. /**
  43945. * Returns the clip distances builtin.
  43946. *
  43947. * @return {string} The clip distances builtin.
  43948. */
  43949. getClipDistance() {
  43950. return 'gl_ClipDistance';
  43951. }
  43952. /**
  43953. * Whether the requested feature is available or not.
  43954. *
  43955. * @param {string} name - The requested feature.
  43956. * @return {boolean} Whether the requested feature is supported or not.
  43957. */
  43958. isAvailable( name ) {
  43959. let result = supports$1[ name ];
  43960. if ( result === undefined ) {
  43961. let extensionName;
  43962. result = false;
  43963. switch ( name ) {
  43964. case 'float32Filterable':
  43965. extensionName = 'OES_texture_float_linear';
  43966. break;
  43967. case 'clipDistance':
  43968. extensionName = 'WEBGL_clip_cull_distance';
  43969. break;
  43970. }
  43971. if ( extensionName !== undefined ) {
  43972. const extensions = this.renderer.backend.extensions;
  43973. if ( extensions.has( extensionName ) ) {
  43974. extensions.get( extensionName );
  43975. result = true;
  43976. }
  43977. }
  43978. supports$1[ name ] = result;
  43979. }
  43980. return result;
  43981. }
  43982. /**
  43983. * Whether to flip texture data along its vertical axis or not.
  43984. *
  43985. * @return {boolean} Returns always `true` in context of GLSL.
  43986. */
  43987. isFlipY() {
  43988. return true;
  43989. }
  43990. /**
  43991. * Enables hardware clipping.
  43992. *
  43993. * @param {string} planeCount - The clipping plane count.
  43994. */
  43995. enableHardwareClipping( planeCount ) {
  43996. this.enableExtension( 'GL_ANGLE_clip_cull_distance', 'require' );
  43997. this.builtins[ 'vertex' ].push( `out float gl_ClipDistance[ ${ planeCount } ]` );
  43998. }
  43999. /**
  44000. * Enables multiview.
  44001. */
  44002. enableMultiview() {
  44003. this.enableExtension( 'GL_OVR_multiview2', 'require', 'fragment' );
  44004. this.enableExtension( 'GL_OVR_multiview2', 'require', 'vertex' );
  44005. this.builtins[ 'vertex' ].push( 'layout(num_views = 2) in' );
  44006. }
  44007. /**
  44008. * Registers a transform in context of Transform Feedback.
  44009. *
  44010. * @param {string} varyingName - The varying name.
  44011. * @param {AttributeNode} attributeNode - The attribute node.
  44012. */
  44013. registerTransform( varyingName, attributeNode ) {
  44014. this.transforms.push( { varyingName, attributeNode } );
  44015. }
  44016. /**
  44017. * Returns the transforms of the given shader stage as a GLSL string.
  44018. *
  44019. * @param {string} shaderStage - The shader stage.
  44020. * @return {string} The GLSL snippet that defines the transforms.
  44021. */
  44022. getTransforms( /* shaderStage */ ) {
  44023. const transforms = this.transforms;
  44024. let snippet = '';
  44025. for ( let i = 0; i < transforms.length; i ++ ) {
  44026. const transform = transforms[ i ];
  44027. const attributeName = this.getPropertyName( transform.attributeNode );
  44028. if ( attributeName ) snippet += `${ transform.varyingName } = ${ attributeName };\n\t`;
  44029. }
  44030. return snippet;
  44031. }
  44032. /**
  44033. * Returns a GLSL struct based on the given name and variables.
  44034. *
  44035. * @private
  44036. * @param {string} name - The struct name.
  44037. * @param {string} vars - The struct variables.
  44038. * @return {string} The GLSL snippet representing a struct.
  44039. */
  44040. _getGLSLUniformStruct( name, vars ) {
  44041. return `
  44042. layout( std140 ) uniform ${name} {
  44043. ${vars}
  44044. };`;
  44045. }
  44046. /**
  44047. * Returns a GLSL vertex shader based on the given shader data.
  44048. *
  44049. * @private
  44050. * @param {Object} shaderData - The shader data.
  44051. * @return {string} The vertex shader.
  44052. */
  44053. _getGLSLVertexCode( shaderData ) {
  44054. return `#version 300 es
  44055. ${ this.getSignature() }
  44056. // extensions
  44057. ${shaderData.extensions}
  44058. // precision
  44059. ${ defaultPrecisions }
  44060. // uniforms
  44061. ${shaderData.uniforms}
  44062. // varyings
  44063. ${shaderData.varyings}
  44064. // attributes
  44065. ${shaderData.attributes}
  44066. // codes
  44067. ${shaderData.codes}
  44068. void main() {
  44069. // vars
  44070. ${shaderData.vars}
  44071. // transforms
  44072. ${shaderData.transforms}
  44073. // flow
  44074. ${shaderData.flow}
  44075. gl_PointSize = 1.0;
  44076. }
  44077. `;
  44078. }
  44079. /**
  44080. * Returns a GLSL fragment shader based on the given shader data.
  44081. *
  44082. * @private
  44083. * @param {Object} shaderData - The shader data.
  44084. * @return {string} The vertex shader.
  44085. */
  44086. _getGLSLFragmentCode( shaderData ) {
  44087. return `#version 300 es
  44088. ${ this.getSignature() }
  44089. // extensions
  44090. ${shaderData.extensions}
  44091. // precision
  44092. ${ defaultPrecisions }
  44093. // structs
  44094. ${shaderData.structs}
  44095. // uniforms
  44096. ${shaderData.uniforms}
  44097. // varyings
  44098. ${shaderData.varyings}
  44099. // codes
  44100. ${shaderData.codes}
  44101. void main() {
  44102. // vars
  44103. ${shaderData.vars}
  44104. // flow
  44105. ${shaderData.flow}
  44106. }
  44107. `;
  44108. }
  44109. /**
  44110. * Controls the code build of the shader stages.
  44111. */
  44112. buildCode() {
  44113. const shadersData = this.material !== null ? { fragment: {}, vertex: {} } : { compute: {} };
  44114. this.sortBindingGroups();
  44115. for ( const shaderStage in shadersData ) {
  44116. let flow = '// code\n\n';
  44117. flow += this.flowCode[ shaderStage ];
  44118. const flowNodes = this.flowNodes[ shaderStage ];
  44119. const mainNode = flowNodes[ flowNodes.length - 1 ];
  44120. for ( const node of flowNodes ) {
  44121. const flowSlotData = this.getFlowData( node/*, shaderStage*/ );
  44122. const slotName = node.name;
  44123. if ( slotName ) {
  44124. if ( flow.length > 0 ) flow += '\n';
  44125. flow += `\t// flow -> ${ slotName }\n\t`;
  44126. }
  44127. flow += `${ flowSlotData.code }\n\t`;
  44128. if ( node === mainNode && shaderStage !== 'compute' ) {
  44129. flow += '// result\n\t';
  44130. if ( shaderStage === 'vertex' ) {
  44131. flow += 'gl_Position = ';
  44132. flow += `${ flowSlotData.result };`;
  44133. } else if ( shaderStage === 'fragment' ) {
  44134. if ( ! node.outputNode.isOutputStructNode ) {
  44135. flow += 'fragColor = ';
  44136. flow += `${ flowSlotData.result };`;
  44137. }
  44138. }
  44139. }
  44140. }
  44141. const stageData = shadersData[ shaderStage ];
  44142. stageData.extensions = this.getExtensions( shaderStage );
  44143. stageData.uniforms = this.getUniforms( shaderStage );
  44144. stageData.attributes = this.getAttributes( shaderStage );
  44145. stageData.varyings = this.getVaryings( shaderStage );
  44146. stageData.vars = this.getVars( shaderStage );
  44147. stageData.structs = this.getStructs( shaderStage );
  44148. stageData.codes = this.getCodes( shaderStage );
  44149. stageData.transforms = this.getTransforms( shaderStage );
  44150. stageData.flow = flow;
  44151. }
  44152. if ( this.material !== null ) {
  44153. this.vertexShader = this._getGLSLVertexCode( shadersData.vertex );
  44154. this.fragmentShader = this._getGLSLFragmentCode( shadersData.fragment );
  44155. } else {
  44156. this.computeShader = this._getGLSLVertexCode( shadersData.compute );
  44157. }
  44158. }
  44159. /**
  44160. * This method is one of the more important ones since it's responsible
  44161. * for generating a matching binding instance for the given uniform node.
  44162. *
  44163. * These bindings are later used in the renderer to create bind groups
  44164. * and layouts.
  44165. *
  44166. * @param {UniformNode} node - The uniform node.
  44167. * @param {string} type - The node data type.
  44168. * @param {string} shaderStage - The shader stage.
  44169. * @param {?string} [name=null] - An optional uniform name.
  44170. * @return {NodeUniform} The node uniform object.
  44171. */
  44172. getUniformFromNode( node, type, shaderStage, name = null ) {
  44173. const uniformNode = super.getUniformFromNode( node, type, shaderStage, name );
  44174. const nodeData = this.getDataFromNode( node, shaderStage, this.globalCache );
  44175. let uniformGPU = nodeData.uniformGPU;
  44176. if ( uniformGPU === undefined ) {
  44177. const group = node.groupNode;
  44178. const groupName = group.name;
  44179. const bindings = this.getBindGroupArray( groupName, shaderStage );
  44180. if ( type === 'texture' ) {
  44181. uniformGPU = new NodeSampledTexture( uniformNode.name, uniformNode.node, group );
  44182. bindings.push( uniformGPU );
  44183. } else if ( type === 'cubeTexture' ) {
  44184. uniformGPU = new NodeSampledCubeTexture( uniformNode.name, uniformNode.node, group );
  44185. bindings.push( uniformGPU );
  44186. } else if ( type === 'texture3D' ) {
  44187. uniformGPU = new NodeSampledTexture3D( uniformNode.name, uniformNode.node, group );
  44188. bindings.push( uniformGPU );
  44189. } else if ( type === 'buffer' ) {
  44190. node.name = `NodeBuffer_${ node.id }`;
  44191. uniformNode.name = `buffer${ node.id }`;
  44192. const buffer = new NodeUniformBuffer( node, group );
  44193. buffer.name = node.name;
  44194. bindings.push( buffer );
  44195. uniformGPU = buffer;
  44196. } else {
  44197. const uniformsStage = this.uniformGroups[ shaderStage ] || ( this.uniformGroups[ shaderStage ] = {} );
  44198. let uniformsGroup = uniformsStage[ groupName ];
  44199. if ( uniformsGroup === undefined ) {
  44200. uniformsGroup = new NodeUniformsGroup( shaderStage + '_' + groupName, group );
  44201. //uniformsGroup.setVisibility( gpuShaderStageLib[ shaderStage ] );
  44202. uniformsStage[ groupName ] = uniformsGroup;
  44203. bindings.push( uniformsGroup );
  44204. }
  44205. uniformGPU = this.getNodeUniform( uniformNode, type );
  44206. uniformsGroup.addUniform( uniformGPU );
  44207. }
  44208. nodeData.uniformGPU = uniformGPU;
  44209. }
  44210. return uniformNode;
  44211. }
  44212. }
  44213. let _vector2 = null;
  44214. let _color4 = null;
  44215. /**
  44216. * Most of the rendering related logic is implemented in the
  44217. * {@link Renderer} module and related management components.
  44218. * Sometimes it is required though to execute commands which are
  44219. * specific to the current 3D backend (which is WebGPU or WebGL 2).
  44220. * This abstract base class defines an interface that encapsulates
  44221. * all backend-related logic. Derived classes for each backend must
  44222. * implement the interface.
  44223. *
  44224. * @abstract
  44225. * @private
  44226. */
  44227. class Backend {
  44228. /**
  44229. * Constructs a new backend.
  44230. *
  44231. * @param {Object} parameters - An object holding parameters for the backend.
  44232. */
  44233. constructor( parameters = {} ) {
  44234. /**
  44235. * The parameters of the backend.
  44236. *
  44237. * @type {Object}
  44238. */
  44239. this.parameters = Object.assign( {}, parameters );
  44240. /**
  44241. * This weak map holds backend-specific data of objects
  44242. * like textures, attributes or render targets.
  44243. *
  44244. * @type {WeakMap<Object, Object>}
  44245. */
  44246. this.data = new WeakMap();
  44247. /**
  44248. * A reference to the renderer.
  44249. *
  44250. * @type {?Renderer}
  44251. * @default null
  44252. */
  44253. this.renderer = null;
  44254. /**
  44255. * A reference to the canvas element the renderer is drawing to.
  44256. *
  44257. * @type {?(HTMLCanvasElement|OffscreenCanvas)}
  44258. * @default null
  44259. */
  44260. this.domElement = null;
  44261. /**
  44262. * A reference to the timestamp query pool.
  44263. *
  44264. * @type {{render: ?TimestampQueryPool, compute: ?TimestampQueryPool}}
  44265. */
  44266. this.timestampQueryPool = {
  44267. [ TimestampQuery.RENDER ]: null,
  44268. [ TimestampQuery.COMPUTE ]: null
  44269. };
  44270. /**
  44271. * Whether to track timestamps with a Timestamp Query API or not.
  44272. *
  44273. * @type {boolean}
  44274. * @default false
  44275. */
  44276. this.trackTimestamp = ( parameters.trackTimestamp === true );
  44277. }
  44278. /**
  44279. * Initializes the backend so it is ready for usage. Concrete backends
  44280. * are supposed to implement their rendering context creation and related
  44281. * operations in this method.
  44282. *
  44283. * @async
  44284. * @param {Renderer} renderer - The renderer.
  44285. * @return {Promise} A Promise that resolves when the backend has been initialized.
  44286. */
  44287. async init( renderer ) {
  44288. this.renderer = renderer;
  44289. }
  44290. /**
  44291. * The coordinate system of the backend.
  44292. *
  44293. * @abstract
  44294. * @type {number}
  44295. * @readonly
  44296. */
  44297. get coordinateSystem() {}
  44298. // render context
  44299. /**
  44300. * This method is executed at the beginning of a render call and
  44301. * can be used by the backend to prepare the state for upcoming
  44302. * draw calls.
  44303. *
  44304. * @abstract
  44305. * @param {RenderContext} renderContext - The render context.
  44306. */
  44307. beginRender( /*renderContext*/ ) {}
  44308. /**
  44309. * This method is executed at the end of a render call and
  44310. * can be used by the backend to finalize work after draw
  44311. * calls.
  44312. *
  44313. * @abstract
  44314. * @param {RenderContext} renderContext - The render context.
  44315. */
  44316. finishRender( /*renderContext*/ ) {}
  44317. /**
  44318. * This method is executed at the beginning of a compute call and
  44319. * can be used by the backend to prepare the state for upcoming
  44320. * compute tasks.
  44321. *
  44322. * @abstract
  44323. * @param {Node|Array<Node>} computeGroup - The compute node(s).
  44324. */
  44325. beginCompute( /*computeGroup*/ ) {}
  44326. /**
  44327. * This method is executed at the end of a compute call and
  44328. * can be used by the backend to finalize work after compute
  44329. * tasks.
  44330. *
  44331. * @abstract
  44332. * @param {Node|Array<Node>} computeGroup - The compute node(s).
  44333. */
  44334. finishCompute( /*computeGroup*/ ) {}
  44335. // render object
  44336. /**
  44337. * Executes a draw command for the given render object.
  44338. *
  44339. * @abstract
  44340. * @param {RenderObject} renderObject - The render object to draw.
  44341. * @param {Info} info - Holds a series of statistical information about the GPU memory and the rendering process.
  44342. */
  44343. draw( /*renderObject, info*/ ) { }
  44344. // compute node
  44345. /**
  44346. * Executes a compute command for the given compute node.
  44347. *
  44348. * @abstract
  44349. * @param {Node|Array<Node>} computeGroup - The group of compute nodes of a compute call. Can be a single compute node.
  44350. * @param {Node} computeNode - The compute node.
  44351. * @param {Array<BindGroup>} bindings - The bindings.
  44352. * @param {ComputePipeline} computePipeline - The compute pipeline.
  44353. */
  44354. compute( /*computeGroup, computeNode, computeBindings, computePipeline*/ ) { }
  44355. // program
  44356. /**
  44357. * Creates a shader program from the given programmable stage.
  44358. *
  44359. * @abstract
  44360. * @param {ProgrammableStage} program - The programmable stage.
  44361. */
  44362. createProgram( /*program*/ ) { }
  44363. /**
  44364. * Destroys the shader program of the given programmable stage.
  44365. *
  44366. * @abstract
  44367. * @param {ProgrammableStage} program - The programmable stage.
  44368. */
  44369. destroyProgram( /*program*/ ) { }
  44370. // bindings
  44371. /**
  44372. * Creates bindings from the given bind group definition.
  44373. *
  44374. * @abstract
  44375. * @param {BindGroup} bindGroup - The bind group.
  44376. * @param {Array<BindGroup>} bindings - Array of bind groups.
  44377. * @param {number} cacheIndex - The cache index.
  44378. * @param {number} version - The version.
  44379. */
  44380. createBindings( /*bindGroup, bindings, cacheIndex, version*/ ) { }
  44381. /**
  44382. * Updates the given bind group definition.
  44383. *
  44384. * @abstract
  44385. * @param {BindGroup} bindGroup - The bind group.
  44386. * @param {Array<BindGroup>} bindings - Array of bind groups.
  44387. * @param {number} cacheIndex - The cache index.
  44388. * @param {number} version - The version.
  44389. */
  44390. updateBindings( /*bindGroup, bindings, cacheIndex, version*/ ) { }
  44391. /**
  44392. * Updates a buffer binding.
  44393. *
  44394. * @abstract
  44395. * @param {Buffer} binding - The buffer binding to update.
  44396. */
  44397. updateBinding( /*binding*/ ) { }
  44398. // pipeline
  44399. /**
  44400. * Creates a render pipeline for the given render object.
  44401. *
  44402. * @abstract
  44403. * @param {RenderObject} renderObject - The render object.
  44404. * @param {Array<Promise>} promises - An array of compilation promises which are used in `compileAsync()`.
  44405. */
  44406. createRenderPipeline( /*renderObject, promises*/ ) { }
  44407. /**
  44408. * Creates a compute pipeline for the given compute node.
  44409. *
  44410. * @abstract
  44411. * @param {ComputePipeline} computePipeline - The compute pipeline.
  44412. * @param {Array<BindGroup>} bindings - The bindings.
  44413. */
  44414. createComputePipeline( /*computePipeline, bindings*/ ) { }
  44415. // cache key
  44416. /**
  44417. * Returns `true` if the render pipeline requires an update.
  44418. *
  44419. * @abstract
  44420. * @param {RenderObject} renderObject - The render object.
  44421. * @return {boolean} Whether the render pipeline requires an update or not.
  44422. */
  44423. needsRenderUpdate( /*renderObject*/ ) { }
  44424. /**
  44425. * Returns a cache key that is used to identify render pipelines.
  44426. *
  44427. * @abstract
  44428. * @param {RenderObject} renderObject - The render object.
  44429. * @return {string} The cache key.
  44430. */
  44431. getRenderCacheKey( /*renderObject*/ ) { }
  44432. // node builder
  44433. /**
  44434. * Returns a node builder for the given render object.
  44435. *
  44436. * @abstract
  44437. * @param {RenderObject} renderObject - The render object.
  44438. * @param {Renderer} renderer - The renderer.
  44439. * @return {NodeBuilder} The node builder.
  44440. */
  44441. createNodeBuilder( /*renderObject, renderer*/ ) { }
  44442. // textures
  44443. /**
  44444. * Updates a GPU sampler for the given texture.
  44445. *
  44446. * @abstract
  44447. * @param {Texture} texture - The texture to update the sampler for.
  44448. * @return {string} The current sampler key.
  44449. */
  44450. updateSampler( /*texture*/ ) { }
  44451. /**
  44452. * Creates a default texture for the given texture that can be used
  44453. * as a placeholder until the actual texture is ready for usage.
  44454. *
  44455. * @abstract
  44456. * @param {Texture} texture - The texture to create a default texture for.
  44457. */
  44458. createDefaultTexture( /*texture*/ ) { }
  44459. /**
  44460. * Defines a texture on the GPU for the given texture object.
  44461. *
  44462. * @abstract
  44463. * @param {Texture} texture - The texture.
  44464. * @param {Object} [options={}] - Optional configuration parameter.
  44465. */
  44466. createTexture( /*texture, options={}*/ ) { }
  44467. /**
  44468. * Uploads the updated texture data to the GPU.
  44469. *
  44470. * @abstract
  44471. * @param {Texture} texture - The texture.
  44472. * @param {Object} [options={}] - Optional configuration parameter.
  44473. */
  44474. updateTexture( /*texture, options = {}*/ ) { }
  44475. /**
  44476. * Generates mipmaps for the given texture.
  44477. *
  44478. * @abstract
  44479. * @param {Texture} texture - The texture.
  44480. */
  44481. generateMipmaps( /*texture*/ ) { }
  44482. /**
  44483. * Destroys the GPU data for the given texture object.
  44484. *
  44485. * @abstract
  44486. * @param {Texture} texture - The texture.
  44487. * @param {boolean} [isDefaultTexture=false] - Whether the texture uses a default GPU texture or not.
  44488. */
  44489. destroyTexture( /*texture, isDefaultTexture*/ ) { }
  44490. /**
  44491. * Returns texture data as a typed array.
  44492. *
  44493. * @abstract
  44494. * @async
  44495. * @param {Texture} texture - The texture to copy.
  44496. * @param {number} x - The x coordinate of the copy origin.
  44497. * @param {number} y - The y coordinate of the copy origin.
  44498. * @param {number} width - The width of the copy.
  44499. * @param {number} height - The height of the copy.
  44500. * @param {number} faceIndex - The face index.
  44501. * @return {Promise<TypedArray>} A Promise that resolves with a typed array when the copy operation has finished.
  44502. */
  44503. async copyTextureToBuffer( /*texture, x, y, width, height, faceIndex*/ ) {}
  44504. /**
  44505. * Copies data of the given source texture to the given destination texture.
  44506. *
  44507. * @abstract
  44508. * @param {Texture} srcTexture - The source texture.
  44509. * @param {Texture} dstTexture - The destination texture.
  44510. * @param {?(Box3|Box2)} [srcRegion=null] - The region of the source texture to copy.
  44511. * @param {?(Vector2|Vector3)} [dstPosition=null] - The destination position of the copy.
  44512. * @param {number} [srcLevel=0] - The source mip level to copy from.
  44513. * @param {number} [dstLevel=0] - The destination mip level to copy to.
  44514. */
  44515. copyTextureToTexture( /*srcTexture, dstTexture, srcRegion = null, dstPosition = null, srcLevel = 0, dstLevel = 0*/ ) {}
  44516. /**
  44517. * Copies the current bound framebuffer to the given texture.
  44518. *
  44519. * @abstract
  44520. * @param {Texture} texture - The destination texture.
  44521. * @param {RenderContext} renderContext - The render context.
  44522. * @param {Vector4} rectangle - A four dimensional vector defining the origin and dimension of the copy.
  44523. */
  44524. copyFramebufferToTexture( /*texture, renderContext, rectangle*/ ) {}
  44525. // attributes
  44526. /**
  44527. * Creates the GPU buffer of a shader attribute.
  44528. *
  44529. * @abstract
  44530. * @param {BufferAttribute} attribute - The buffer attribute.
  44531. */
  44532. createAttribute( /*attribute*/ ) { }
  44533. /**
  44534. * Creates the GPU buffer of an indexed shader attribute.
  44535. *
  44536. * @abstract
  44537. * @param {BufferAttribute} attribute - The indexed buffer attribute.
  44538. */
  44539. createIndexAttribute( /*attribute*/ ) { }
  44540. /**
  44541. * Creates the GPU buffer of a storage attribute.
  44542. *
  44543. * @abstract
  44544. * @param {BufferAttribute} attribute - The buffer attribute.
  44545. */
  44546. createStorageAttribute( /*attribute*/ ) { }
  44547. /**
  44548. * Updates the GPU buffer of a shader attribute.
  44549. *
  44550. * @abstract
  44551. * @param {BufferAttribute} attribute - The buffer attribute to update.
  44552. */
  44553. updateAttribute( /*attribute*/ ) { }
  44554. /**
  44555. * Destroys the GPU buffer of a shader attribute.
  44556. *
  44557. * @abstract
  44558. * @param {BufferAttribute} attribute - The buffer attribute to destroy.
  44559. */
  44560. destroyAttribute( /*attribute*/ ) { }
  44561. // canvas
  44562. /**
  44563. * Returns the backend's rendering context.
  44564. *
  44565. * @abstract
  44566. * @return {Object} The rendering context.
  44567. */
  44568. getContext() { }
  44569. /**
  44570. * Backends can use this method if they have to run
  44571. * logic when the renderer gets resized.
  44572. *
  44573. * @abstract
  44574. */
  44575. updateSize() { }
  44576. /**
  44577. * Updates the viewport with the values from the given render context.
  44578. *
  44579. * @abstract
  44580. * @param {RenderContext} renderContext - The render context.
  44581. */
  44582. updateViewport( /*renderContext*/ ) {}
  44583. // utils
  44584. /**
  44585. * Updates a unique identifier for the given render context that can be used
  44586. * to allocate resources like occlusion queries or timestamp queries.
  44587. *
  44588. * @param {RenderContext|ComputeNode} abstractRenderContext - The render context.
  44589. */
  44590. updateTimeStampUID( abstractRenderContext ) {
  44591. const contextData = this.get( abstractRenderContext );
  44592. const frame = this.renderer.info.frame;
  44593. let prefix;
  44594. if ( abstractRenderContext.isComputeNode === true ) {
  44595. prefix = 'c:' + this.renderer.info.compute.frameCalls;
  44596. } else {
  44597. prefix = 'r:' + this.renderer.info.render.frameCalls;
  44598. }
  44599. contextData.timestampUID = prefix + ':' + abstractRenderContext.id + ':f' + frame;
  44600. }
  44601. /**
  44602. * Returns a unique identifier for the given render context that can be used
  44603. * to allocate resources like occlusion queries or timestamp queries.
  44604. *
  44605. * @param {RenderContext|ComputeNode} abstractRenderContext - The render context.
  44606. * @return {string} The unique identifier.
  44607. */
  44608. getTimestampUID( abstractRenderContext ) {
  44609. return this.get( abstractRenderContext ).timestampUID;
  44610. }
  44611. /**
  44612. * Returns all timestamp frames for the given type.
  44613. *
  44614. * @param {string} type - The type of the time stamp.
  44615. * @return {Array<number>} The timestamp frames.
  44616. */
  44617. getTimestampFrames( type ) {
  44618. const queryPool = this.timestampQueryPool[ type ];
  44619. return queryPool ? queryPool.getTimestampFrames() : [];
  44620. }
  44621. /**
  44622. * Returns the query pool for the given uid.
  44623. *
  44624. * @param {string} uid - The unique identifier.
  44625. * @return {TimestampQueryPool} The query pool.
  44626. */
  44627. _getQueryPool( uid ) {
  44628. const type = uid.startsWith( 'c:' ) ? TimestampQuery.COMPUTE : TimestampQuery.RENDER;
  44629. const queryPool = this.timestampQueryPool[ type ];
  44630. return queryPool;
  44631. }
  44632. /**
  44633. * Returns the timestamp for the given uid.
  44634. *
  44635. * @param {string} uid - The unique identifier.
  44636. * @return {number} The timestamp.
  44637. */
  44638. getTimestamp( uid ) {
  44639. const queryPool = this._getQueryPool( uid );
  44640. return queryPool.getTimestamp( uid );
  44641. }
  44642. /**
  44643. * Returns `true` if a timestamp for the given uid is available.
  44644. *
  44645. * @param {string} uid - The unique identifier.
  44646. * @return {boolean} Whether the timestamp is available or not.
  44647. */
  44648. hasTimestamp( uid ) {
  44649. const queryPool = this._getQueryPool( uid );
  44650. return queryPool.hasTimestamp( uid );
  44651. }
  44652. /**
  44653. * Returns `true` if the given 3D object is fully occluded by other
  44654. * 3D objects in the scene. Backends must implement this method by using
  44655. * a Occlusion Query API.
  44656. *
  44657. * @abstract
  44658. * @param {RenderContext} renderContext - The render context.
  44659. * @param {Object3D} object - The 3D object to test.
  44660. * @return {boolean} Whether the 3D object is fully occluded or not.
  44661. */
  44662. isOccluded( /*renderContext, object*/ ) {}
  44663. /**
  44664. * Resolves the time stamp for the given render context and type.
  44665. *
  44666. * @async
  44667. * @abstract
  44668. * @param {string} [type='render'] - The type of the time stamp.
  44669. * @return {Promise<number>} A Promise that resolves with the time stamp.
  44670. */
  44671. async resolveTimestampsAsync( type = 'render' ) {
  44672. if ( ! this.trackTimestamp ) {
  44673. warnOnce( 'WebGPURenderer: Timestamp tracking is disabled.' );
  44674. return;
  44675. }
  44676. const queryPool = this.timestampQueryPool[ type ];
  44677. if ( ! queryPool ) {
  44678. return;
  44679. }
  44680. const duration = await queryPool.resolveQueriesAsync();
  44681. this.renderer.info[ type ].timestamp = duration;
  44682. return duration;
  44683. }
  44684. /**
  44685. * This method performs a readback operation by moving buffer data from
  44686. * a storage buffer attribute from the GPU to the CPU.
  44687. *
  44688. * @async
  44689. * @param {StorageBufferAttribute} attribute - The storage buffer attribute.
  44690. * @return {Promise<ArrayBuffer>} A promise that resolves with the buffer data when the data are ready.
  44691. */
  44692. async getArrayBufferAsync( /* attribute */ ) {}
  44693. /**
  44694. * Checks if the given feature is supported by the backend.
  44695. *
  44696. * @async
  44697. * @abstract
  44698. * @param {string} name - The feature's name.
  44699. * @return {Promise<boolean>} A Promise that resolves with a bool that indicates whether the feature is supported or not.
  44700. */
  44701. async hasFeatureAsync( /*name*/ ) { }
  44702. /**
  44703. * Checks if the given feature is supported by the backend.
  44704. *
  44705. * @abstract
  44706. * @param {string} name - The feature's name.
  44707. * @return {boolean} Whether the feature is supported or not.
  44708. */
  44709. hasFeature( /*name*/ ) {}
  44710. /**
  44711. * Returns the maximum anisotropy texture filtering value.
  44712. *
  44713. * @abstract
  44714. * @return {number} The maximum anisotropy texture filtering value.
  44715. */
  44716. getMaxAnisotropy() {}
  44717. /**
  44718. * Returns the drawing buffer size.
  44719. *
  44720. * @return {Vector2} The drawing buffer size.
  44721. */
  44722. getDrawingBufferSize() {
  44723. _vector2 = _vector2 || new Vector2();
  44724. return this.renderer.getDrawingBufferSize( _vector2 );
  44725. }
  44726. /**
  44727. * Defines the scissor test.
  44728. *
  44729. * @abstract
  44730. * @param {boolean} boolean - Whether the scissor test should be enabled or not.
  44731. */
  44732. setScissorTest( /*boolean*/ ) { }
  44733. /**
  44734. * Returns the clear color and alpha into a single
  44735. * color object.
  44736. *
  44737. * @return {Color4} The clear color.
  44738. */
  44739. getClearColor() {
  44740. const renderer = this.renderer;
  44741. _color4 = _color4 || new Color4();
  44742. renderer.getClearColor( _color4 );
  44743. _color4.getRGB( _color4 );
  44744. return _color4;
  44745. }
  44746. /**
  44747. * Returns the DOM element. If no DOM element exists, the backend
  44748. * creates a new one.
  44749. *
  44750. * @return {HTMLCanvasElement} The DOM element.
  44751. */
  44752. getDomElement() {
  44753. let domElement = this.domElement;
  44754. if ( domElement === null ) {
  44755. domElement = ( this.parameters.canvas !== undefined ) ? this.parameters.canvas : createCanvasElement();
  44756. // OffscreenCanvas does not have setAttribute, see #22811
  44757. if ( 'setAttribute' in domElement ) domElement.setAttribute( 'data-engine', `three.js r${REVISION} webgpu` );
  44758. this.domElement = domElement;
  44759. }
  44760. return domElement;
  44761. }
  44762. /**
  44763. * Sets a dictionary for the given object into the
  44764. * internal data structure.
  44765. *
  44766. * @param {Object} object - The object.
  44767. * @param {Object} value - The dictionary to set.
  44768. */
  44769. set( object, value ) {
  44770. this.data.set( object, value );
  44771. }
  44772. /**
  44773. * Returns the dictionary for the given object.
  44774. *
  44775. * @param {Object} object - The object.
  44776. * @return {Object} The object's dictionary.
  44777. */
  44778. get( object ) {
  44779. let map = this.data.get( object );
  44780. if ( map === undefined ) {
  44781. map = {};
  44782. this.data.set( object, map );
  44783. }
  44784. return map;
  44785. }
  44786. /**
  44787. * Checks if the given object has a dictionary
  44788. * with data defined.
  44789. *
  44790. * @param {Object} object - The object.
  44791. * @return {boolean} Whether a dictionary for the given object as been defined or not.
  44792. */
  44793. has( object ) {
  44794. return this.data.has( object );
  44795. }
  44796. /**
  44797. * Deletes an object from the internal data structure.
  44798. *
  44799. * @param {Object} object - The object to delete.
  44800. */
  44801. delete( object ) {
  44802. this.data.delete( object );
  44803. }
  44804. /**
  44805. * Frees internal resources.
  44806. *
  44807. * @abstract
  44808. */
  44809. dispose() { }
  44810. }
  44811. let _id$1 = 0;
  44812. /**
  44813. * This module is internally used in context of compute shaders.
  44814. * This type of shader is not natively supported in WebGL 2 and
  44815. * thus implemented via Transform Feedback. `DualAttributeData`
  44816. * manages the related data.
  44817. *
  44818. * @private
  44819. */
  44820. class DualAttributeData {
  44821. constructor( attributeData, dualBuffer ) {
  44822. this.buffers = [ attributeData.bufferGPU, dualBuffer ];
  44823. this.type = attributeData.type;
  44824. this.bufferType = attributeData.bufferType;
  44825. this.pbo = attributeData.pbo;
  44826. this.byteLength = attributeData.byteLength;
  44827. this.bytesPerElement = attributeData.BYTES_PER_ELEMENT;
  44828. this.version = attributeData.version;
  44829. this.isInteger = attributeData.isInteger;
  44830. this.activeBufferIndex = 0;
  44831. this.baseId = attributeData.id;
  44832. }
  44833. get id() {
  44834. return `${ this.baseId }|${ this.activeBufferIndex }`;
  44835. }
  44836. get bufferGPU() {
  44837. return this.buffers[ this.activeBufferIndex ];
  44838. }
  44839. get transformBuffer() {
  44840. return this.buffers[ this.activeBufferIndex ^ 1 ];
  44841. }
  44842. switchBuffers() {
  44843. this.activeBufferIndex ^= 1;
  44844. }
  44845. }
  44846. /**
  44847. * A WebGL 2 backend utility module for managing shader attributes.
  44848. *
  44849. * @private
  44850. */
  44851. class WebGLAttributeUtils {
  44852. /**
  44853. * Constructs a new utility object.
  44854. *
  44855. * @param {WebGLBackend} backend - The WebGL 2 backend.
  44856. */
  44857. constructor( backend ) {
  44858. /**
  44859. * A reference to the WebGL 2 backend.
  44860. *
  44861. * @type {WebGLBackend}
  44862. */
  44863. this.backend = backend;
  44864. }
  44865. /**
  44866. * Creates the GPU buffer for the given buffer attribute.
  44867. *
  44868. * @param {BufferAttribute} attribute - The buffer attribute.
  44869. * @param {GLenum } bufferType - A flag that indicates the buffer type and thus binding point target.
  44870. */
  44871. createAttribute( attribute, bufferType ) {
  44872. const backend = this.backend;
  44873. const { gl } = backend;
  44874. const array = attribute.array;
  44875. const usage = attribute.usage || gl.STATIC_DRAW;
  44876. const bufferAttribute = attribute.isInterleavedBufferAttribute ? attribute.data : attribute;
  44877. const bufferData = backend.get( bufferAttribute );
  44878. let bufferGPU = bufferData.bufferGPU;
  44879. if ( bufferGPU === undefined ) {
  44880. bufferGPU = this._createBuffer( gl, bufferType, array, usage );
  44881. bufferData.bufferGPU = bufferGPU;
  44882. bufferData.bufferType = bufferType;
  44883. bufferData.version = bufferAttribute.version;
  44884. }
  44885. //attribute.onUploadCallback();
  44886. let type;
  44887. if ( array instanceof Float32Array ) {
  44888. type = gl.FLOAT;
  44889. } else if ( typeof Float16Array !== 'undefined' && array instanceof Float16Array ) {
  44890. type = gl.HALF_FLOAT;
  44891. } else if ( array instanceof Uint16Array ) {
  44892. if ( attribute.isFloat16BufferAttribute ) {
  44893. type = gl.HALF_FLOAT;
  44894. } else {
  44895. type = gl.UNSIGNED_SHORT;
  44896. }
  44897. } else if ( array instanceof Int16Array ) {
  44898. type = gl.SHORT;
  44899. } else if ( array instanceof Uint32Array ) {
  44900. type = gl.UNSIGNED_INT;
  44901. } else if ( array instanceof Int32Array ) {
  44902. type = gl.INT;
  44903. } else if ( array instanceof Int8Array ) {
  44904. type = gl.BYTE;
  44905. } else if ( array instanceof Uint8Array ) {
  44906. type = gl.UNSIGNED_BYTE;
  44907. } else if ( array instanceof Uint8ClampedArray ) {
  44908. type = gl.UNSIGNED_BYTE;
  44909. } else {
  44910. throw new Error( 'THREE.WebGLBackend: Unsupported buffer data format: ' + array );
  44911. }
  44912. let attributeData = {
  44913. bufferGPU,
  44914. bufferType,
  44915. type,
  44916. byteLength: array.byteLength,
  44917. bytesPerElement: array.BYTES_PER_ELEMENT,
  44918. version: attribute.version,
  44919. pbo: attribute.pbo,
  44920. isInteger: type === gl.INT || type === gl.UNSIGNED_INT || attribute.gpuType === IntType,
  44921. id: _id$1 ++
  44922. };
  44923. if ( attribute.isStorageBufferAttribute || attribute.isStorageInstancedBufferAttribute ) {
  44924. // create buffer for transform feedback use
  44925. const bufferGPUDual = this._createBuffer( gl, bufferType, array, usage );
  44926. attributeData = new DualAttributeData( attributeData, bufferGPUDual );
  44927. }
  44928. backend.set( attribute, attributeData );
  44929. }
  44930. /**
  44931. * Updates the GPU buffer of the given buffer attribute.
  44932. *
  44933. * @param {BufferAttribute} attribute - The buffer attribute.
  44934. */
  44935. updateAttribute( attribute ) {
  44936. const backend = this.backend;
  44937. const { gl } = backend;
  44938. const array = attribute.array;
  44939. const bufferAttribute = attribute.isInterleavedBufferAttribute ? attribute.data : attribute;
  44940. const bufferData = backend.get( bufferAttribute );
  44941. const bufferType = bufferData.bufferType;
  44942. const updateRanges = attribute.isInterleavedBufferAttribute ? attribute.data.updateRanges : attribute.updateRanges;
  44943. gl.bindBuffer( bufferType, bufferData.bufferGPU );
  44944. if ( updateRanges.length === 0 ) {
  44945. // Not using update ranges
  44946. gl.bufferSubData( bufferType, 0, array );
  44947. } else {
  44948. for ( let i = 0, l = updateRanges.length; i < l; i ++ ) {
  44949. const range = updateRanges[ i ];
  44950. gl.bufferSubData( bufferType, range.start * array.BYTES_PER_ELEMENT,
  44951. array, range.start, range.count );
  44952. }
  44953. bufferAttribute.clearUpdateRanges();
  44954. }
  44955. gl.bindBuffer( bufferType, null );
  44956. bufferData.version = bufferAttribute.version;
  44957. }
  44958. /**
  44959. * Destroys the GPU buffer of the given buffer attribute.
  44960. *
  44961. * @param {BufferAttribute} attribute - The buffer attribute.
  44962. */
  44963. destroyAttribute( attribute ) {
  44964. const backend = this.backend;
  44965. const { gl } = backend;
  44966. if ( attribute.isInterleavedBufferAttribute ) {
  44967. backend.delete( attribute.data );
  44968. }
  44969. const attributeData = backend.get( attribute );
  44970. gl.deleteBuffer( attributeData.bufferGPU );
  44971. backend.delete( attribute );
  44972. }
  44973. /**
  44974. * This method performs a readback operation by moving buffer data from
  44975. * a storage buffer attribute from the GPU to the CPU.
  44976. *
  44977. * @async
  44978. * @param {StorageBufferAttribute} attribute - The storage buffer attribute.
  44979. * @return {Promise<ArrayBuffer>} A promise that resolves with the buffer data when the data are ready.
  44980. */
  44981. async getArrayBufferAsync( attribute ) {
  44982. const backend = this.backend;
  44983. const { gl } = backend;
  44984. const bufferAttribute = attribute.isInterleavedBufferAttribute ? attribute.data : attribute;
  44985. const { bufferGPU } = backend.get( bufferAttribute );
  44986. const array = attribute.array;
  44987. const byteLength = array.byteLength;
  44988. gl.bindBuffer( gl.COPY_READ_BUFFER, bufferGPU );
  44989. const writeBuffer = gl.createBuffer();
  44990. gl.bindBuffer( gl.COPY_WRITE_BUFFER, writeBuffer );
  44991. gl.bufferData( gl.COPY_WRITE_BUFFER, byteLength, gl.STREAM_READ );
  44992. gl.copyBufferSubData( gl.COPY_READ_BUFFER, gl.COPY_WRITE_BUFFER, 0, 0, byteLength );
  44993. await backend.utils._clientWaitAsync();
  44994. const dstBuffer = new attribute.array.constructor( array.length );
  44995. // Ensure the buffer is bound before reading
  44996. gl.bindBuffer( gl.COPY_WRITE_BUFFER, writeBuffer );
  44997. gl.getBufferSubData( gl.COPY_WRITE_BUFFER, 0, dstBuffer );
  44998. gl.deleteBuffer( writeBuffer );
  44999. gl.bindBuffer( gl.COPY_READ_BUFFER, null );
  45000. gl.bindBuffer( gl.COPY_WRITE_BUFFER, null );
  45001. return dstBuffer.buffer;
  45002. }
  45003. /**
  45004. * Creates a WebGL buffer with the given data.
  45005. *
  45006. * @private
  45007. * @param {WebGL2RenderingContext} gl - The rendering context.
  45008. * @param {GLenum } bufferType - A flag that indicates the buffer type and thus binding point target.
  45009. * @param {TypedArray} array - The array of the buffer attribute.
  45010. * @param {GLenum} usage - The usage.
  45011. * @return {WebGLBuffer} The WebGL buffer.
  45012. */
  45013. _createBuffer( gl, bufferType, array, usage ) {
  45014. const bufferGPU = gl.createBuffer();
  45015. gl.bindBuffer( bufferType, bufferGPU );
  45016. gl.bufferData( bufferType, array, usage );
  45017. gl.bindBuffer( bufferType, null );
  45018. return bufferGPU;
  45019. }
  45020. }
  45021. let equationToGL, factorToGL;
  45022. /**
  45023. * A WebGL 2 backend utility module for managing the WebGL state.
  45024. *
  45025. * The major goal of this module is to reduce the number of state changes
  45026. * by caching the WEbGL state with a series of variables. In this way, the
  45027. * renderer only executes state change commands when necessary which
  45028. * improves the overall performance.
  45029. *
  45030. * @private
  45031. */
  45032. class WebGLState {
  45033. /**
  45034. * Constructs a new utility object.
  45035. *
  45036. * @param {WebGLBackend} backend - The WebGL 2 backend.
  45037. */
  45038. constructor( backend ) {
  45039. /**
  45040. * A reference to the WebGL 2 backend.
  45041. *
  45042. * @type {WebGLBackend}
  45043. */
  45044. this.backend = backend;
  45045. /**
  45046. * A reference to the rendering context.
  45047. *
  45048. * @type {WebGL2RenderingContext}
  45049. */
  45050. this.gl = this.backend.gl;
  45051. // Below properties are intended to cache
  45052. // the WebGL state and are not explicitly
  45053. // documented for convenience reasons.
  45054. this.enabled = {};
  45055. this.currentFlipSided = null;
  45056. this.currentCullFace = null;
  45057. this.currentProgram = null;
  45058. this.currentBlendingEnabled = false;
  45059. this.currentBlending = null;
  45060. this.currentBlendSrc = null;
  45061. this.currentBlendDst = null;
  45062. this.currentBlendSrcAlpha = null;
  45063. this.currentBlendDstAlpha = null;
  45064. this.currentPremultipledAlpha = null;
  45065. this.currentPolygonOffsetFactor = null;
  45066. this.currentPolygonOffsetUnits = null;
  45067. this.currentColorMask = null;
  45068. this.currentDepthFunc = null;
  45069. this.currentDepthMask = null;
  45070. this.currentStencilFunc = null;
  45071. this.currentStencilRef = null;
  45072. this.currentStencilFuncMask = null;
  45073. this.currentStencilFail = null;
  45074. this.currentStencilZFail = null;
  45075. this.currentStencilZPass = null;
  45076. this.currentStencilMask = null;
  45077. this.currentLineWidth = null;
  45078. this.currentClippingPlanes = 0;
  45079. this.currentVAO = null;
  45080. this.currentIndex = null;
  45081. this.currentBoundFramebuffers = {};
  45082. this.currentDrawbuffers = new WeakMap();
  45083. this.maxTextures = this.gl.getParameter( this.gl.MAX_TEXTURE_IMAGE_UNITS );
  45084. this.currentTextureSlot = null;
  45085. this.currentBoundTextures = {};
  45086. this.currentBoundBufferBases = {};
  45087. this._init();
  45088. }
  45089. /**
  45090. * Inits the state of the utility.
  45091. *
  45092. * @private
  45093. */
  45094. _init() {
  45095. const gl = this.gl;
  45096. // Store only WebGL constants here.
  45097. equationToGL = {
  45098. [ AddEquation ]: gl.FUNC_ADD,
  45099. [ SubtractEquation ]: gl.FUNC_SUBTRACT,
  45100. [ ReverseSubtractEquation ]: gl.FUNC_REVERSE_SUBTRACT
  45101. };
  45102. factorToGL = {
  45103. [ ZeroFactor ]: gl.ZERO,
  45104. [ OneFactor ]: gl.ONE,
  45105. [ SrcColorFactor ]: gl.SRC_COLOR,
  45106. [ SrcAlphaFactor ]: gl.SRC_ALPHA,
  45107. [ SrcAlphaSaturateFactor ]: gl.SRC_ALPHA_SATURATE,
  45108. [ DstColorFactor ]: gl.DST_COLOR,
  45109. [ DstAlphaFactor ]: gl.DST_ALPHA,
  45110. [ OneMinusSrcColorFactor ]: gl.ONE_MINUS_SRC_COLOR,
  45111. [ OneMinusSrcAlphaFactor ]: gl.ONE_MINUS_SRC_ALPHA,
  45112. [ OneMinusDstColorFactor ]: gl.ONE_MINUS_DST_COLOR,
  45113. [ OneMinusDstAlphaFactor ]: gl.ONE_MINUS_DST_ALPHA
  45114. };
  45115. const scissorParam = gl.getParameter( gl.SCISSOR_BOX );
  45116. const viewportParam = gl.getParameter( gl.VIEWPORT );
  45117. this.currentScissor = new Vector4().fromArray( scissorParam );
  45118. this.currentViewport = new Vector4().fromArray( viewportParam );
  45119. this._tempVec4 = new Vector4();
  45120. }
  45121. /**
  45122. * Enables the given WebGL capability.
  45123. *
  45124. * This method caches the capability state so
  45125. * `gl.enable()` is only called when necessary.
  45126. *
  45127. * @param {GLenum} id - The capability to enable.
  45128. */
  45129. enable( id ) {
  45130. const { enabled } = this;
  45131. if ( enabled[ id ] !== true ) {
  45132. this.gl.enable( id );
  45133. enabled[ id ] = true;
  45134. }
  45135. }
  45136. /**
  45137. * Disables the given WebGL capability.
  45138. *
  45139. * This method caches the capability state so
  45140. * `gl.disable()` is only called when necessary.
  45141. *
  45142. * @param {GLenum} id - The capability to enable.
  45143. */
  45144. disable( id ) {
  45145. const { enabled } = this;
  45146. if ( enabled[ id ] !== false ) {
  45147. this.gl.disable( id );
  45148. enabled[ id ] = false;
  45149. }
  45150. }
  45151. /**
  45152. * Specifies whether polygons are front- or back-facing
  45153. * by setting the winding orientation.
  45154. *
  45155. * This method caches the state so `gl.frontFace()` is only
  45156. * called when necessary.
  45157. *
  45158. * @param {boolean} flipSided - Whether triangles flipped their sides or not.
  45159. */
  45160. setFlipSided( flipSided ) {
  45161. if ( this.currentFlipSided !== flipSided ) {
  45162. const { gl } = this;
  45163. if ( flipSided ) {
  45164. gl.frontFace( gl.CW );
  45165. } else {
  45166. gl.frontFace( gl.CCW );
  45167. }
  45168. this.currentFlipSided = flipSided;
  45169. }
  45170. }
  45171. /**
  45172. * Specifies whether or not front- and/or back-facing
  45173. * polygons can be culled.
  45174. *
  45175. * This method caches the state so `gl.cullFace()` is only
  45176. * called when necessary.
  45177. *
  45178. * @param {number} cullFace - Defines which polygons are candidates for culling.
  45179. */
  45180. setCullFace( cullFace ) {
  45181. const { gl } = this;
  45182. if ( cullFace !== CullFaceNone ) {
  45183. this.enable( gl.CULL_FACE );
  45184. if ( cullFace !== this.currentCullFace ) {
  45185. if ( cullFace === CullFaceBack ) {
  45186. gl.cullFace( gl.BACK );
  45187. } else if ( cullFace === CullFaceFront ) {
  45188. gl.cullFace( gl.FRONT );
  45189. } else {
  45190. gl.cullFace( gl.FRONT_AND_BACK );
  45191. }
  45192. }
  45193. } else {
  45194. this.disable( gl.CULL_FACE );
  45195. }
  45196. this.currentCullFace = cullFace;
  45197. }
  45198. /**
  45199. * Specifies the width of line primitives.
  45200. *
  45201. * This method caches the state so `gl.lineWidth()` is only
  45202. * called when necessary.
  45203. *
  45204. * @param {number} width - The line width.
  45205. */
  45206. setLineWidth( width ) {
  45207. const { currentLineWidth, gl } = this;
  45208. if ( width !== currentLineWidth ) {
  45209. gl.lineWidth( width );
  45210. this.currentLineWidth = width;
  45211. }
  45212. }
  45213. /**
  45214. * Defines the blending.
  45215. *
  45216. * This method caches the state so `gl.blendEquation()`, `gl.blendEquationSeparate()`,
  45217. * `gl.blendFunc()` and `gl.blendFuncSeparate()` are only called when necessary.
  45218. *
  45219. * @param {number} blending - The blending type.
  45220. * @param {number} blendEquation - The blending equation.
  45221. * @param {number} blendSrc - Only relevant for custom blending. The RGB source blending factor.
  45222. * @param {number} blendDst - Only relevant for custom blending. The RGB destination blending factor.
  45223. * @param {number} blendEquationAlpha - Only relevant for custom blending. The blending equation for alpha.
  45224. * @param {number} blendSrcAlpha - Only relevant for custom blending. The alpha source blending factor.
  45225. * @param {number} blendDstAlpha - Only relevant for custom blending. The alpha destination blending factor.
  45226. * @param {boolean} premultipliedAlpha - Whether premultiplied alpha is enabled or not.
  45227. */
  45228. setBlending( blending, blendEquation, blendSrc, blendDst, blendEquationAlpha, blendSrcAlpha, blendDstAlpha, premultipliedAlpha ) {
  45229. const { gl } = this;
  45230. if ( blending === NoBlending ) {
  45231. if ( this.currentBlendingEnabled === true ) {
  45232. this.disable( gl.BLEND );
  45233. this.currentBlendingEnabled = false;
  45234. }
  45235. return;
  45236. }
  45237. if ( this.currentBlendingEnabled === false ) {
  45238. this.enable( gl.BLEND );
  45239. this.currentBlendingEnabled = true;
  45240. }
  45241. if ( blending !== CustomBlending ) {
  45242. if ( blending !== this.currentBlending || premultipliedAlpha !== this.currentPremultipledAlpha ) {
  45243. if ( this.currentBlendEquation !== AddEquation || this.currentBlendEquationAlpha !== AddEquation ) {
  45244. gl.blendEquation( gl.FUNC_ADD );
  45245. this.currentBlendEquation = AddEquation;
  45246. this.currentBlendEquationAlpha = AddEquation;
  45247. }
  45248. if ( premultipliedAlpha ) {
  45249. switch ( blending ) {
  45250. case NormalBlending:
  45251. gl.blendFuncSeparate( gl.ONE, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA );
  45252. break;
  45253. case AdditiveBlending:
  45254. gl.blendFunc( gl.ONE, gl.ONE );
  45255. break;
  45256. case SubtractiveBlending:
  45257. gl.blendFuncSeparate( gl.ZERO, gl.ONE_MINUS_SRC_COLOR, gl.ZERO, gl.ONE );
  45258. break;
  45259. case MultiplyBlending:
  45260. gl.blendFuncSeparate( gl.DST_COLOR, gl.ONE_MINUS_SRC_ALPHA, gl.ZERO, gl.ONE );
  45261. break;
  45262. default:
  45263. error( 'WebGLState: Invalid blending: ', blending );
  45264. break;
  45265. }
  45266. } else {
  45267. switch ( blending ) {
  45268. case NormalBlending:
  45269. gl.blendFuncSeparate( gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA );
  45270. break;
  45271. case AdditiveBlending:
  45272. gl.blendFuncSeparate( gl.SRC_ALPHA, gl.ONE, gl.ONE, gl.ONE );
  45273. break;
  45274. case SubtractiveBlending:
  45275. error( 'WebGLState: SubtractiveBlending requires material.premultipliedAlpha = true' );
  45276. break;
  45277. case MultiplyBlending:
  45278. error( 'WebGLState: MultiplyBlending requires material.premultipliedAlpha = true' );
  45279. break;
  45280. default:
  45281. error( 'WebGLState: Invalid blending: ', blending );
  45282. break;
  45283. }
  45284. }
  45285. this.currentBlendSrc = null;
  45286. this.currentBlendDst = null;
  45287. this.currentBlendSrcAlpha = null;
  45288. this.currentBlendDstAlpha = null;
  45289. this.currentBlending = blending;
  45290. this.currentPremultipledAlpha = premultipliedAlpha;
  45291. }
  45292. return;
  45293. }
  45294. // custom blending
  45295. blendEquationAlpha = blendEquationAlpha || blendEquation;
  45296. blendSrcAlpha = blendSrcAlpha || blendSrc;
  45297. blendDstAlpha = blendDstAlpha || blendDst;
  45298. if ( blendEquation !== this.currentBlendEquation || blendEquationAlpha !== this.currentBlendEquationAlpha ) {
  45299. gl.blendEquationSeparate( equationToGL[ blendEquation ], equationToGL[ blendEquationAlpha ] );
  45300. this.currentBlendEquation = blendEquation;
  45301. this.currentBlendEquationAlpha = blendEquationAlpha;
  45302. }
  45303. if ( blendSrc !== this.currentBlendSrc || blendDst !== this.currentBlendDst || blendSrcAlpha !== this.currentBlendSrcAlpha || blendDstAlpha !== this.currentBlendDstAlpha ) {
  45304. gl.blendFuncSeparate( factorToGL[ blendSrc ], factorToGL[ blendDst ], factorToGL[ blendSrcAlpha ], factorToGL[ blendDstAlpha ] );
  45305. this.currentBlendSrc = blendSrc;
  45306. this.currentBlendDst = blendDst;
  45307. this.currentBlendSrcAlpha = blendSrcAlpha;
  45308. this.currentBlendDstAlpha = blendDstAlpha;
  45309. }
  45310. this.currentBlending = blending;
  45311. this.currentPremultipledAlpha = false;
  45312. }
  45313. /**
  45314. * Specifies whether colors can be written when rendering
  45315. * into a framebuffer or not.
  45316. *
  45317. * This method caches the state so `gl.colorMask()` is only
  45318. * called when necessary.
  45319. *
  45320. * @param {boolean} colorMask - The color mask.
  45321. */
  45322. setColorMask( colorMask ) {
  45323. if ( this.currentColorMask !== colorMask ) {
  45324. this.gl.colorMask( colorMask, colorMask, colorMask, colorMask );
  45325. this.currentColorMask = colorMask;
  45326. }
  45327. }
  45328. /**
  45329. * Specifies whether the depth test is enabled or not.
  45330. *
  45331. * @param {boolean} depthTest - Whether the depth test is enabled or not.
  45332. */
  45333. setDepthTest( depthTest ) {
  45334. const { gl } = this;
  45335. if ( depthTest ) {
  45336. this.enable( gl.DEPTH_TEST );
  45337. } else {
  45338. this.disable( gl.DEPTH_TEST );
  45339. }
  45340. }
  45341. /**
  45342. * Specifies whether depth values can be written when rendering
  45343. * into a framebuffer or not.
  45344. *
  45345. * This method caches the state so `gl.depthMask()` is only
  45346. * called when necessary.
  45347. *
  45348. * @param {boolean} depthMask - The depth mask.
  45349. */
  45350. setDepthMask( depthMask ) {
  45351. if ( this.currentDepthMask !== depthMask ) {
  45352. this.gl.depthMask( depthMask );
  45353. this.currentDepthMask = depthMask;
  45354. }
  45355. }
  45356. /**
  45357. * Specifies the depth compare function.
  45358. *
  45359. * This method caches the state so `gl.depthFunc()` is only
  45360. * called when necessary.
  45361. *
  45362. * @param {number} depthFunc - The depth compare function.
  45363. */
  45364. setDepthFunc( depthFunc ) {
  45365. if ( this.currentDepthFunc !== depthFunc ) {
  45366. const { gl } = this;
  45367. switch ( depthFunc ) {
  45368. case NeverDepth:
  45369. gl.depthFunc( gl.NEVER );
  45370. break;
  45371. case AlwaysDepth:
  45372. gl.depthFunc( gl.ALWAYS );
  45373. break;
  45374. case LessDepth:
  45375. gl.depthFunc( gl.LESS );
  45376. break;
  45377. case LessEqualDepth:
  45378. gl.depthFunc( gl.LEQUAL );
  45379. break;
  45380. case EqualDepth:
  45381. gl.depthFunc( gl.EQUAL );
  45382. break;
  45383. case GreaterEqualDepth:
  45384. gl.depthFunc( gl.GEQUAL );
  45385. break;
  45386. case GreaterDepth:
  45387. gl.depthFunc( gl.GREATER );
  45388. break;
  45389. case NotEqualDepth:
  45390. gl.depthFunc( gl.NOTEQUAL );
  45391. break;
  45392. default:
  45393. gl.depthFunc( gl.LEQUAL );
  45394. }
  45395. this.currentDepthFunc = depthFunc;
  45396. }
  45397. }
  45398. /**
  45399. * Specifies the scissor box.
  45400. *
  45401. * @param {number} x - The x-coordinate of the lower left corner of the viewport.
  45402. * @param {number} y - The y-coordinate of the lower left corner of the viewport.
  45403. * @param {number} width - The width of the viewport.
  45404. * @param {number} height - The height of the viewport.
  45405. *
  45406. */
  45407. scissor( x, y, width, height ) {
  45408. const scissor = this._tempVec4.set( x, y, width, height );
  45409. if ( this.currentScissor.equals( scissor ) === false ) {
  45410. const { gl } = this;
  45411. gl.scissor( scissor.x, scissor.y, scissor.z, scissor.w );
  45412. this.currentScissor.copy( scissor );
  45413. }
  45414. }
  45415. /**
  45416. * Specifies the viewport.
  45417. *
  45418. * @param {number} x - The x-coordinate of the lower left corner of the viewport.
  45419. * @param {number} y - The y-coordinate of the lower left corner of the viewport.
  45420. * @param {number} width - The width of the viewport.
  45421. * @param {number} height - The height of the viewport.
  45422. *
  45423. */
  45424. viewport( x, y, width, height ) {
  45425. const viewport = this._tempVec4.set( x, y, width, height );
  45426. if ( this.currentViewport.equals( viewport ) === false ) {
  45427. const { gl } = this;
  45428. gl.viewport( viewport.x, viewport.y, viewport.z, viewport.w );
  45429. this.currentViewport.copy( viewport );
  45430. }
  45431. }
  45432. /**
  45433. * Defines the scissor test.
  45434. *
  45435. * @param {boolean} boolean - Whether the scissor test should be enabled or not.
  45436. */
  45437. setScissorTest( boolean ) {
  45438. const gl = this.gl;
  45439. if ( boolean ) {
  45440. gl.enable( gl.SCISSOR_TEST );
  45441. } else {
  45442. gl.disable( gl.SCISSOR_TEST );
  45443. }
  45444. }
  45445. /**
  45446. * Specifies whether the stencil test is enabled or not.
  45447. *
  45448. * @param {boolean} stencilTest - Whether the stencil test is enabled or not.
  45449. */
  45450. setStencilTest( stencilTest ) {
  45451. const { gl } = this;
  45452. if ( stencilTest ) {
  45453. this.enable( gl.STENCIL_TEST );
  45454. } else {
  45455. this.disable( gl.STENCIL_TEST );
  45456. }
  45457. }
  45458. /**
  45459. * Specifies whether stencil values can be written when rendering
  45460. * into a framebuffer or not.
  45461. *
  45462. * This method caches the state so `gl.stencilMask()` is only
  45463. * called when necessary.
  45464. *
  45465. * @param {boolean} stencilMask - The stencil mask.
  45466. */
  45467. setStencilMask( stencilMask ) {
  45468. if ( this.currentStencilMask !== stencilMask ) {
  45469. this.gl.stencilMask( stencilMask );
  45470. this.currentStencilMask = stencilMask;
  45471. }
  45472. }
  45473. /**
  45474. * Specifies whether the stencil test functions.
  45475. *
  45476. * This method caches the state so `gl.stencilFunc()` is only
  45477. * called when necessary.
  45478. *
  45479. * @param {number} stencilFunc - The stencil compare function.
  45480. * @param {number} stencilRef - The reference value for the stencil test.
  45481. * @param {number} stencilMask - A bit-wise mask that is used to AND the reference value and the stored stencil value when the test is done.
  45482. */
  45483. setStencilFunc( stencilFunc, stencilRef, stencilMask ) {
  45484. if ( this.currentStencilFunc !== stencilFunc ||
  45485. this.currentStencilRef !== stencilRef ||
  45486. this.currentStencilFuncMask !== stencilMask ) {
  45487. this.gl.stencilFunc( stencilFunc, stencilRef, stencilMask );
  45488. this.currentStencilFunc = stencilFunc;
  45489. this.currentStencilRef = stencilRef;
  45490. this.currentStencilFuncMask = stencilMask;
  45491. }
  45492. }
  45493. /**
  45494. * Specifies whether the stencil test operation.
  45495. *
  45496. * This method caches the state so `gl.stencilOp()` is only
  45497. * called when necessary.
  45498. *
  45499. * @param {number} stencilFail - The function to use when the stencil test fails.
  45500. * @param {number} stencilZFail - The function to use when the stencil test passes, but the depth test fail.
  45501. * @param {number} stencilZPass - The function to use when both the stencil test and the depth test pass,
  45502. * or when the stencil test passes and there is no depth buffer or depth testing is disabled.
  45503. */
  45504. setStencilOp( stencilFail, stencilZFail, stencilZPass ) {
  45505. if ( this.currentStencilFail !== stencilFail ||
  45506. this.currentStencilZFail !== stencilZFail ||
  45507. this.currentStencilZPass !== stencilZPass ) {
  45508. this.gl.stencilOp( stencilFail, stencilZFail, stencilZPass );
  45509. this.currentStencilFail = stencilFail;
  45510. this.currentStencilZFail = stencilZFail;
  45511. this.currentStencilZPass = stencilZPass;
  45512. }
  45513. }
  45514. /**
  45515. * Configures the WebGL state for the given material.
  45516. *
  45517. * @param {Material} material - The material to configure the state for.
  45518. * @param {number} frontFaceCW - Whether the front faces are counter-clockwise or not.
  45519. * @param {number} hardwareClippingPlanes - The number of hardware clipping planes.
  45520. */
  45521. setMaterial( material, frontFaceCW, hardwareClippingPlanes ) {
  45522. const { gl } = this;
  45523. material.side === DoubleSide
  45524. ? this.disable( gl.CULL_FACE )
  45525. : this.enable( gl.CULL_FACE );
  45526. let flipSided = ( material.side === BackSide );
  45527. if ( frontFaceCW ) flipSided = ! flipSided;
  45528. this.setFlipSided( flipSided );
  45529. ( material.blending === NormalBlending && material.transparent === false )
  45530. ? this.setBlending( NoBlending )
  45531. : this.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst, material.blendEquationAlpha, material.blendSrcAlpha, material.blendDstAlpha, material.premultipliedAlpha );
  45532. this.setDepthFunc( material.depthFunc );
  45533. this.setDepthTest( material.depthTest );
  45534. this.setDepthMask( material.depthWrite );
  45535. this.setColorMask( material.colorWrite );
  45536. const stencilWrite = material.stencilWrite;
  45537. this.setStencilTest( stencilWrite );
  45538. if ( stencilWrite ) {
  45539. this.setStencilMask( material.stencilWriteMask );
  45540. this.setStencilFunc( material.stencilFunc, material.stencilRef, material.stencilFuncMask );
  45541. this.setStencilOp( material.stencilFail, material.stencilZFail, material.stencilZPass );
  45542. }
  45543. this.setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits );
  45544. material.alphaToCoverage === true && this.backend.renderer.currentSamples > 0
  45545. ? this.enable( gl.SAMPLE_ALPHA_TO_COVERAGE )
  45546. : this.disable( gl.SAMPLE_ALPHA_TO_COVERAGE );
  45547. if ( hardwareClippingPlanes > 0 ) {
  45548. if ( this.currentClippingPlanes !== hardwareClippingPlanes ) {
  45549. const CLIP_DISTANCE0_WEBGL = 0x3000;
  45550. for ( let i = 0; i < 8; i ++ ) {
  45551. if ( i < hardwareClippingPlanes ) {
  45552. this.enable( CLIP_DISTANCE0_WEBGL + i );
  45553. } else {
  45554. this.disable( CLIP_DISTANCE0_WEBGL + i );
  45555. }
  45556. }
  45557. }
  45558. }
  45559. }
  45560. /**
  45561. * Specifies the polygon offset.
  45562. *
  45563. * This method caches the state so `gl.polygonOffset()` is only
  45564. * called when necessary.
  45565. *
  45566. * @param {boolean} polygonOffset - Whether polygon offset is enabled or not.
  45567. * @param {number} factor - The scale factor for the variable depth offset for each polygon.
  45568. * @param {number} units - The multiplier by which an implementation-specific value is multiplied with to create a constant depth offset.
  45569. */
  45570. setPolygonOffset( polygonOffset, factor, units ) {
  45571. const { gl } = this;
  45572. if ( polygonOffset ) {
  45573. this.enable( gl.POLYGON_OFFSET_FILL );
  45574. if ( this.currentPolygonOffsetFactor !== factor || this.currentPolygonOffsetUnits !== units ) {
  45575. gl.polygonOffset( factor, units );
  45576. this.currentPolygonOffsetFactor = factor;
  45577. this.currentPolygonOffsetUnits = units;
  45578. }
  45579. } else {
  45580. this.disable( gl.POLYGON_OFFSET_FILL );
  45581. }
  45582. }
  45583. /**
  45584. * Defines the usage of the given WebGL program.
  45585. *
  45586. * This method caches the state so `gl.useProgram()` is only
  45587. * called when necessary.
  45588. *
  45589. * @param {WebGLProgram} program - The WebGL program to use.
  45590. * @return {boolean} Whether a program change has been executed or not.
  45591. */
  45592. useProgram( program ) {
  45593. if ( this.currentProgram !== program ) {
  45594. this.gl.useProgram( program );
  45595. this.currentProgram = program;
  45596. return true;
  45597. }
  45598. return false;
  45599. }
  45600. /**
  45601. * Sets the vertex state by binding the given VAO and element buffer.
  45602. *
  45603. * @param {WebGLVertexArrayObject} vao - The VAO.
  45604. * @param {?WebGLBuffer} indexBuffer - The index buffer.
  45605. * @return {boolean} Whether a vertex state has been changed or not.
  45606. */
  45607. setVertexState( vao, indexBuffer = null ) {
  45608. const gl = this.gl;
  45609. if ( this.currentVAO !== vao || this.currentIndex !== indexBuffer ) {
  45610. gl.bindVertexArray( vao );
  45611. if ( indexBuffer !== null ) {
  45612. gl.bindBuffer( gl.ELEMENT_ARRAY_BUFFER, indexBuffer );
  45613. }
  45614. this.currentVAO = vao;
  45615. this.currentIndex = indexBuffer;
  45616. return true;
  45617. }
  45618. return false;
  45619. }
  45620. /**
  45621. * Resets the vertex array state by resetting the VAO and element buffer.
  45622. */
  45623. resetVertexState() {
  45624. const gl = this.gl;
  45625. gl.bindVertexArray( null );
  45626. gl.bindBuffer( gl.ELEMENT_ARRAY_BUFFER, null );
  45627. this.currentVAO = null;
  45628. this.currentIndex = null;
  45629. }
  45630. // framebuffer
  45631. /**
  45632. * Binds the given framebuffer.
  45633. *
  45634. * This method caches the state so `gl.bindFramebuffer()` is only
  45635. * called when necessary.
  45636. *
  45637. * @param {number} target - The binding point (target).
  45638. * @param {WebGLFramebuffer} framebuffer - The WebGL framebuffer to bind.
  45639. * @return {boolean} Whether a bind has been executed or not.
  45640. */
  45641. bindFramebuffer( target, framebuffer ) {
  45642. const { gl, currentBoundFramebuffers } = this;
  45643. if ( currentBoundFramebuffers[ target ] !== framebuffer ) {
  45644. gl.bindFramebuffer( target, framebuffer );
  45645. currentBoundFramebuffers[ target ] = framebuffer;
  45646. // gl.DRAW_FRAMEBUFFER is equivalent to gl.FRAMEBUFFER
  45647. if ( target === gl.DRAW_FRAMEBUFFER ) {
  45648. currentBoundFramebuffers[ gl.FRAMEBUFFER ] = framebuffer;
  45649. }
  45650. if ( target === gl.FRAMEBUFFER ) {
  45651. currentBoundFramebuffers[ gl.DRAW_FRAMEBUFFER ] = framebuffer;
  45652. }
  45653. return true;
  45654. }
  45655. return false;
  45656. }
  45657. /**
  45658. * Defines draw buffers to which fragment colors are written into.
  45659. * Configures the MRT setup of custom framebuffers.
  45660. *
  45661. * This method caches the state so `gl.drawBuffers()` is only
  45662. * called when necessary.
  45663. *
  45664. * @param {RenderContext} renderContext - The render context.
  45665. * @param {WebGLFramebuffer} framebuffer - The WebGL framebuffer.
  45666. */
  45667. drawBuffers( renderContext, framebuffer ) {
  45668. const { gl } = this;
  45669. let drawBuffers = [];
  45670. let needsUpdate = false;
  45671. if ( renderContext.textures !== null ) {
  45672. drawBuffers = this.currentDrawbuffers.get( framebuffer );
  45673. if ( drawBuffers === undefined ) {
  45674. drawBuffers = [];
  45675. this.currentDrawbuffers.set( framebuffer, drawBuffers );
  45676. }
  45677. const textures = renderContext.textures;
  45678. if ( drawBuffers.length !== textures.length || drawBuffers[ 0 ] !== gl.COLOR_ATTACHMENT0 ) {
  45679. for ( let i = 0, il = textures.length; i < il; i ++ ) {
  45680. drawBuffers[ i ] = gl.COLOR_ATTACHMENT0 + i;
  45681. }
  45682. drawBuffers.length = textures.length;
  45683. needsUpdate = true;
  45684. }
  45685. } else {
  45686. if ( drawBuffers[ 0 ] !== gl.BACK ) {
  45687. drawBuffers[ 0 ] = gl.BACK;
  45688. needsUpdate = true;
  45689. }
  45690. }
  45691. if ( needsUpdate ) {
  45692. gl.drawBuffers( drawBuffers );
  45693. }
  45694. }
  45695. // texture
  45696. /**
  45697. * Makes the given texture unit active.
  45698. *
  45699. * This method caches the state so `gl.activeTexture()` is only
  45700. * called when necessary.
  45701. *
  45702. * @param {number} webglSlot - The texture unit to make active.
  45703. */
  45704. activeTexture( webglSlot ) {
  45705. const { gl, currentTextureSlot, maxTextures } = this;
  45706. if ( webglSlot === undefined ) webglSlot = gl.TEXTURE0 + maxTextures - 1;
  45707. if ( currentTextureSlot !== webglSlot ) {
  45708. gl.activeTexture( webglSlot );
  45709. this.currentTextureSlot = webglSlot;
  45710. }
  45711. }
  45712. /**
  45713. * Binds the given WebGL texture to a target.
  45714. *
  45715. * This method caches the state so `gl.bindTexture()` is only
  45716. * called when necessary.
  45717. *
  45718. * @param {number} webglType - The binding point (target).
  45719. * @param {WebGLTexture} webglTexture - The WebGL texture to bind.
  45720. * @param {number} webglSlot - The texture.
  45721. */
  45722. bindTexture( webglType, webglTexture, webglSlot ) {
  45723. const { gl, currentTextureSlot, currentBoundTextures, maxTextures } = this;
  45724. if ( webglSlot === undefined ) {
  45725. if ( currentTextureSlot === null ) {
  45726. webglSlot = gl.TEXTURE0 + maxTextures - 1;
  45727. } else {
  45728. webglSlot = currentTextureSlot;
  45729. }
  45730. }
  45731. let boundTexture = currentBoundTextures[ webglSlot ];
  45732. if ( boundTexture === undefined ) {
  45733. boundTexture = { type: undefined, texture: undefined };
  45734. currentBoundTextures[ webglSlot ] = boundTexture;
  45735. }
  45736. if ( boundTexture.type !== webglType || boundTexture.texture !== webglTexture ) {
  45737. if ( currentTextureSlot !== webglSlot ) {
  45738. gl.activeTexture( webglSlot );
  45739. this.currentTextureSlot = webglSlot;
  45740. }
  45741. gl.bindTexture( webglType, webglTexture );
  45742. boundTexture.type = webglType;
  45743. boundTexture.texture = webglTexture;
  45744. }
  45745. }
  45746. /**
  45747. * Binds a given WebGL buffer to a given binding point (target) at a given index.
  45748. *
  45749. * This method caches the state so `gl.bindBufferBase()` is only
  45750. * called when necessary.
  45751. *
  45752. * @param {number} target - The target for the bind operation.
  45753. * @param {number} index - The index of the target.
  45754. * @param {WebGLBuffer} buffer - The WebGL buffer.
  45755. * @return {boolean} Whether a bind has been executed or not.
  45756. */
  45757. bindBufferBase( target, index, buffer ) {
  45758. const { gl } = this;
  45759. const key = `${target}-${index}`;
  45760. if ( this.currentBoundBufferBases[ key ] !== buffer ) {
  45761. gl.bindBufferBase( target, index, buffer );
  45762. this.currentBoundBufferBases[ key ] = buffer;
  45763. return true;
  45764. }
  45765. return false;
  45766. }
  45767. /**
  45768. * Unbinds the current bound texture.
  45769. *
  45770. * This method caches the state so `gl.bindTexture()` is only
  45771. * called when necessary.
  45772. */
  45773. unbindTexture() {
  45774. const { gl, currentTextureSlot, currentBoundTextures } = this;
  45775. const boundTexture = currentBoundTextures[ currentTextureSlot ];
  45776. if ( boundTexture !== undefined && boundTexture.type !== undefined ) {
  45777. gl.bindTexture( boundTexture.type, null );
  45778. boundTexture.type = undefined;
  45779. boundTexture.texture = undefined;
  45780. }
  45781. }
  45782. }
  45783. /**
  45784. * A WebGL 2 backend utility module with common helpers.
  45785. *
  45786. * @private
  45787. */
  45788. class WebGLUtils {
  45789. /**
  45790. * Constructs a new utility object.
  45791. *
  45792. * @param {WebGLBackend} backend - The WebGL 2 backend.
  45793. */
  45794. constructor( backend ) {
  45795. /**
  45796. * A reference to the WebGL 2 backend.
  45797. *
  45798. * @type {WebGLBackend}
  45799. */
  45800. this.backend = backend;
  45801. /**
  45802. * A reference to the rendering context.
  45803. *
  45804. * @type {WebGL2RenderingContext}
  45805. */
  45806. this.gl = this.backend.gl;
  45807. /**
  45808. * A reference to a backend module holding extension-related
  45809. * utility functions.
  45810. *
  45811. * @type {WebGLExtensions}
  45812. */
  45813. this.extensions = backend.extensions;
  45814. }
  45815. /**
  45816. * Converts the given three.js constant into a WebGL constant.
  45817. * The method currently supports the conversion of texture formats
  45818. * and types.
  45819. *
  45820. * @param {number} p - The three.js constant.
  45821. * @param {string} [colorSpace=NoColorSpace] - The color space.
  45822. * @return {?number} The corresponding WebGL constant.
  45823. */
  45824. convert( p, colorSpace = NoColorSpace ) {
  45825. const { gl, extensions } = this;
  45826. let extension;
  45827. const transfer = ColorManagement.getTransfer( colorSpace );
  45828. if ( p === UnsignedByteType ) return gl.UNSIGNED_BYTE;
  45829. if ( p === UnsignedShort4444Type ) return gl.UNSIGNED_SHORT_4_4_4_4;
  45830. if ( p === UnsignedShort5551Type ) return gl.UNSIGNED_SHORT_5_5_5_1;
  45831. if ( p === UnsignedInt5999Type ) return gl.UNSIGNED_INT_5_9_9_9_REV;
  45832. if ( p === UnsignedInt101111Type ) return gl.UNSIGNED_INT_10F_11F_11F_REV;
  45833. if ( p === ByteType ) return gl.BYTE;
  45834. if ( p === ShortType ) return gl.SHORT;
  45835. if ( p === UnsignedShortType ) return gl.UNSIGNED_SHORT;
  45836. if ( p === IntType ) return gl.INT;
  45837. if ( p === UnsignedIntType ) return gl.UNSIGNED_INT;
  45838. if ( p === FloatType ) return gl.FLOAT;
  45839. if ( p === HalfFloatType ) {
  45840. return gl.HALF_FLOAT;
  45841. }
  45842. if ( p === AlphaFormat ) return gl.ALPHA;
  45843. if ( p === RGBFormat ) return gl.RGB;
  45844. if ( p === RGBAFormat ) return gl.RGBA;
  45845. if ( p === DepthFormat ) return gl.DEPTH_COMPONENT;
  45846. if ( p === DepthStencilFormat ) return gl.DEPTH_STENCIL;
  45847. // WebGL2 formats.
  45848. if ( p === RedFormat ) return gl.RED;
  45849. if ( p === RedIntegerFormat ) return gl.RED_INTEGER;
  45850. if ( p === RGFormat ) return gl.RG;
  45851. if ( p === RGIntegerFormat ) return gl.RG_INTEGER;
  45852. if ( p === RGBAIntegerFormat ) return gl.RGBA_INTEGER;
  45853. // S3TC
  45854. if ( p === RGB_S3TC_DXT1_Format || p === RGBA_S3TC_DXT1_Format || p === RGBA_S3TC_DXT3_Format || p === RGBA_S3TC_DXT5_Format ) {
  45855. if ( transfer === SRGBTransfer ) {
  45856. extension = extensions.get( 'WEBGL_compressed_texture_s3tc_srgb' );
  45857. if ( extension !== null ) {
  45858. if ( p === RGB_S3TC_DXT1_Format ) return extension.COMPRESSED_SRGB_S3TC_DXT1_EXT;
  45859. if ( p === RGBA_S3TC_DXT1_Format ) return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT;
  45860. if ( p === RGBA_S3TC_DXT3_Format ) return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT;
  45861. if ( p === RGBA_S3TC_DXT5_Format ) return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT;
  45862. } else {
  45863. return null;
  45864. }
  45865. } else {
  45866. extension = extensions.get( 'WEBGL_compressed_texture_s3tc' );
  45867. if ( extension !== null ) {
  45868. if ( p === RGB_S3TC_DXT1_Format ) return extension.COMPRESSED_RGB_S3TC_DXT1_EXT;
  45869. if ( p === RGBA_S3TC_DXT1_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  45870. if ( p === RGBA_S3TC_DXT3_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  45871. if ( p === RGBA_S3TC_DXT5_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  45872. } else {
  45873. return null;
  45874. }
  45875. }
  45876. }
  45877. // PVRTC
  45878. if ( p === RGB_PVRTC_4BPPV1_Format || p === RGB_PVRTC_2BPPV1_Format || p === RGBA_PVRTC_4BPPV1_Format || p === RGBA_PVRTC_2BPPV1_Format ) {
  45879. extension = extensions.get( 'WEBGL_compressed_texture_pvrtc' );
  45880. if ( extension !== null ) {
  45881. if ( p === RGB_PVRTC_4BPPV1_Format ) return extension.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;
  45882. if ( p === RGB_PVRTC_2BPPV1_Format ) return extension.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;
  45883. if ( p === RGBA_PVRTC_4BPPV1_Format ) return extension.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;
  45884. if ( p === RGBA_PVRTC_2BPPV1_Format ) return extension.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG;
  45885. } else {
  45886. return null;
  45887. }
  45888. }
  45889. // ETC
  45890. if ( p === RGB_ETC1_Format || p === RGB_ETC2_Format || p === RGBA_ETC2_EAC_Format ) {
  45891. extension = extensions.get( 'WEBGL_compressed_texture_etc' );
  45892. if ( extension !== null ) {
  45893. if ( p === RGB_ETC1_Format || p === RGB_ETC2_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ETC2 : extension.COMPRESSED_RGB8_ETC2;
  45894. if ( p === RGBA_ETC2_EAC_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC : extension.COMPRESSED_RGBA8_ETC2_EAC;
  45895. } else {
  45896. return null;
  45897. }
  45898. }
  45899. // ASTC
  45900. if ( p === RGBA_ASTC_4x4_Format || p === RGBA_ASTC_5x4_Format || p === RGBA_ASTC_5x5_Format ||
  45901. p === RGBA_ASTC_6x5_Format || p === RGBA_ASTC_6x6_Format || p === RGBA_ASTC_8x5_Format ||
  45902. p === RGBA_ASTC_8x6_Format || p === RGBA_ASTC_8x8_Format || p === RGBA_ASTC_10x5_Format ||
  45903. p === RGBA_ASTC_10x6_Format || p === RGBA_ASTC_10x8_Format || p === RGBA_ASTC_10x10_Format ||
  45904. p === RGBA_ASTC_12x10_Format || p === RGBA_ASTC_12x12_Format ) {
  45905. extension = extensions.get( 'WEBGL_compressed_texture_astc' );
  45906. if ( extension !== null ) {
  45907. if ( p === RGBA_ASTC_4x4_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR : extension.COMPRESSED_RGBA_ASTC_4x4_KHR;
  45908. if ( p === RGBA_ASTC_5x4_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR : extension.COMPRESSED_RGBA_ASTC_5x4_KHR;
  45909. if ( p === RGBA_ASTC_5x5_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR : extension.COMPRESSED_RGBA_ASTC_5x5_KHR;
  45910. if ( p === RGBA_ASTC_6x5_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR : extension.COMPRESSED_RGBA_ASTC_6x5_KHR;
  45911. if ( p === RGBA_ASTC_6x6_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR : extension.COMPRESSED_RGBA_ASTC_6x6_KHR;
  45912. if ( p === RGBA_ASTC_8x5_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR : extension.COMPRESSED_RGBA_ASTC_8x5_KHR;
  45913. if ( p === RGBA_ASTC_8x6_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR : extension.COMPRESSED_RGBA_ASTC_8x6_KHR;
  45914. if ( p === RGBA_ASTC_8x8_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR : extension.COMPRESSED_RGBA_ASTC_8x8_KHR;
  45915. if ( p === RGBA_ASTC_10x5_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR : extension.COMPRESSED_RGBA_ASTC_10x5_KHR;
  45916. if ( p === RGBA_ASTC_10x6_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR : extension.COMPRESSED_RGBA_ASTC_10x6_KHR;
  45917. if ( p === RGBA_ASTC_10x8_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR : extension.COMPRESSED_RGBA_ASTC_10x8_KHR;
  45918. if ( p === RGBA_ASTC_10x10_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR : extension.COMPRESSED_RGBA_ASTC_10x10_KHR;
  45919. if ( p === RGBA_ASTC_12x10_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR : extension.COMPRESSED_RGBA_ASTC_12x10_KHR;
  45920. if ( p === RGBA_ASTC_12x12_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR : extension.COMPRESSED_RGBA_ASTC_12x12_KHR;
  45921. } else {
  45922. return null;
  45923. }
  45924. }
  45925. // BPTC
  45926. if ( p === RGBA_BPTC_Format ) {
  45927. extension = extensions.get( 'EXT_texture_compression_bptc' );
  45928. if ( extension !== null ) {
  45929. if ( p === RGBA_BPTC_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT : extension.COMPRESSED_RGBA_BPTC_UNORM_EXT;
  45930. } else {
  45931. return null;
  45932. }
  45933. }
  45934. // RGTC
  45935. if ( p === RED_RGTC1_Format || p === SIGNED_RED_RGTC1_Format || p === RED_GREEN_RGTC2_Format || p === SIGNED_RED_GREEN_RGTC2_Format ) {
  45936. extension = extensions.get( 'EXT_texture_compression_rgtc' );
  45937. if ( extension !== null ) {
  45938. if ( p === RED_RGTC1_Format ) return extension.COMPRESSED_RED_RGTC1_EXT;
  45939. if ( p === SIGNED_RED_RGTC1_Format ) return extension.COMPRESSED_SIGNED_RED_RGTC1_EXT;
  45940. if ( p === RED_GREEN_RGTC2_Format ) return extension.COMPRESSED_RED_GREEN_RGTC2_EXT;
  45941. if ( p === SIGNED_RED_GREEN_RGTC2_Format ) return extension.COMPRESSED_SIGNED_RED_GREEN_RGTC2_EXT;
  45942. } else {
  45943. return null;
  45944. }
  45945. }
  45946. //
  45947. if ( p === UnsignedInt248Type ) {
  45948. return gl.UNSIGNED_INT_24_8;
  45949. }
  45950. // if "p" can't be resolved, assume the user defines a WebGL constant as a string (fallback/workaround for packed RGB formats)
  45951. return ( gl[ p ] !== undefined ) ? gl[ p ] : null;
  45952. }
  45953. /**
  45954. * This method can be used to synchronize the CPU with the GPU by waiting until
  45955. * ongoing GPU commands have been completed.
  45956. *
  45957. * @private
  45958. * @return {Promise} A promise that resolves when all ongoing GPU commands have been completed.
  45959. */
  45960. _clientWaitAsync() {
  45961. const { gl } = this;
  45962. const sync = gl.fenceSync( gl.SYNC_GPU_COMMANDS_COMPLETE, 0 );
  45963. gl.flush();
  45964. return new Promise( ( resolve, reject ) => {
  45965. function test() {
  45966. const res = gl.clientWaitSync( sync, gl.SYNC_FLUSH_COMMANDS_BIT, 0 );
  45967. if ( res === gl.WAIT_FAILED ) {
  45968. gl.deleteSync( sync );
  45969. reject();
  45970. return;
  45971. }
  45972. if ( res === gl.TIMEOUT_EXPIRED ) {
  45973. requestAnimationFrame( test );
  45974. return;
  45975. }
  45976. gl.deleteSync( sync );
  45977. resolve();
  45978. }
  45979. test();
  45980. } );
  45981. }
  45982. }
  45983. let initialized = false, wrappingToGL, filterToGL, compareToGL;
  45984. /**
  45985. * A WebGL 2 backend utility module for managing textures.
  45986. *
  45987. * @private
  45988. */
  45989. class WebGLTextureUtils {
  45990. /**
  45991. * Constructs a new utility object.
  45992. *
  45993. * @param {WebGLBackend} backend - The WebGL 2 backend.
  45994. */
  45995. constructor( backend ) {
  45996. /**
  45997. * A reference to the WebGL 2 backend.
  45998. *
  45999. * @type {WebGLBackend}
  46000. */
  46001. this.backend = backend;
  46002. /**
  46003. * A reference to the rendering context.
  46004. *
  46005. * @type {WebGL2RenderingContext}
  46006. */
  46007. this.gl = backend.gl;
  46008. /**
  46009. * A reference to a backend module holding extension-related
  46010. * utility functions.
  46011. *
  46012. * @type {WebGLExtensions}
  46013. */
  46014. this.extensions = backend.extensions;
  46015. /**
  46016. * A dictionary for managing default textures. The key
  46017. * is the binding point (target), the value the WEbGL texture object.
  46018. *
  46019. * @type {Object<GLenum,WebGLTexture>}
  46020. */
  46021. this.defaultTextures = {};
  46022. /**
  46023. * A scratch framebuffer used for attaching the source texture in
  46024. * {@link copyTextureToTexture}.
  46025. *
  46026. * @private
  46027. * @type {?WebGLFramebuffer}
  46028. */
  46029. this._srcFramebuffer = null;
  46030. /**
  46031. * A scratch framebuffer used for attaching the destination texture in
  46032. * {@link copyTextureToTexture}.
  46033. *
  46034. * @private
  46035. * @type {?WebGLFramebuffer}
  46036. */
  46037. this._dstFramebuffer = null;
  46038. if ( initialized === false ) {
  46039. this._init();
  46040. initialized = true;
  46041. }
  46042. }
  46043. /**
  46044. * Inits the state of the utility.
  46045. *
  46046. * @private
  46047. */
  46048. _init() {
  46049. const gl = this.gl;
  46050. // Store only WebGL constants here.
  46051. wrappingToGL = {
  46052. [ RepeatWrapping ]: gl.REPEAT,
  46053. [ ClampToEdgeWrapping ]: gl.CLAMP_TO_EDGE,
  46054. [ MirroredRepeatWrapping ]: gl.MIRRORED_REPEAT
  46055. };
  46056. filterToGL = {
  46057. [ NearestFilter ]: gl.NEAREST,
  46058. [ NearestMipmapNearestFilter ]: gl.NEAREST_MIPMAP_NEAREST,
  46059. [ NearestMipmapLinearFilter ]: gl.NEAREST_MIPMAP_LINEAR,
  46060. [ LinearFilter ]: gl.LINEAR,
  46061. [ LinearMipmapNearestFilter ]: gl.LINEAR_MIPMAP_NEAREST,
  46062. [ LinearMipmapLinearFilter ]: gl.LINEAR_MIPMAP_LINEAR
  46063. };
  46064. compareToGL = {
  46065. [ NeverCompare ]: gl.NEVER,
  46066. [ AlwaysCompare ]: gl.ALWAYS,
  46067. [ LessCompare ]: gl.LESS,
  46068. [ LessEqualCompare ]: gl.LEQUAL,
  46069. [ EqualCompare ]: gl.EQUAL,
  46070. [ GreaterEqualCompare ]: gl.GEQUAL,
  46071. [ GreaterCompare ]: gl.GREATER,
  46072. [ NotEqualCompare ]: gl.NOTEQUAL
  46073. };
  46074. }
  46075. /**
  46076. * Returns the native texture type for the given texture.
  46077. *
  46078. * @param {Texture} texture - The texture.
  46079. * @return {GLenum} The native texture type.
  46080. */
  46081. getGLTextureType( texture ) {
  46082. const { gl } = this;
  46083. let glTextureType;
  46084. if ( texture.isCubeTexture === true ) {
  46085. glTextureType = gl.TEXTURE_CUBE_MAP;
  46086. } else if ( texture.isArrayTexture === true || texture.isDataArrayTexture === true || texture.isCompressedArrayTexture === true ) {
  46087. glTextureType = gl.TEXTURE_2D_ARRAY;
  46088. } else if ( texture.isData3DTexture === true ) { // TODO: isCompressed3DTexture, wait for #26642
  46089. glTextureType = gl.TEXTURE_3D;
  46090. } else {
  46091. glTextureType = gl.TEXTURE_2D;
  46092. }
  46093. return glTextureType;
  46094. }
  46095. /**
  46096. * Returns the native texture type for the given texture.
  46097. *
  46098. * @param {?string} internalFormatName - The internal format name. When `null`, the internal format is derived from the subsequent parameters.
  46099. * @param {GLenum} glFormat - The WebGL format.
  46100. * @param {GLenum} glType - The WebGL type.
  46101. * @param {string} colorSpace - The texture's color space.
  46102. * @param {boolean} [forceLinearTransfer=false] - Whether to force a linear transfer or not.
  46103. * @return {GLenum} The internal format.
  46104. */
  46105. getInternalFormat( internalFormatName, glFormat, glType, colorSpace, forceLinearTransfer = false ) {
  46106. const { gl, extensions } = this;
  46107. if ( internalFormatName !== null ) {
  46108. if ( gl[ internalFormatName ] !== undefined ) return gl[ internalFormatName ];
  46109. warn( 'WebGLBackend: Attempt to use non-existing WebGL internal format \'' + internalFormatName + '\'' );
  46110. }
  46111. let internalFormat = glFormat;
  46112. if ( glFormat === gl.RED ) {
  46113. if ( glType === gl.FLOAT ) internalFormat = gl.R32F;
  46114. if ( glType === gl.HALF_FLOAT ) internalFormat = gl.R16F;
  46115. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.R8;
  46116. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.R16;
  46117. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.R32UI;
  46118. if ( glType === gl.BYTE ) internalFormat = gl.R8I;
  46119. if ( glType === gl.SHORT ) internalFormat = gl.R16I;
  46120. if ( glType === gl.INT ) internalFormat = gl.R32I;
  46121. }
  46122. if ( glFormat === gl.RED_INTEGER ) {
  46123. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.R8UI;
  46124. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.R16UI;
  46125. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.R32UI;
  46126. if ( glType === gl.BYTE ) internalFormat = gl.R8I;
  46127. if ( glType === gl.SHORT ) internalFormat = gl.R16I;
  46128. if ( glType === gl.INT ) internalFormat = gl.R32I;
  46129. }
  46130. if ( glFormat === gl.RG ) {
  46131. if ( glType === gl.FLOAT ) internalFormat = gl.RG32F;
  46132. if ( glType === gl.HALF_FLOAT ) internalFormat = gl.RG16F;
  46133. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RG8;
  46134. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RG16;
  46135. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RG32UI;
  46136. if ( glType === gl.BYTE ) internalFormat = gl.RG8I;
  46137. if ( glType === gl.SHORT ) internalFormat = gl.RG16I;
  46138. if ( glType === gl.INT ) internalFormat = gl.RG32I;
  46139. }
  46140. if ( glFormat === gl.RG_INTEGER ) {
  46141. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RG8UI;
  46142. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RG16UI;
  46143. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RG32UI;
  46144. if ( glType === gl.BYTE ) internalFormat = gl.RG8I;
  46145. if ( glType === gl.SHORT ) internalFormat = gl.RG16I;
  46146. if ( glType === gl.INT ) internalFormat = gl.RG32I;
  46147. }
  46148. if ( glFormat === gl.RGB ) {
  46149. const transfer = forceLinearTransfer ? LinearTransfer : ColorManagement.getTransfer( colorSpace );
  46150. if ( glType === gl.FLOAT ) internalFormat = gl.RGB32F;
  46151. if ( glType === gl.HALF_FLOAT ) internalFormat = gl.RGB16F;
  46152. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RGB8;
  46153. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RGB16;
  46154. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RGB32UI;
  46155. if ( glType === gl.BYTE ) internalFormat = gl.RGB8I;
  46156. if ( glType === gl.SHORT ) internalFormat = gl.RGB16I;
  46157. if ( glType === gl.INT ) internalFormat = gl.RGB32I;
  46158. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = ( transfer === SRGBTransfer ) ? gl.SRGB8 : gl.RGB8;
  46159. if ( glType === gl.UNSIGNED_SHORT_5_6_5 ) internalFormat = gl.RGB565;
  46160. if ( glType === gl.UNSIGNED_SHORT_5_5_5_1 ) internalFormat = gl.RGB5_A1;
  46161. if ( glType === gl.UNSIGNED_SHORT_4_4_4_4 ) internalFormat = gl.RGB4;
  46162. if ( glType === gl.UNSIGNED_INT_5_9_9_9_REV ) internalFormat = gl.RGB9_E5;
  46163. if ( glType === gl.UNSIGNED_INT_10F_11F_11F_REV ) internalFormat = gl.R11F_G11F_B10F;
  46164. }
  46165. if ( glFormat === gl.RGB_INTEGER ) {
  46166. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RGB8UI;
  46167. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RGB16UI;
  46168. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RGB32UI;
  46169. if ( glType === gl.BYTE ) internalFormat = gl.RGB8I;
  46170. if ( glType === gl.SHORT ) internalFormat = gl.RGB16I;
  46171. if ( glType === gl.INT ) internalFormat = gl.RGB32I;
  46172. }
  46173. if ( glFormat === gl.RGBA ) {
  46174. const transfer = forceLinearTransfer ? LinearTransfer : ColorManagement.getTransfer( colorSpace );
  46175. if ( glType === gl.FLOAT ) internalFormat = gl.RGBA32F;
  46176. if ( glType === gl.HALF_FLOAT ) internalFormat = gl.RGBA16F;
  46177. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RGBA8;
  46178. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RGBA16;
  46179. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RGBA32UI;
  46180. if ( glType === gl.BYTE ) internalFormat = gl.RGBA8I;
  46181. if ( glType === gl.SHORT ) internalFormat = gl.RGBA16I;
  46182. if ( glType === gl.INT ) internalFormat = gl.RGBA32I;
  46183. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = ( transfer === SRGBTransfer ) ? gl.SRGB8_ALPHA8 : gl.RGBA8;
  46184. if ( glType === gl.UNSIGNED_SHORT_4_4_4_4 ) internalFormat = gl.RGBA4;
  46185. if ( glType === gl.UNSIGNED_SHORT_5_5_5_1 ) internalFormat = gl.RGB5_A1;
  46186. }
  46187. if ( glFormat === gl.RGBA_INTEGER ) {
  46188. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RGBA8UI;
  46189. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RGBA16UI;
  46190. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RGBA32UI;
  46191. if ( glType === gl.BYTE ) internalFormat = gl.RGBA8I;
  46192. if ( glType === gl.SHORT ) internalFormat = gl.RGBA16I;
  46193. if ( glType === gl.INT ) internalFormat = gl.RGBA32I;
  46194. }
  46195. if ( glFormat === gl.DEPTH_COMPONENT ) {
  46196. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.DEPTH_COMPONENT16;
  46197. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.DEPTH_COMPONENT24;
  46198. if ( glType === gl.FLOAT ) internalFormat = gl.DEPTH_COMPONENT32F;
  46199. }
  46200. if ( glFormat === gl.DEPTH_STENCIL ) {
  46201. if ( glType === gl.UNSIGNED_INT_24_8 ) internalFormat = gl.DEPTH24_STENCIL8;
  46202. }
  46203. if ( internalFormat === gl.R16F || internalFormat === gl.R32F ||
  46204. internalFormat === gl.RG16F || internalFormat === gl.RG32F ||
  46205. internalFormat === gl.RGBA16F || internalFormat === gl.RGBA32F ) {
  46206. extensions.get( 'EXT_color_buffer_float' );
  46207. }
  46208. return internalFormat;
  46209. }
  46210. /**
  46211. * Sets the texture parameters for the given texture.
  46212. *
  46213. * @param {GLenum} textureType - The texture type.
  46214. * @param {Texture} texture - The texture.
  46215. */
  46216. setTextureParameters( textureType, texture ) {
  46217. const { gl, extensions, backend } = this;
  46218. const workingPrimaries = ColorManagement.getPrimaries( ColorManagement.workingColorSpace );
  46219. const texturePrimaries = texture.colorSpace === NoColorSpace ? null : ColorManagement.getPrimaries( texture.colorSpace );
  46220. const unpackConversion = texture.colorSpace === NoColorSpace || workingPrimaries === texturePrimaries ? gl.NONE : gl.BROWSER_DEFAULT_WEBGL;
  46221. gl.pixelStorei( gl.UNPACK_FLIP_Y_WEBGL, texture.flipY );
  46222. gl.pixelStorei( gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, texture.premultiplyAlpha );
  46223. gl.pixelStorei( gl.UNPACK_ALIGNMENT, texture.unpackAlignment );
  46224. gl.pixelStorei( gl.UNPACK_COLORSPACE_CONVERSION_WEBGL, unpackConversion );
  46225. gl.texParameteri( textureType, gl.TEXTURE_WRAP_S, wrappingToGL[ texture.wrapS ] );
  46226. gl.texParameteri( textureType, gl.TEXTURE_WRAP_T, wrappingToGL[ texture.wrapT ] );
  46227. if ( textureType === gl.TEXTURE_3D || textureType === gl.TEXTURE_2D_ARRAY ) {
  46228. // WebGL 2 does not support wrapping for depth 2D array textures
  46229. if ( ! texture.isArrayTexture ) {
  46230. gl.texParameteri( textureType, gl.TEXTURE_WRAP_R, wrappingToGL[ texture.wrapR ] );
  46231. }
  46232. }
  46233. gl.texParameteri( textureType, gl.TEXTURE_MAG_FILTER, filterToGL[ texture.magFilter ] );
  46234. const hasMipmaps = texture.mipmaps !== undefined && texture.mipmaps.length > 0;
  46235. // follow WebGPU backend mapping for texture filtering
  46236. const minFilter = texture.minFilter === LinearFilter && hasMipmaps ? LinearMipmapLinearFilter : texture.minFilter;
  46237. gl.texParameteri( textureType, gl.TEXTURE_MIN_FILTER, filterToGL[ minFilter ] );
  46238. if ( texture.compareFunction ) {
  46239. gl.texParameteri( textureType, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE );
  46240. gl.texParameteri( textureType, gl.TEXTURE_COMPARE_FUNC, compareToGL[ texture.compareFunction ] );
  46241. }
  46242. if ( extensions.has( 'EXT_texture_filter_anisotropic' ) === true ) {
  46243. if ( texture.magFilter === NearestFilter ) return;
  46244. if ( texture.minFilter !== NearestMipmapLinearFilter && texture.minFilter !== LinearMipmapLinearFilter ) return;
  46245. if ( texture.type === FloatType && extensions.has( 'OES_texture_float_linear' ) === false ) return; // verify extension for WebGL 1 and WebGL 2
  46246. if ( texture.anisotropy > 1 ) {
  46247. const extension = extensions.get( 'EXT_texture_filter_anisotropic' );
  46248. gl.texParameterf( textureType, extension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min( texture.anisotropy, backend.getMaxAnisotropy() ) );
  46249. }
  46250. }
  46251. }
  46252. /**
  46253. * Creates a default texture for the given texture that can be used
  46254. * as a placeholder until the actual texture is ready for usage.
  46255. *
  46256. * @param {Texture} texture - The texture to create a default texture for.
  46257. */
  46258. createDefaultTexture( texture ) {
  46259. const { gl, backend, defaultTextures } = this;
  46260. const glTextureType = this.getGLTextureType( texture );
  46261. let textureGPU = defaultTextures[ glTextureType ];
  46262. if ( textureGPU === undefined ) {
  46263. textureGPU = gl.createTexture();
  46264. backend.state.bindTexture( glTextureType, textureGPU );
  46265. gl.texParameteri( glTextureType, gl.TEXTURE_MIN_FILTER, gl.NEAREST );
  46266. gl.texParameteri( glTextureType, gl.TEXTURE_MAG_FILTER, gl.NEAREST );
  46267. // gl.texImage2D( glTextureType, 0, gl.RGBA, 1, 1, 0, gl.RGBA, gl.UNSIGNED_BYTE, data );
  46268. defaultTextures[ glTextureType ] = textureGPU;
  46269. }
  46270. backend.set( texture, {
  46271. textureGPU,
  46272. glTextureType
  46273. } );
  46274. }
  46275. /**
  46276. * Defines a texture on the GPU for the given texture object.
  46277. *
  46278. * @param {Texture} texture - The texture.
  46279. * @param {Object} [options={}] - Optional configuration parameter.
  46280. * @return {undefined}
  46281. */
  46282. createTexture( texture, options ) {
  46283. const { gl, backend } = this;
  46284. const { levels, width, height, depth } = options;
  46285. const glFormat = backend.utils.convert( texture.format, texture.colorSpace );
  46286. const glType = backend.utils.convert( texture.type );
  46287. const glInternalFormat = this.getInternalFormat( texture.internalFormat, glFormat, glType, texture.colorSpace, texture.isVideoTexture );
  46288. const textureGPU = gl.createTexture();
  46289. const glTextureType = this.getGLTextureType( texture );
  46290. backend.state.bindTexture( glTextureType, textureGPU );
  46291. this.setTextureParameters( glTextureType, texture );
  46292. if ( texture.isArrayTexture || texture.isDataArrayTexture || texture.isCompressedArrayTexture ) {
  46293. gl.texStorage3D( gl.TEXTURE_2D_ARRAY, levels, glInternalFormat, width, height, depth );
  46294. } else if ( texture.isData3DTexture ) {
  46295. gl.texStorage3D( gl.TEXTURE_3D, levels, glInternalFormat, width, height, depth );
  46296. } else if ( ! texture.isVideoTexture ) {
  46297. gl.texStorage2D( glTextureType, levels, glInternalFormat, width, height );
  46298. }
  46299. backend.set( texture, {
  46300. textureGPU,
  46301. glTextureType,
  46302. glFormat,
  46303. glType,
  46304. glInternalFormat
  46305. } );
  46306. }
  46307. /**
  46308. * Uploads texture buffer data to the GPU memory.
  46309. *
  46310. * @param {WebGLBuffer} buffer - The buffer data.
  46311. * @param {Texture} texture - The texture,
  46312. */
  46313. copyBufferToTexture( buffer, texture ) {
  46314. const { gl, backend } = this;
  46315. const { textureGPU, glTextureType, glFormat, glType } = backend.get( texture );
  46316. const { width, height } = texture.source.data;
  46317. gl.bindBuffer( gl.PIXEL_UNPACK_BUFFER, buffer );
  46318. backend.state.bindTexture( glTextureType, textureGPU );
  46319. gl.pixelStorei( gl.UNPACK_FLIP_Y_WEBGL, false );
  46320. gl.pixelStorei( gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, false );
  46321. gl.texSubImage2D( glTextureType, 0, 0, 0, width, height, glFormat, glType, 0 );
  46322. gl.bindBuffer( gl.PIXEL_UNPACK_BUFFER, null );
  46323. backend.state.unbindTexture();
  46324. // debug
  46325. // const framebuffer = gl.createFramebuffer();
  46326. // gl.bindFramebuffer( gl.FRAMEBUFFER, framebuffer );
  46327. // gl.framebufferTexture2D( gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, glTextureType, textureGPU, 0 );
  46328. // const readout = new Float32Array( width * height * 4 );
  46329. // const altFormat = gl.getParameter( gl.IMPLEMENTATION_COLOR_READ_FORMAT );
  46330. // const altType = gl.getParameter( gl.IMPLEMENTATION_COLOR_READ_TYPE );
  46331. // gl.readPixels( 0, 0, width, height, altFormat, altType, readout );
  46332. // gl.bindFramebuffer( gl.FRAMEBUFFER, null );
  46333. // log( readout );
  46334. }
  46335. /**
  46336. * Uploads the updated texture data to the GPU.
  46337. *
  46338. * @param {Texture} texture - The texture.
  46339. * @param {Object} [options={}] - Optional configuration parameter.
  46340. */
  46341. updateTexture( texture, options ) {
  46342. const { gl } = this;
  46343. const { width, height } = options;
  46344. const { textureGPU, glTextureType, glFormat, glType, glInternalFormat } = this.backend.get( texture );
  46345. if ( texture.isRenderTargetTexture || ( textureGPU === undefined /* unsupported texture format */ ) )
  46346. return;
  46347. this.backend.state.bindTexture( glTextureType, textureGPU );
  46348. this.setTextureParameters( glTextureType, texture );
  46349. if ( texture.isCompressedTexture ) {
  46350. const mipmaps = texture.mipmaps;
  46351. const image = options.image;
  46352. for ( let i = 0; i < mipmaps.length; i ++ ) {
  46353. const mipmap = mipmaps[ i ];
  46354. if ( texture.isCompressedArrayTexture ) {
  46355. if ( texture.format !== gl.RGBA ) {
  46356. if ( glFormat !== null ) {
  46357. gl.compressedTexSubImage3D( gl.TEXTURE_2D_ARRAY, i, 0, 0, 0, mipmap.width, mipmap.height, image.depth, glFormat, mipmap.data );
  46358. } else {
  46359. warn( 'WebGLBackend: Attempt to load unsupported compressed texture format in .uploadTexture()' );
  46360. }
  46361. } else {
  46362. gl.texSubImage3D( gl.TEXTURE_2D_ARRAY, i, 0, 0, 0, mipmap.width, mipmap.height, image.depth, glFormat, glType, mipmap.data );
  46363. }
  46364. } else {
  46365. if ( glFormat !== null ) {
  46366. gl.compressedTexSubImage2D( gl.TEXTURE_2D, i, 0, 0, mipmap.width, mipmap.height, glFormat, mipmap.data );
  46367. } else {
  46368. warn( 'WebGLBackend: Unsupported compressed texture format' );
  46369. }
  46370. }
  46371. }
  46372. } else if ( texture.isCubeTexture ) {
  46373. const images = options.images;
  46374. const mipmaps = texture.mipmaps;
  46375. for ( let i = 0; i < 6; i ++ ) {
  46376. const image = getImage( images[ i ] );
  46377. gl.texSubImage2D( gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, 0, 0, width, height, glFormat, glType, image );
  46378. for ( let j = 0; j < mipmaps.length; j ++ ) {
  46379. const mipmap = mipmaps[ j ];
  46380. const image = getImage( mipmap.images[ i ] );
  46381. gl.texSubImage2D( gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j + 1, 0, 0, image.width, image.height, glFormat, glType, image );
  46382. }
  46383. }
  46384. } else if ( texture.isDataArrayTexture || texture.isArrayTexture ) {
  46385. const image = options.image;
  46386. if ( texture.layerUpdates.size > 0 ) {
  46387. const layerByteLength = getByteLength( image.width, image.height, texture.format, texture.type );
  46388. for ( const layerIndex of texture.layerUpdates ) {
  46389. const layerData = image.data.subarray(
  46390. layerIndex * layerByteLength / image.data.BYTES_PER_ELEMENT,
  46391. ( layerIndex + 1 ) * layerByteLength / image.data.BYTES_PER_ELEMENT
  46392. );
  46393. gl.texSubImage3D( gl.TEXTURE_2D_ARRAY, 0, 0, 0, layerIndex, image.width, image.height, 1, glFormat, glType, layerData );
  46394. }
  46395. texture.clearLayerUpdates();
  46396. } else {
  46397. gl.texSubImage3D( gl.TEXTURE_2D_ARRAY, 0, 0, 0, 0, image.width, image.height, image.depth, glFormat, glType, image.data );
  46398. }
  46399. } else if ( texture.isData3DTexture ) {
  46400. const image = options.image;
  46401. gl.texSubImage3D( gl.TEXTURE_3D, 0, 0, 0, 0, image.width, image.height, image.depth, glFormat, glType, image.data );
  46402. } else if ( texture.isVideoTexture ) {
  46403. texture.update();
  46404. gl.texImage2D( glTextureType, 0, glInternalFormat, glFormat, glType, options.image );
  46405. } else {
  46406. const mipmaps = texture.mipmaps;
  46407. if ( mipmaps.length > 0 ) {
  46408. for ( let i = 0, il = mipmaps.length; i < il; i ++ ) {
  46409. const mipmap = mipmaps[ i ];
  46410. const image = getImage( mipmap );
  46411. gl.texSubImage2D( glTextureType, i, 0, 0, mipmap.width, mipmap.height, glFormat, glType, image );
  46412. }
  46413. } else {
  46414. const image = getImage( options.image );
  46415. gl.texSubImage2D( glTextureType, 0, 0, 0, width, height, glFormat, glType, image );
  46416. }
  46417. }
  46418. }
  46419. /**
  46420. * Generates mipmaps for the given texture.
  46421. *
  46422. * @param {Texture} texture - The texture.
  46423. */
  46424. generateMipmaps( texture ) {
  46425. const { gl, backend } = this;
  46426. const { textureGPU, glTextureType } = backend.get( texture );
  46427. backend.state.bindTexture( glTextureType, textureGPU );
  46428. gl.generateMipmap( glTextureType );
  46429. }
  46430. /**
  46431. * Deallocates the render buffers of the given render target.
  46432. *
  46433. * @param {RenderTarget} renderTarget - The render target.
  46434. */
  46435. deallocateRenderBuffers( renderTarget ) {
  46436. const { gl, backend } = this;
  46437. // remove framebuffer reference
  46438. if ( renderTarget ) {
  46439. const renderContextData = backend.get( renderTarget );
  46440. renderContextData.renderBufferStorageSetup = undefined;
  46441. if ( renderContextData.framebuffers ) {
  46442. for ( const cacheKey in renderContextData.framebuffers ) {
  46443. gl.deleteFramebuffer( renderContextData.framebuffers[ cacheKey ] );
  46444. }
  46445. delete renderContextData.framebuffers;
  46446. }
  46447. if ( renderContextData.depthRenderbuffer ) {
  46448. gl.deleteRenderbuffer( renderContextData.depthRenderbuffer );
  46449. delete renderContextData.depthRenderbuffer;
  46450. }
  46451. if ( renderContextData.stencilRenderbuffer ) {
  46452. gl.deleteRenderbuffer( renderContextData.stencilRenderbuffer );
  46453. delete renderContextData.stencilRenderbuffer;
  46454. }
  46455. if ( renderContextData.msaaFrameBuffer ) {
  46456. gl.deleteFramebuffer( renderContextData.msaaFrameBuffer );
  46457. delete renderContextData.msaaFrameBuffer;
  46458. }
  46459. if ( renderContextData.msaaRenderbuffers ) {
  46460. for ( let i = 0; i < renderContextData.msaaRenderbuffers.length; i ++ ) {
  46461. gl.deleteRenderbuffer( renderContextData.msaaRenderbuffers[ i ] );
  46462. }
  46463. delete renderContextData.msaaRenderbuffers;
  46464. }
  46465. }
  46466. }
  46467. /**
  46468. * Destroys the GPU data for the given texture object.
  46469. *
  46470. * @param {Texture} texture - The texture.
  46471. * @param {boolean} [isDefaultTexture=false] - Whether the texture uses a default GPU texture or not.
  46472. */
  46473. destroyTexture( texture, isDefaultTexture = false ) {
  46474. const { gl, backend } = this;
  46475. const { textureGPU, renderTarget } = backend.get( texture );
  46476. this.deallocateRenderBuffers( renderTarget );
  46477. if ( isDefaultTexture === false ) {
  46478. gl.deleteTexture( textureGPU );
  46479. }
  46480. backend.delete( texture );
  46481. }
  46482. /**
  46483. * Copies data of the given source texture to the given destination texture.
  46484. *
  46485. * @param {Texture} srcTexture - The source texture.
  46486. * @param {Texture} dstTexture - The destination texture.
  46487. * @param {?(Box3|Box2)} [srcRegion=null] - The region of the source texture to copy.
  46488. * @param {?(Vector2|Vector3)} [dstPosition=null] - The destination position of the copy.
  46489. * @param {number} [srcLevel=0] - The source mip level to copy from.
  46490. * @param {number} [dstLevel=0] - The destination mip level to copy to.
  46491. */
  46492. copyTextureToTexture( srcTexture, dstTexture, srcRegion = null, dstPosition = null, srcLevel = 0, dstLevel = 0 ) {
  46493. const { gl, backend } = this;
  46494. const { state } = this.backend;
  46495. const { textureGPU: dstTextureGPU, glTextureType, glType, glFormat } = backend.get( dstTexture );
  46496. state.bindTexture( glTextureType, dstTextureGPU );
  46497. // gather the necessary dimensions to copy
  46498. let width, height, depth, minX, minY, minZ;
  46499. let dstX, dstY, dstZ;
  46500. const image = srcTexture.isCompressedTexture ? srcTexture.mipmaps[ dstLevel ] : srcTexture.image;
  46501. if ( srcRegion !== null ) {
  46502. width = srcRegion.max.x - srcRegion.min.x;
  46503. height = srcRegion.max.y - srcRegion.min.y;
  46504. depth = srcRegion.isBox3 ? srcRegion.max.z - srcRegion.min.z : 1;
  46505. minX = srcRegion.min.x;
  46506. minY = srcRegion.min.y;
  46507. minZ = srcRegion.isBox3 ? srcRegion.min.z : 0;
  46508. } else {
  46509. const levelScale = Math.pow( 2, - srcLevel );
  46510. width = Math.floor( image.width * levelScale );
  46511. height = Math.floor( image.height * levelScale );
  46512. if ( srcTexture.isDataArrayTexture || srcTexture.isArrayTexture ) {
  46513. depth = image.depth;
  46514. } else if ( srcTexture.isData3DTexture ) {
  46515. depth = Math.floor( image.depth * levelScale );
  46516. } else {
  46517. depth = 1;
  46518. }
  46519. minX = 0;
  46520. minY = 0;
  46521. minZ = 0;
  46522. }
  46523. if ( dstPosition !== null ) {
  46524. dstX = dstPosition.x;
  46525. dstY = dstPosition.y;
  46526. dstZ = dstPosition.z;
  46527. } else {
  46528. dstX = 0;
  46529. dstY = 0;
  46530. dstZ = 0;
  46531. }
  46532. gl.pixelStorei( gl.UNPACK_FLIP_Y_WEBGL, dstTexture.flipY );
  46533. gl.pixelStorei( gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, dstTexture.premultiplyAlpha );
  46534. gl.pixelStorei( gl.UNPACK_ALIGNMENT, dstTexture.unpackAlignment );
  46535. // used for copying data from cpu
  46536. const currentUnpackRowLen = gl.getParameter( gl.UNPACK_ROW_LENGTH );
  46537. const currentUnpackImageHeight = gl.getParameter( gl.UNPACK_IMAGE_HEIGHT );
  46538. const currentUnpackSkipPixels = gl.getParameter( gl.UNPACK_SKIP_PIXELS );
  46539. const currentUnpackSkipRows = gl.getParameter( gl.UNPACK_SKIP_ROWS );
  46540. const currentUnpackSkipImages = gl.getParameter( gl.UNPACK_SKIP_IMAGES );
  46541. gl.pixelStorei( gl.UNPACK_ROW_LENGTH, image.width );
  46542. gl.pixelStorei( gl.UNPACK_IMAGE_HEIGHT, image.height );
  46543. gl.pixelStorei( gl.UNPACK_SKIP_PIXELS, minX );
  46544. gl.pixelStorei( gl.UNPACK_SKIP_ROWS, minY );
  46545. gl.pixelStorei( gl.UNPACK_SKIP_IMAGES, minZ );
  46546. // set up the src texture
  46547. const isSrc3D = srcTexture.isDataArrayTexture || srcTexture.isData3DTexture || dstTexture.isArrayTexture;
  46548. const isDst3D = dstTexture.isDataArrayTexture || dstTexture.isData3DTexture || dstTexture.isArrayTexture;
  46549. if ( srcTexture.isDepthTexture ) {
  46550. const srcTextureData = backend.get( srcTexture );
  46551. const dstTextureData = backend.get( dstTexture );
  46552. const srcRenderContextData = backend.get( srcTextureData.renderTarget );
  46553. const dstRenderContextData = backend.get( dstTextureData.renderTarget );
  46554. const srcFramebuffer = srcRenderContextData.framebuffers[ srcTextureData.cacheKey ];
  46555. const dstFramebuffer = dstRenderContextData.framebuffers[ dstTextureData.cacheKey ];
  46556. state.bindFramebuffer( gl.READ_FRAMEBUFFER, srcFramebuffer );
  46557. state.bindFramebuffer( gl.DRAW_FRAMEBUFFER, dstFramebuffer );
  46558. for ( let i = 0; i < depth; i ++ ) {
  46559. // if the source or destination are a 3d target then a layer needs to be bound
  46560. if ( isSrc3D ) {
  46561. gl.framebufferTextureLayer( gl.READ_FRAMEBUFFER, gl.COLOR_ATTACHMENT0, srcTextureData.textureGPU, srcLevel, minZ + i );
  46562. gl.framebufferTextureLayer( gl.DRAW_FRAMEBUFFER, gl.COLOR_ATTACHMENT0, dstTextureGPU, dstLevel, dstZ + i );
  46563. }
  46564. gl.blitFramebuffer( minX, minY, width, height, dstX, dstY, width, height, gl.DEPTH_BUFFER_BIT, gl.NEAREST );
  46565. }
  46566. state.bindFramebuffer( gl.READ_FRAMEBUFFER, null );
  46567. state.bindFramebuffer( gl.DRAW_FRAMEBUFFER, null );
  46568. } else if ( srcLevel !== 0 || srcTexture.isRenderTargetTexture || backend.has( srcTexture ) ) {
  46569. // get the appropriate frame buffers
  46570. const srcTextureData = backend.get( srcTexture );
  46571. if ( this._srcFramebuffer === null ) this._srcFramebuffer = gl.createFramebuffer();
  46572. if ( this._dstFramebuffer === null ) this._dstFramebuffer = gl.createFramebuffer();
  46573. // bind the frame buffer targets
  46574. state.bindFramebuffer( gl.READ_FRAMEBUFFER, this._srcFramebuffer );
  46575. state.bindFramebuffer( gl.DRAW_FRAMEBUFFER, this._dstFramebuffer );
  46576. for ( let i = 0; i < depth; i ++ ) {
  46577. // assign the correct layers and mip maps to the frame buffers
  46578. if ( isSrc3D ) {
  46579. gl.framebufferTextureLayer( gl.READ_FRAMEBUFFER, gl.COLOR_ATTACHMENT0, srcTextureData.textureGPU, srcLevel, minZ + i );
  46580. } else {
  46581. gl.framebufferTexture2D( gl.READ_FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, srcTextureData.textureGPU, srcLevel );
  46582. }
  46583. if ( isDst3D ) {
  46584. gl.framebufferTextureLayer( gl.DRAW_FRAMEBUFFER, gl.COLOR_ATTACHMENT0, dstTextureGPU, dstLevel, dstZ + i );
  46585. } else {
  46586. gl.framebufferTexture2D( gl.DRAW_FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, dstTextureGPU, dstLevel );
  46587. }
  46588. // copy the data using the fastest function that can achieve the copy
  46589. if ( srcLevel !== 0 ) {
  46590. gl.blitFramebuffer( minX, minY, width, height, dstX, dstY, width, height, gl.COLOR_BUFFER_BIT, gl.NEAREST );
  46591. } else if ( isDst3D ) {
  46592. gl.copyTexSubImage3D( glTextureType, dstLevel, dstX, dstY, dstZ + i, minX, minY, width, height );
  46593. } else {
  46594. gl.copyTexSubImage2D( glTextureType, dstLevel, dstX, dstY, minX, minY, width, height );
  46595. }
  46596. }
  46597. // unbind read, draw buffers
  46598. state.bindFramebuffer( gl.READ_FRAMEBUFFER, null );
  46599. state.bindFramebuffer( gl.DRAW_FRAMEBUFFER, null );
  46600. } else {
  46601. if ( isDst3D ) {
  46602. // copy data into the 3d texture
  46603. if ( srcTexture.isDataTexture || srcTexture.isData3DTexture ) {
  46604. gl.texSubImage3D( glTextureType, dstLevel, dstX, dstY, dstZ, width, height, depth, glFormat, glType, image.data );
  46605. } else if ( dstTexture.isCompressedArrayTexture ) {
  46606. gl.compressedTexSubImage3D( glTextureType, dstLevel, dstX, dstY, dstZ, width, height, depth, glFormat, image.data );
  46607. } else {
  46608. gl.texSubImage3D( glTextureType, dstLevel, dstX, dstY, dstZ, width, height, depth, glFormat, glType, image );
  46609. }
  46610. } else {
  46611. // copy data into the 2d texture
  46612. if ( srcTexture.isDataTexture ) {
  46613. gl.texSubImage2D( gl.TEXTURE_2D, dstLevel, dstX, dstY, width, height, glFormat, glType, image.data );
  46614. } else if ( srcTexture.isCompressedTexture ) {
  46615. gl.compressedTexSubImage2D( gl.TEXTURE_2D, dstLevel, dstX, dstY, image.width, image.height, glFormat, image.data );
  46616. } else {
  46617. gl.texSubImage2D( gl.TEXTURE_2D, dstLevel, dstX, dstY, width, height, glFormat, glType, image );
  46618. }
  46619. }
  46620. }
  46621. // reset values
  46622. gl.pixelStorei( gl.UNPACK_ROW_LENGTH, currentUnpackRowLen );
  46623. gl.pixelStorei( gl.UNPACK_IMAGE_HEIGHT, currentUnpackImageHeight );
  46624. gl.pixelStorei( gl.UNPACK_SKIP_PIXELS, currentUnpackSkipPixels );
  46625. gl.pixelStorei( gl.UNPACK_SKIP_ROWS, currentUnpackSkipRows );
  46626. gl.pixelStorei( gl.UNPACK_SKIP_IMAGES, currentUnpackSkipImages );
  46627. // Generate mipmaps only when copying level 0
  46628. if ( dstLevel === 0 && dstTexture.generateMipmaps ) {
  46629. gl.generateMipmap( glTextureType );
  46630. }
  46631. state.unbindTexture();
  46632. }
  46633. /**
  46634. * Copies the current bound framebuffer to the given texture.
  46635. *
  46636. * @param {Texture} texture - The destination texture.
  46637. * @param {RenderContext} renderContext - The render context.
  46638. * @param {Vector4} rectangle - A four dimensional vector defining the origin and dimension of the copy.
  46639. */
  46640. copyFramebufferToTexture( texture, renderContext, rectangle ) {
  46641. const { gl } = this;
  46642. const { state } = this.backend;
  46643. const { textureGPU } = this.backend.get( texture );
  46644. const { x, y, z: width, w: height } = rectangle;
  46645. const requireDrawFrameBuffer = texture.isDepthTexture === true || ( renderContext.renderTarget && renderContext.renderTarget.samples > 0 );
  46646. const srcHeight = renderContext.renderTarget ? renderContext.renderTarget.height : this.backend.getDrawingBufferSize().y;
  46647. if ( requireDrawFrameBuffer ) {
  46648. const partial = ( x !== 0 || y !== 0 );
  46649. let mask;
  46650. let attachment;
  46651. if ( texture.isDepthTexture === true ) {
  46652. mask = gl.DEPTH_BUFFER_BIT;
  46653. attachment = gl.DEPTH_ATTACHMENT;
  46654. if ( renderContext.stencil ) {
  46655. mask |= gl.STENCIL_BUFFER_BIT;
  46656. }
  46657. } else {
  46658. mask = gl.COLOR_BUFFER_BIT;
  46659. attachment = gl.COLOR_ATTACHMENT0;
  46660. }
  46661. if ( partial ) {
  46662. const renderTargetContextData = this.backend.get( renderContext.renderTarget );
  46663. const fb = renderTargetContextData.framebuffers[ renderContext.getCacheKey() ];
  46664. const msaaFrameBuffer = renderTargetContextData.msaaFrameBuffer;
  46665. state.bindFramebuffer( gl.DRAW_FRAMEBUFFER, fb );
  46666. state.bindFramebuffer( gl.READ_FRAMEBUFFER, msaaFrameBuffer );
  46667. const flippedY = srcHeight - y - height;
  46668. gl.blitFramebuffer( x, flippedY, x + width, flippedY + height, x, flippedY, x + width, flippedY + height, mask, gl.NEAREST );
  46669. state.bindFramebuffer( gl.READ_FRAMEBUFFER, fb );
  46670. state.bindTexture( gl.TEXTURE_2D, textureGPU );
  46671. gl.copyTexSubImage2D( gl.TEXTURE_2D, 0, 0, 0, x, flippedY, width, height );
  46672. state.unbindTexture();
  46673. } else {
  46674. const fb = gl.createFramebuffer();
  46675. state.bindFramebuffer( gl.DRAW_FRAMEBUFFER, fb );
  46676. gl.framebufferTexture2D( gl.DRAW_FRAMEBUFFER, attachment, gl.TEXTURE_2D, textureGPU, 0 );
  46677. gl.blitFramebuffer( 0, 0, width, height, 0, 0, width, height, mask, gl.NEAREST );
  46678. gl.deleteFramebuffer( fb );
  46679. }
  46680. } else {
  46681. state.bindTexture( gl.TEXTURE_2D, textureGPU );
  46682. gl.copyTexSubImage2D( gl.TEXTURE_2D, 0, 0, 0, x, srcHeight - height - y, width, height );
  46683. state.unbindTexture();
  46684. }
  46685. if ( texture.generateMipmaps ) this.generateMipmaps( texture );
  46686. this.backend._setFramebuffer( renderContext );
  46687. }
  46688. /**
  46689. * SetupS storage for internal depth/stencil buffers and bind to correct framebuffer.
  46690. *
  46691. * @param {WebGLRenderbuffer} renderbuffer - The render buffer.
  46692. * @param {RenderContext} renderContext - The render context.
  46693. * @param {number} samples - The MSAA sample count.
  46694. * @param {boolean} [useMultisampledRTT=false] - Whether to use WEBGL_multisampled_render_to_texture or not.
  46695. */
  46696. setupRenderBufferStorage( renderbuffer, renderContext, samples, useMultisampledRTT = false ) {
  46697. const { gl } = this;
  46698. const renderTarget = renderContext.renderTarget;
  46699. const { depthTexture, depthBuffer, stencilBuffer, width, height } = renderTarget;
  46700. gl.bindRenderbuffer( gl.RENDERBUFFER, renderbuffer );
  46701. if ( depthBuffer && ! stencilBuffer ) {
  46702. let glInternalFormat = gl.DEPTH_COMPONENT24;
  46703. if ( useMultisampledRTT === true ) {
  46704. const multisampledRTTExt = this.extensions.get( 'WEBGL_multisampled_render_to_texture' );
  46705. multisampledRTTExt.renderbufferStorageMultisampleEXT( gl.RENDERBUFFER, renderTarget.samples, glInternalFormat, width, height );
  46706. } else if ( samples > 0 ) {
  46707. if ( depthTexture && depthTexture.isDepthTexture ) {
  46708. if ( depthTexture.type === gl.FLOAT ) {
  46709. glInternalFormat = gl.DEPTH_COMPONENT32F;
  46710. }
  46711. }
  46712. gl.renderbufferStorageMultisample( gl.RENDERBUFFER, samples, glInternalFormat, width, height );
  46713. } else {
  46714. gl.renderbufferStorage( gl.RENDERBUFFER, glInternalFormat, width, height );
  46715. }
  46716. gl.framebufferRenderbuffer( gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, renderbuffer );
  46717. } else if ( depthBuffer && stencilBuffer ) {
  46718. if ( samples > 0 ) {
  46719. gl.renderbufferStorageMultisample( gl.RENDERBUFFER, samples, gl.DEPTH24_STENCIL8, width, height );
  46720. } else {
  46721. gl.renderbufferStorage( gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height );
  46722. }
  46723. gl.framebufferRenderbuffer( gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, renderbuffer );
  46724. }
  46725. gl.bindRenderbuffer( gl.RENDERBUFFER, null );
  46726. }
  46727. /**
  46728. * Returns texture data as a typed array.
  46729. *
  46730. * @async
  46731. * @param {Texture} texture - The texture to copy.
  46732. * @param {number} x - The x coordinate of the copy origin.
  46733. * @param {number} y - The y coordinate of the copy origin.
  46734. * @param {number} width - The width of the copy.
  46735. * @param {number} height - The height of the copy.
  46736. * @param {number} faceIndex - The face index.
  46737. * @return {Promise<TypedArray>} A Promise that resolves with a typed array when the copy operation has finished.
  46738. */
  46739. async copyTextureToBuffer( texture, x, y, width, height, faceIndex ) {
  46740. const { backend, gl } = this;
  46741. const { textureGPU, glFormat, glType } = this.backend.get( texture );
  46742. const fb = gl.createFramebuffer();
  46743. gl.bindFramebuffer( gl.READ_FRAMEBUFFER, fb );
  46744. const target = texture.isCubeTexture ? gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex : gl.TEXTURE_2D;
  46745. gl.framebufferTexture2D( gl.READ_FRAMEBUFFER, gl.COLOR_ATTACHMENT0, target, textureGPU, 0 );
  46746. const typedArrayType = this._getTypedArrayType( glType );
  46747. const bytesPerTexel = this._getBytesPerTexel( glType, glFormat );
  46748. const elementCount = width * height;
  46749. const byteLength = elementCount * bytesPerTexel;
  46750. const buffer = gl.createBuffer();
  46751. gl.bindBuffer( gl.PIXEL_PACK_BUFFER, buffer );
  46752. gl.bufferData( gl.PIXEL_PACK_BUFFER, byteLength, gl.STREAM_READ );
  46753. gl.readPixels( x, y, width, height, glFormat, glType, 0 );
  46754. gl.bindBuffer( gl.PIXEL_PACK_BUFFER, null );
  46755. await backend.utils._clientWaitAsync();
  46756. const dstBuffer = new typedArrayType( byteLength / typedArrayType.BYTES_PER_ELEMENT );
  46757. gl.bindBuffer( gl.PIXEL_PACK_BUFFER, buffer );
  46758. gl.getBufferSubData( gl.PIXEL_PACK_BUFFER, 0, dstBuffer );
  46759. gl.bindBuffer( gl.PIXEL_PACK_BUFFER, null );
  46760. gl.deleteFramebuffer( fb );
  46761. return dstBuffer;
  46762. }
  46763. /**
  46764. * Returns the corresponding typed array type for the given WebGL data type.
  46765. *
  46766. * @private
  46767. * @param {GLenum} glType - The WebGL data type.
  46768. * @return {TypedArray.constructor} The typed array type.
  46769. */
  46770. _getTypedArrayType( glType ) {
  46771. const { gl } = this;
  46772. if ( glType === gl.UNSIGNED_BYTE ) return Uint8Array;
  46773. if ( glType === gl.UNSIGNED_SHORT_4_4_4_4 ) return Uint16Array;
  46774. if ( glType === gl.UNSIGNED_SHORT_5_5_5_1 ) return Uint16Array;
  46775. if ( glType === gl.UNSIGNED_SHORT_5_6_5 ) return Uint16Array;
  46776. if ( glType === gl.UNSIGNED_SHORT ) return Uint16Array;
  46777. if ( glType === gl.UNSIGNED_INT ) return Uint32Array;
  46778. if ( glType === gl.HALF_FLOAT ) return Uint16Array;
  46779. if ( glType === gl.FLOAT ) return Float32Array;
  46780. throw new Error( `Unsupported WebGL type: ${glType}` );
  46781. }
  46782. /**
  46783. * Returns the bytes-per-texel value for the given WebGL data type and texture format.
  46784. *
  46785. * @private
  46786. * @param {GLenum} glType - The WebGL data type.
  46787. * @param {GLenum} glFormat - The WebGL texture format.
  46788. * @return {number} The bytes-per-texel.
  46789. */
  46790. _getBytesPerTexel( glType, glFormat ) {
  46791. const { gl } = this;
  46792. let bytesPerComponent = 0;
  46793. if ( glType === gl.UNSIGNED_BYTE ) bytesPerComponent = 1;
  46794. if ( glType === gl.UNSIGNED_SHORT_4_4_4_4 ||
  46795. glType === gl.UNSIGNED_SHORT_5_5_5_1 ||
  46796. glType === gl.UNSIGNED_SHORT_5_6_5 ||
  46797. glType === gl.UNSIGNED_SHORT ||
  46798. glType === gl.HALF_FLOAT ) bytesPerComponent = 2;
  46799. if ( glType === gl.UNSIGNED_INT ||
  46800. glType === gl.FLOAT ) bytesPerComponent = 4;
  46801. if ( glFormat === gl.RGBA ) return bytesPerComponent * 4;
  46802. if ( glFormat === gl.RGB ) return bytesPerComponent * 3;
  46803. if ( glFormat === gl.ALPHA ) return bytesPerComponent;
  46804. }
  46805. /**
  46806. * Frees the internal resources.
  46807. */
  46808. dispose() {
  46809. const { gl } = this;
  46810. if ( this._srcFramebuffer !== null ) gl.deleteFramebuffer( this._srcFramebuffer );
  46811. if ( this._dstFramebuffer !== null ) gl.deleteFramebuffer( this._dstFramebuffer );
  46812. }
  46813. }
  46814. function getImage( source ) {
  46815. if ( source.isDataTexture ) {
  46816. return source.image.data;
  46817. } else if ( ( typeof HTMLImageElement !== 'undefined' && source instanceof HTMLImageElement ) ||
  46818. ( typeof HTMLCanvasElement !== 'undefined' && source instanceof HTMLCanvasElement ) ||
  46819. ( typeof ImageBitmap !== 'undefined' && source instanceof ImageBitmap ) ||
  46820. ( typeof OffscreenCanvas !== 'undefined' && source instanceof OffscreenCanvas ) ) {
  46821. return source;
  46822. }
  46823. return source.data;
  46824. }
  46825. /**
  46826. * A WebGL 2 backend utility module for managing extensions.
  46827. *
  46828. * @private
  46829. */
  46830. class WebGLExtensions {
  46831. /**
  46832. * Constructs a new utility object.
  46833. *
  46834. * @param {WebGLBackend} backend - The WebGL 2 backend.
  46835. */
  46836. constructor( backend ) {
  46837. /**
  46838. * A reference to the WebGL 2 backend.
  46839. *
  46840. * @type {WebGLBackend}
  46841. */
  46842. this.backend = backend;
  46843. /**
  46844. * A reference to the rendering context.
  46845. *
  46846. * @type {WebGL2RenderingContext}
  46847. */
  46848. this.gl = this.backend.gl;
  46849. /**
  46850. * A list with all the supported WebGL extensions.
  46851. *
  46852. * @type {Array<string>}
  46853. */
  46854. this.availableExtensions = this.gl.getSupportedExtensions();
  46855. /**
  46856. * A dictionary with requested WebGL extensions.
  46857. * The key is the name of the extension, the value
  46858. * the requested extension object.
  46859. *
  46860. * @type {Object<string,Object>}
  46861. */
  46862. this.extensions = {};
  46863. }
  46864. /**
  46865. * Returns the extension object for the given extension name.
  46866. *
  46867. * @param {string} name - The extension name.
  46868. * @return {Object} The extension object.
  46869. */
  46870. get( name ) {
  46871. let extension = this.extensions[ name ];
  46872. if ( extension === undefined ) {
  46873. extension = this.gl.getExtension( name );
  46874. this.extensions[ name ] = extension;
  46875. }
  46876. return extension;
  46877. }
  46878. /**
  46879. * Returns `true` if the requested extension is available.
  46880. *
  46881. * @param {string} name - The extension name.
  46882. * @return {boolean} Whether the given extension is available or not.
  46883. */
  46884. has( name ) {
  46885. return this.availableExtensions.includes( name );
  46886. }
  46887. }
  46888. /**
  46889. * A WebGL 2 backend utility module for managing the device's capabilities.
  46890. *
  46891. * @private
  46892. */
  46893. class WebGLCapabilities {
  46894. /**
  46895. * Constructs a new utility object.
  46896. *
  46897. * @param {WebGLBackend} backend - The WebGL 2 backend.
  46898. */
  46899. constructor( backend ) {
  46900. /**
  46901. * A reference to the WebGL 2 backend.
  46902. *
  46903. * @type {WebGLBackend}
  46904. */
  46905. this.backend = backend;
  46906. /**
  46907. * This value holds the cached max anisotropy value.
  46908. *
  46909. * @type {?number}
  46910. * @default null
  46911. */
  46912. this.maxAnisotropy = null;
  46913. }
  46914. /**
  46915. * Returns the maximum anisotropy texture filtering value. This value
  46916. * depends on the device and is reported by the `EXT_texture_filter_anisotropic`
  46917. * WebGL extension.
  46918. *
  46919. * @return {number} The maximum anisotropy texture filtering value.
  46920. */
  46921. getMaxAnisotropy() {
  46922. if ( this.maxAnisotropy !== null ) return this.maxAnisotropy;
  46923. const gl = this.backend.gl;
  46924. const extensions = this.backend.extensions;
  46925. if ( extensions.has( 'EXT_texture_filter_anisotropic' ) === true ) {
  46926. const extension = extensions.get( 'EXT_texture_filter_anisotropic' );
  46927. this.maxAnisotropy = gl.getParameter( extension.MAX_TEXTURE_MAX_ANISOTROPY_EXT );
  46928. } else {
  46929. this.maxAnisotropy = 0;
  46930. }
  46931. return this.maxAnisotropy;
  46932. }
  46933. }
  46934. const GLFeatureName = {
  46935. 'WEBGL_multi_draw': 'WEBGL_multi_draw',
  46936. 'WEBGL_compressed_texture_astc': 'texture-compression-astc',
  46937. 'WEBGL_compressed_texture_etc': 'texture-compression-etc2',
  46938. 'WEBGL_compressed_texture_etc1': 'texture-compression-etc1',
  46939. 'WEBGL_compressed_texture_pvrtc': 'texture-compression-pvrtc',
  46940. 'WEBGL_compressed_texture_s3tc': 'texture-compression-s3tc',
  46941. 'EXT_texture_compression_bptc': 'texture-compression-bc',
  46942. 'EXT_disjoint_timer_query_webgl2': 'timestamp-query',
  46943. 'OVR_multiview2': 'OVR_multiview2'
  46944. };
  46945. class WebGLBufferRenderer {
  46946. constructor( backend ) {
  46947. this.gl = backend.gl;
  46948. this.extensions = backend.extensions;
  46949. this.info = backend.renderer.info;
  46950. this.mode = null;
  46951. this.index = 0;
  46952. this.type = null;
  46953. this.object = null;
  46954. }
  46955. render( start, count ) {
  46956. const { gl, mode, object, type, info, index } = this;
  46957. if ( index !== 0 ) {
  46958. gl.drawElements( mode, count, type, start );
  46959. } else {
  46960. gl.drawArrays( mode, start, count );
  46961. }
  46962. info.update( object, count, 1 );
  46963. }
  46964. renderInstances( start, count, primcount ) {
  46965. const { gl, mode, type, index, object, info } = this;
  46966. if ( primcount === 0 ) return;
  46967. if ( index !== 0 ) {
  46968. gl.drawElementsInstanced( mode, count, type, start, primcount );
  46969. } else {
  46970. gl.drawArraysInstanced( mode, start, count, primcount );
  46971. }
  46972. info.update( object, count, primcount );
  46973. }
  46974. renderMultiDraw( starts, counts, drawCount ) {
  46975. const { extensions, mode, object, info } = this;
  46976. if ( drawCount === 0 ) return;
  46977. const extension = extensions.get( 'WEBGL_multi_draw' );
  46978. if ( extension === null ) {
  46979. for ( let i = 0; i < drawCount; i ++ ) {
  46980. this.render( starts[ i ], counts[ i ] );
  46981. }
  46982. } else {
  46983. if ( this.index !== 0 ) {
  46984. extension.multiDrawElementsWEBGL( mode, counts, 0, this.type, starts, 0, drawCount );
  46985. } else {
  46986. extension.multiDrawArraysWEBGL( mode, starts, 0, counts, 0, drawCount );
  46987. }
  46988. let elementCount = 0;
  46989. for ( let i = 0; i < drawCount; i ++ ) {
  46990. elementCount += counts[ i ];
  46991. }
  46992. info.update( object, elementCount, 1 );
  46993. }
  46994. }
  46995. renderMultiDrawInstances( starts, counts, drawCount, primcount ) {
  46996. const { extensions, mode, object, info } = this;
  46997. if ( drawCount === 0 ) return;
  46998. const extension = extensions.get( 'WEBGL_multi_draw' );
  46999. if ( extension === null ) {
  47000. for ( let i = 0; i < drawCount; i ++ ) {
  47001. this.renderInstances( starts[ i ], counts[ i ], primcount[ i ] );
  47002. }
  47003. } else {
  47004. if ( this.index !== 0 ) {
  47005. extension.multiDrawElementsInstancedWEBGL( mode, counts, 0, this.type, starts, 0, primcount, 0, drawCount );
  47006. } else {
  47007. extension.multiDrawArraysInstancedWEBGL( mode, starts, 0, counts, 0, primcount, 0, drawCount );
  47008. }
  47009. let elementCount = 0;
  47010. for ( let i = 0; i < drawCount; i ++ ) {
  47011. elementCount += counts[ i ] * primcount[ i ];
  47012. }
  47013. info.update( object, elementCount, 1 );
  47014. }
  47015. }
  47016. //
  47017. }
  47018. /**
  47019. * Abstract base class of a timestamp query pool.
  47020. *
  47021. * @abstract
  47022. */
  47023. class TimestampQueryPool {
  47024. /**
  47025. * Creates a new timestamp query pool.
  47026. *
  47027. * @param {number} [maxQueries=256] - Maximum number of queries this pool can hold.
  47028. */
  47029. constructor( maxQueries = 256 ) {
  47030. /**
  47031. * Whether to track timestamps or not.
  47032. *
  47033. * @type {boolean}
  47034. * @default true
  47035. */
  47036. this.trackTimestamp = true;
  47037. /**
  47038. * Maximum number of queries this pool can hold.
  47039. *
  47040. * @type {number}
  47041. * @default 256
  47042. */
  47043. this.maxQueries = maxQueries;
  47044. /**
  47045. * How many queries allocated so far.
  47046. *
  47047. * @type {number}
  47048. * @default 0
  47049. */
  47050. this.currentQueryIndex = 0;
  47051. /**
  47052. * Tracks offsets for different contexts.
  47053. *
  47054. * @type {Map<string, number>}
  47055. */
  47056. this.queryOffsets = new Map();
  47057. /**
  47058. * Whether the pool has been disposed or not.
  47059. *
  47060. * @type {boolean}
  47061. * @default false
  47062. */
  47063. this.isDisposed = false;
  47064. /**
  47065. * TODO
  47066. *
  47067. * @type {number}
  47068. * @default 0
  47069. */
  47070. this.lastValue = 0;
  47071. /**
  47072. * Stores all timestamp frames.
  47073. *
  47074. * @type {Array<number>}
  47075. */
  47076. this.frames = [];
  47077. /**
  47078. * TODO
  47079. *
  47080. * @type {boolean}
  47081. * @default false
  47082. */
  47083. this.pendingResolve = false;
  47084. /**
  47085. * Stores the latest timestamp for each render context.
  47086. *
  47087. * @type {Map<string, number>}
  47088. */
  47089. this.timestamps = new Map();
  47090. }
  47091. /**
  47092. * Returns all timestamp frames.
  47093. *
  47094. * @return {Array<number>} The timestamp frames.
  47095. */
  47096. getTimestampFrames() {
  47097. return this.frames;
  47098. }
  47099. /**
  47100. * Returns the timestamp for a given render context.
  47101. *
  47102. * @param {string} uid - A unique identifier for the render context.
  47103. * @return {?number} The timestamp, or undefined if not available.
  47104. */
  47105. getTimestamp( uid ) {
  47106. let timestamp = this.timestamps.get( uid );
  47107. if ( timestamp === undefined ) {
  47108. warn( `TimestampQueryPool: No timestamp available for uid ${ uid }.` );
  47109. timestamp = 0;
  47110. }
  47111. return timestamp;
  47112. }
  47113. /**
  47114. * Returns whether a timestamp is available for a given render context.
  47115. *
  47116. * @param {string} uid - A unique identifier for the render context.
  47117. * @return {boolean} True if a timestamp is available, false otherwise.
  47118. */
  47119. hasTimestamp( uid ) {
  47120. return this.timestamps.has( uid );
  47121. }
  47122. /**
  47123. * Allocate queries for a specific uid.
  47124. *
  47125. * @abstract
  47126. * @param {string} uid - A unique identifier for the render context.
  47127. * @param {number} frameId - The current frame identifier.
  47128. * @returns {?number}
  47129. */
  47130. allocateQueriesForContext( /* uid, frameId */ ) {}
  47131. /**
  47132. * Resolve all timestamps and return data (or process them).
  47133. *
  47134. * @abstract
  47135. * @async
  47136. * @returns {Promise<number>|number} The resolved timestamp value.
  47137. */
  47138. async resolveQueriesAsync() {}
  47139. /**
  47140. * Dispose of the query pool.
  47141. *
  47142. * @abstract
  47143. */
  47144. dispose() {}
  47145. }
  47146. /**
  47147. * Manages a pool of WebGL timestamp queries for performance measurement.
  47148. * Handles creation, execution, and resolution of timer queries using WebGL extensions.
  47149. *
  47150. * @augments TimestampQueryPool
  47151. */
  47152. class WebGLTimestampQueryPool extends TimestampQueryPool {
  47153. /**
  47154. * Creates a new WebGL timestamp query pool.
  47155. *
  47156. * @param {WebGLRenderingContext|WebGL2RenderingContext} gl - The WebGL context.
  47157. * @param {string} type - The type identifier for this query pool.
  47158. * @param {number} [maxQueries=2048] - Maximum number of queries this pool can hold.
  47159. */
  47160. constructor( gl, type, maxQueries = 2048 ) {
  47161. super( maxQueries );
  47162. this.gl = gl;
  47163. this.type = type;
  47164. // Check for timer query extensions
  47165. this.ext = gl.getExtension( 'EXT_disjoint_timer_query_webgl2' ) ||
  47166. gl.getExtension( 'EXT_disjoint_timer_query' );
  47167. if ( ! this.ext ) {
  47168. warn( 'EXT_disjoint_timer_query not supported; timestamps will be disabled.' );
  47169. this.trackTimestamp = false;
  47170. return;
  47171. }
  47172. // Create query objects
  47173. this.queries = [];
  47174. for ( let i = 0; i < this.maxQueries; i ++ ) {
  47175. this.queries.push( gl.createQuery() );
  47176. }
  47177. this.activeQuery = null;
  47178. this.queryStates = new Map(); // Track state of each query: 'inactive', 'started', 'ended'
  47179. }
  47180. /**
  47181. * Allocates a pair of queries for a given render context.
  47182. *
  47183. * @param {string} uid - A unique identifier for the render context.
  47184. * @returns {?number} The base offset for the allocated queries, or null if allocation failed.
  47185. */
  47186. allocateQueriesForContext( uid ) {
  47187. if ( ! this.trackTimestamp ) return null;
  47188. // Check if we have enough space for a new query pair
  47189. if ( this.currentQueryIndex + 2 > this.maxQueries ) {
  47190. warnOnce( `WebGPUTimestampQueryPool [${ this.type }]: Maximum number of queries exceeded, when using trackTimestamp it is necessary to resolves the queries via renderer.resolveTimestampsAsync( THREE.TimestampQuery.${ this.type.toUpperCase() } ).` );
  47191. return null;
  47192. }
  47193. const baseOffset = this.currentQueryIndex;
  47194. this.currentQueryIndex += 2;
  47195. // Initialize query states
  47196. this.queryStates.set( baseOffset, 'inactive' );
  47197. this.queryOffsets.set( uid, baseOffset );
  47198. return baseOffset;
  47199. }
  47200. /**
  47201. * Begins a timestamp query for the specified render context.
  47202. *
  47203. * @param {string} uid - A unique identifier for the render context.
  47204. */
  47205. beginQuery( uid ) {
  47206. if ( ! this.trackTimestamp || this.isDisposed ) {
  47207. return;
  47208. }
  47209. const baseOffset = this.queryOffsets.get( uid );
  47210. if ( baseOffset == null ) {
  47211. return;
  47212. }
  47213. // Don't start a new query if there's an active one
  47214. if ( this.activeQuery !== null ) {
  47215. return;
  47216. }
  47217. const query = this.queries[ baseOffset ];
  47218. if ( ! query ) {
  47219. return;
  47220. }
  47221. try {
  47222. // Only begin if query is inactive
  47223. if ( this.queryStates.get( baseOffset ) === 'inactive' ) {
  47224. this.gl.beginQuery( this.ext.TIME_ELAPSED_EXT, query );
  47225. this.activeQuery = baseOffset;
  47226. this.queryStates.set( baseOffset, 'started' );
  47227. }
  47228. } catch ( error ) {
  47229. error( 'Error in beginQuery:', error );
  47230. this.activeQuery = null;
  47231. this.queryStates.set( baseOffset, 'inactive' );
  47232. }
  47233. }
  47234. /**
  47235. * Ends the active timestamp query for the specified render context.
  47236. *
  47237. * @param {string} uid - A unique identifier for the render context.
  47238. */
  47239. endQuery( uid ) {
  47240. if ( ! this.trackTimestamp || this.isDisposed ) {
  47241. return;
  47242. }
  47243. const baseOffset = this.queryOffsets.get( uid );
  47244. if ( baseOffset == null ) {
  47245. return;
  47246. }
  47247. // Only end if this is the active query
  47248. if ( this.activeQuery !== baseOffset ) {
  47249. return;
  47250. }
  47251. try {
  47252. this.gl.endQuery( this.ext.TIME_ELAPSED_EXT );
  47253. this.queryStates.set( baseOffset, 'ended' );
  47254. this.activeQuery = null;
  47255. } catch ( error ) {
  47256. error( 'Error in endQuery:', error );
  47257. // Reset state on error
  47258. this.queryStates.set( baseOffset, 'inactive' );
  47259. this.activeQuery = null;
  47260. }
  47261. }
  47262. /**
  47263. * Asynchronously resolves all completed queries and returns the total duration.
  47264. *
  47265. * @async
  47266. * @returns {Promise<number>} The total duration in milliseconds, or the last valid value if resolution fails.
  47267. */
  47268. async resolveQueriesAsync() {
  47269. if ( ! this.trackTimestamp || this.pendingResolve ) {
  47270. return this.lastValue;
  47271. }
  47272. this.pendingResolve = true;
  47273. try {
  47274. // Wait for all ended queries to complete
  47275. const resolvePromises = new Map();
  47276. for ( const [ uid, baseOffset ] of this.queryOffsets ) {
  47277. const state = this.queryStates.get( baseOffset );
  47278. if ( state === 'ended' ) {
  47279. const query = this.queries[ baseOffset ];
  47280. resolvePromises.set( uid, this.resolveQuery( query ) );
  47281. }
  47282. }
  47283. if ( resolvePromises.size === 0 ) {
  47284. return this.lastValue;
  47285. }
  47286. //
  47287. const framesDuration = {};
  47288. const frames = [];
  47289. for ( const [ uid, promise ] of resolvePromises ) {
  47290. const match = uid.match( /^(.*):f(\d+)$/ );
  47291. const frame = parseInt( match[ 2 ] );
  47292. if ( frames.includes( frame ) === false ) {
  47293. frames.push( frame );
  47294. }
  47295. if ( framesDuration[ frame ] === undefined ) framesDuration[ frame ] = 0;
  47296. const duration = await promise;
  47297. this.timestamps.set( uid, duration );
  47298. framesDuration[ frame ] += duration;
  47299. }
  47300. // Return the total duration of the last frame
  47301. const totalDuration = framesDuration[ frames[ frames.length - 1 ] ];
  47302. // Store the last valid result
  47303. this.lastValue = totalDuration;
  47304. this.frames = frames;
  47305. // Reset states
  47306. this.currentQueryIndex = 0;
  47307. this.queryOffsets.clear();
  47308. this.queryStates.clear();
  47309. this.activeQuery = null;
  47310. return totalDuration;
  47311. } catch ( error ) {
  47312. error( 'Error resolving queries:', error );
  47313. return this.lastValue;
  47314. } finally {
  47315. this.pendingResolve = false;
  47316. }
  47317. }
  47318. /**
  47319. * Resolves a single query, checking for completion and disjoint operation.
  47320. *
  47321. * @async
  47322. * @param {WebGLQuery} query - The query object to resolve.
  47323. * @returns {Promise<number>} The elapsed time in milliseconds.
  47324. */
  47325. async resolveQuery( query ) {
  47326. return new Promise( ( resolve ) => {
  47327. if ( this.isDisposed ) {
  47328. resolve( this.lastValue );
  47329. return;
  47330. }
  47331. let timeoutId;
  47332. let isResolved = false;
  47333. const cleanup = () => {
  47334. if ( timeoutId ) {
  47335. clearTimeout( timeoutId );
  47336. timeoutId = null;
  47337. }
  47338. };
  47339. const finalizeResolution = ( value ) => {
  47340. if ( ! isResolved ) {
  47341. isResolved = true;
  47342. cleanup();
  47343. resolve( value );
  47344. }
  47345. };
  47346. const checkQuery = () => {
  47347. if ( this.isDisposed ) {
  47348. finalizeResolution( this.lastValue );
  47349. return;
  47350. }
  47351. try {
  47352. // Check if the GPU timer was disjoint (i.e., timing was unreliable)
  47353. const disjoint = this.gl.getParameter( this.ext.GPU_DISJOINT_EXT );
  47354. if ( disjoint ) {
  47355. finalizeResolution( this.lastValue );
  47356. return;
  47357. }
  47358. const available = this.gl.getQueryParameter( query, this.gl.QUERY_RESULT_AVAILABLE );
  47359. if ( ! available ) {
  47360. timeoutId = setTimeout( checkQuery, 1 );
  47361. return;
  47362. }
  47363. const elapsed = this.gl.getQueryParameter( query, this.gl.QUERY_RESULT );
  47364. resolve( Number( elapsed ) / 1e6 ); // Convert nanoseconds to milliseconds
  47365. } catch ( error ) {
  47366. error( 'Error checking query:', error );
  47367. resolve( this.lastValue );
  47368. }
  47369. };
  47370. checkQuery();
  47371. } );
  47372. }
  47373. /**
  47374. * Releases all resources held by this query pool.
  47375. * This includes deleting all query objects and clearing internal state.
  47376. */
  47377. dispose() {
  47378. if ( this.isDisposed ) {
  47379. return;
  47380. }
  47381. this.isDisposed = true;
  47382. if ( ! this.trackTimestamp ) return;
  47383. for ( const query of this.queries ) {
  47384. this.gl.deleteQuery( query );
  47385. }
  47386. this.queries = [];
  47387. this.queryStates.clear();
  47388. this.queryOffsets.clear();
  47389. this.lastValue = 0;
  47390. this.activeQuery = null;
  47391. }
  47392. }
  47393. /**
  47394. * A backend implementation targeting WebGL 2.
  47395. *
  47396. * @private
  47397. * @augments Backend
  47398. */
  47399. class WebGLBackend extends Backend {
  47400. /**
  47401. * WebGLBackend options.
  47402. *
  47403. * @typedef {Object} WebGLBackend~Options
  47404. * @property {boolean} [logarithmicDepthBuffer=false] - Whether logarithmic depth buffer is enabled or not.
  47405. * @property {boolean} [alpha=true] - Whether the default framebuffer (which represents the final contents of the canvas) should be transparent or opaque.
  47406. * @property {boolean} [depth=true] - Whether the default framebuffer should have a depth buffer or not.
  47407. * @property {boolean} [stencil=false] - Whether the default framebuffer should have a stencil buffer or not.
  47408. * @property {boolean} [antialias=false] - Whether MSAA as the default anti-aliasing should be enabled or not.
  47409. * @property {number} [samples=0] - When `antialias` is `true`, `4` samples are used by default. Set this parameter to any other integer value than 0 to overwrite the default.
  47410. * @property {boolean} [forceWebGL=false] - If set to `true`, the renderer uses a WebGL 2 backend no matter if WebGPU is supported or not.
  47411. * @property {WebGL2RenderingContext} [context=undefined] - A WebGL 2 rendering context.
  47412. */
  47413. /**
  47414. * Constructs a new WebGPU backend.
  47415. *
  47416. * @param {WebGLBackend~Options} [parameters] - The configuration parameter.
  47417. */
  47418. constructor( parameters = {} ) {
  47419. super( parameters );
  47420. /**
  47421. * This flag can be used for type testing.
  47422. *
  47423. * @type {boolean}
  47424. * @readonly
  47425. * @default true
  47426. */
  47427. this.isWebGLBackend = true;
  47428. /**
  47429. * A reference to a backend module holding shader attribute-related
  47430. * utility functions.
  47431. *
  47432. * @type {?WebGLAttributeUtils}
  47433. * @default null
  47434. */
  47435. this.attributeUtils = null;
  47436. /**
  47437. * A reference to a backend module holding extension-related
  47438. * utility functions.
  47439. *
  47440. * @type {?WebGLExtensions}
  47441. * @default null
  47442. */
  47443. this.extensions = null;
  47444. /**
  47445. * A reference to a backend module holding capability-related
  47446. * utility functions.
  47447. *
  47448. * @type {?WebGLCapabilities}
  47449. * @default null
  47450. */
  47451. this.capabilities = null;
  47452. /**
  47453. * A reference to a backend module holding texture-related
  47454. * utility functions.
  47455. *
  47456. * @type {?WebGLTextureUtils}
  47457. * @default null
  47458. */
  47459. this.textureUtils = null;
  47460. /**
  47461. * A reference to a backend module holding renderer-related
  47462. * utility functions.
  47463. *
  47464. * @type {?WebGLBufferRenderer}
  47465. * @default null
  47466. */
  47467. this.bufferRenderer = null;
  47468. /**
  47469. * A reference to the rendering context.
  47470. *
  47471. * @type {?WebGL2RenderingContext}
  47472. * @default null
  47473. */
  47474. this.gl = null;
  47475. /**
  47476. * A reference to a backend module holding state-related
  47477. * utility functions.
  47478. *
  47479. * @type {?WebGLState}
  47480. * @default null
  47481. */
  47482. this.state = null;
  47483. /**
  47484. * A reference to a backend module holding common
  47485. * utility functions.
  47486. *
  47487. * @type {?WebGLUtils}
  47488. * @default null
  47489. */
  47490. this.utils = null;
  47491. /**
  47492. * Dictionary for caching VAOs.
  47493. *
  47494. * @type {Object<string,WebGLVertexArrayObject>}
  47495. */
  47496. this.vaoCache = {};
  47497. /**
  47498. * Dictionary for caching transform feedback objects.
  47499. *
  47500. * @type {Object<string,WebGLTransformFeedback>}
  47501. */
  47502. this.transformFeedbackCache = {};
  47503. /**
  47504. * Controls if `gl.RASTERIZER_DISCARD` should be enabled or not.
  47505. * Only relevant when using compute shaders.
  47506. *
  47507. * @type {boolean}
  47508. * @default false
  47509. */
  47510. this.discard = false;
  47511. /**
  47512. * A reference to the `EXT_disjoint_timer_query_webgl2` extension. `null` if the
  47513. * device does not support the extension.
  47514. *
  47515. * @type {?EXTDisjointTimerQueryWebGL2}
  47516. * @default null
  47517. */
  47518. this.disjoint = null;
  47519. /**
  47520. * A reference to the `KHR_parallel_shader_compile` extension. `null` if the
  47521. * device does not support the extension.
  47522. *
  47523. * @type {?KHRParallelShaderCompile}
  47524. * @default null
  47525. */
  47526. this.parallel = null;
  47527. /**
  47528. * A reference to the current render context.
  47529. *
  47530. * @private
  47531. * @type {RenderContext}
  47532. * @default null
  47533. */
  47534. this._currentContext = null;
  47535. /**
  47536. * A unique collection of bindings.
  47537. *
  47538. * @private
  47539. * @type {WeakSet<Array<BindGroup>>}
  47540. */
  47541. this._knownBindings = new WeakSet();
  47542. /**
  47543. * Whether the device supports framebuffers invalidation or not.
  47544. *
  47545. * @private
  47546. * @type {boolean}
  47547. */
  47548. this._supportsInvalidateFramebuffer = typeof navigator === 'undefined' ? false : /OculusBrowser/g.test( navigator.userAgent );
  47549. /**
  47550. * The target framebuffer when rendering with
  47551. * the WebXR device API.
  47552. *
  47553. * @private
  47554. * @type {?WebGLFramebuffer}
  47555. * @default null
  47556. */
  47557. this._xrFramebuffer = null;
  47558. }
  47559. /**
  47560. * Initializes the backend so it is ready for usage.
  47561. *
  47562. * @param {Renderer} renderer - The renderer.
  47563. */
  47564. init( renderer ) {
  47565. super.init( renderer );
  47566. //
  47567. const parameters = this.parameters;
  47568. const contextAttributes = {
  47569. antialias: renderer.currentSamples > 0,
  47570. alpha: true, // always true for performance reasons
  47571. depth: renderer.depth,
  47572. stencil: renderer.stencil
  47573. };
  47574. const glContext = ( parameters.context !== undefined ) ? parameters.context : renderer.domElement.getContext( 'webgl2', contextAttributes );
  47575. function onContextLost( event ) {
  47576. event.preventDefault();
  47577. const contextLossInfo = {
  47578. api: 'WebGL',
  47579. message: event.statusMessage || 'Unknown reason',
  47580. reason: null,
  47581. originalEvent: event
  47582. };
  47583. renderer.onDeviceLost( contextLossInfo );
  47584. }
  47585. this._onContextLost = onContextLost;
  47586. renderer.domElement.addEventListener( 'webglcontextlost', onContextLost, false );
  47587. this.gl = glContext;
  47588. this.extensions = new WebGLExtensions( this );
  47589. this.capabilities = new WebGLCapabilities( this );
  47590. this.attributeUtils = new WebGLAttributeUtils( this );
  47591. this.textureUtils = new WebGLTextureUtils( this );
  47592. this.bufferRenderer = new WebGLBufferRenderer( this );
  47593. this.state = new WebGLState( this );
  47594. this.utils = new WebGLUtils( this );
  47595. this.extensions.get( 'EXT_color_buffer_float' );
  47596. this.extensions.get( 'WEBGL_clip_cull_distance' );
  47597. this.extensions.get( 'OES_texture_float_linear' );
  47598. this.extensions.get( 'EXT_color_buffer_half_float' );
  47599. this.extensions.get( 'WEBGL_multisampled_render_to_texture' );
  47600. this.extensions.get( 'WEBGL_render_shared_exponent' );
  47601. this.extensions.get( 'WEBGL_multi_draw' );
  47602. this.extensions.get( 'OVR_multiview2' );
  47603. this.disjoint = this.extensions.get( 'EXT_disjoint_timer_query_webgl2' );
  47604. this.parallel = this.extensions.get( 'KHR_parallel_shader_compile' );
  47605. }
  47606. /**
  47607. * The coordinate system of the backend.
  47608. *
  47609. * @type {number}
  47610. * @readonly
  47611. */
  47612. get coordinateSystem() {
  47613. return WebGLCoordinateSystem;
  47614. }
  47615. /**
  47616. * This method performs a readback operation by moving buffer data from
  47617. * a storage buffer attribute from the GPU to the CPU.
  47618. *
  47619. * @async
  47620. * @param {StorageBufferAttribute} attribute - The storage buffer attribute.
  47621. * @return {Promise<ArrayBuffer>} A promise that resolves with the buffer data when the data are ready.
  47622. */
  47623. async getArrayBufferAsync( attribute ) {
  47624. return await this.attributeUtils.getArrayBufferAsync( attribute );
  47625. }
  47626. /**
  47627. * Ensures the backend is XR compatible.
  47628. *
  47629. * @async
  47630. * @return {Promise} A Promise that resolve when the renderer is XR compatible.
  47631. */
  47632. async makeXRCompatible() {
  47633. const attributes = this.gl.getContextAttributes();
  47634. if ( attributes.xrCompatible !== true ) {
  47635. await this.gl.makeXRCompatible();
  47636. }
  47637. }
  47638. /**
  47639. * Sets the XR rendering destination.
  47640. *
  47641. * @param {WebGLFramebuffer} xrFramebuffer - The XR framebuffer.
  47642. */
  47643. setXRTarget( xrFramebuffer ) {
  47644. this._xrFramebuffer = xrFramebuffer;
  47645. }
  47646. /**
  47647. * Configures the given XR render target with external textures.
  47648. *
  47649. * This method is only relevant when using the WebXR Layers API.
  47650. *
  47651. * @param {XRRenderTarget} renderTarget - The XR render target.
  47652. * @param {WebGLTexture} colorTexture - A native color texture.
  47653. * @param {?WebGLTexture} [depthTexture=null] - A native depth texture.
  47654. */
  47655. setXRRenderTargetTextures( renderTarget, colorTexture, depthTexture = null ) {
  47656. const gl = this.gl;
  47657. this.set( renderTarget.texture, { textureGPU: colorTexture, glInternalFormat: gl.RGBA8 } ); // see #24698 why RGBA8 and not SRGB8_ALPHA8 is used
  47658. if ( depthTexture !== null ) {
  47659. const glInternalFormat = renderTarget.stencilBuffer ? gl.DEPTH24_STENCIL8 : gl.DEPTH_COMPONENT24;
  47660. this.set( renderTarget.depthTexture, { textureGPU: depthTexture, glInternalFormat: glInternalFormat } );
  47661. // The multisample_render_to_texture extension doesn't work properly if there
  47662. // are midframe flushes and an external depth texture.
  47663. if ( ( this.extensions.has( 'WEBGL_multisampled_render_to_texture' ) === true ) && renderTarget._autoAllocateDepthBuffer === true && renderTarget.multiview === false ) {
  47664. warn( 'WebGLBackend: Render-to-texture extension was disabled because an external texture was provided' );
  47665. }
  47666. renderTarget._autoAllocateDepthBuffer = false;
  47667. }
  47668. }
  47669. /**
  47670. * Inits a time stamp query for the given render context.
  47671. *
  47672. * @param {string} type - The type of the timestamp query.
  47673. * @param {string} uid - A unique identifier for the timestamp query.
  47674. */
  47675. initTimestampQuery( type, uid ) {
  47676. if ( ! this.disjoint || ! this.trackTimestamp ) return;
  47677. if ( ! this.timestampQueryPool[ type ] ) {
  47678. // TODO: Variable maxQueries?
  47679. this.timestampQueryPool[ type ] = new WebGLTimestampQueryPool( this.gl, type, 2048 );
  47680. }
  47681. const timestampQueryPool = this.timestampQueryPool[ type ];
  47682. const baseOffset = timestampQueryPool.allocateQueriesForContext( uid );
  47683. if ( baseOffset !== null ) {
  47684. timestampQueryPool.beginQuery( uid );
  47685. }
  47686. }
  47687. // timestamp utils
  47688. /**
  47689. * Prepares the timestamp buffer.
  47690. *
  47691. * @param {string} type - The type of the timestamp query.
  47692. * @param {string} uid - A unique identifier for the timestamp query.
  47693. */
  47694. prepareTimestampBuffer( type, uid ) {
  47695. if ( ! this.disjoint || ! this.trackTimestamp ) return;
  47696. const timestampQueryPool = this.timestampQueryPool[ type ];
  47697. timestampQueryPool.endQuery( uid );
  47698. }
  47699. /**
  47700. * Returns the backend's rendering context.
  47701. *
  47702. * @return {WebGL2RenderingContext} The rendering context.
  47703. */
  47704. getContext() {
  47705. return this.gl;
  47706. }
  47707. /**
  47708. * This method is executed at the beginning of a render call and prepares
  47709. * the WebGL state for upcoming render calls
  47710. *
  47711. * @param {RenderContext} renderContext - The render context.
  47712. */
  47713. beginRender( renderContext ) {
  47714. const { state } = this;
  47715. const renderContextData = this.get( renderContext );
  47716. //
  47717. if ( renderContext.viewport ) {
  47718. this.updateViewport( renderContext );
  47719. } else {
  47720. const { width, height } = this.getDrawingBufferSize();
  47721. state.viewport( 0, 0, width, height );
  47722. }
  47723. if ( renderContext.scissor ) {
  47724. const { x, y, width, height } = renderContext.scissorValue;
  47725. state.scissor( x, renderContext.height - height - y, width, height );
  47726. }
  47727. //
  47728. this.initTimestampQuery( TimestampQuery.RENDER, this.getTimestampUID( renderContext ) );
  47729. renderContextData.previousContext = this._currentContext;
  47730. this._currentContext = renderContext;
  47731. this._setFramebuffer( renderContext );
  47732. this.clear( renderContext.clearColor, renderContext.clearDepth, renderContext.clearStencil, renderContext, false );
  47733. const occlusionQueryCount = renderContext.occlusionQueryCount;
  47734. if ( occlusionQueryCount > 0 ) {
  47735. // Get a reference to the array of objects with queries. The renderContextData property
  47736. // can be changed by another render pass before the async reading of all previous queries complete
  47737. renderContextData.currentOcclusionQueries = renderContextData.occlusionQueries;
  47738. renderContextData.currentOcclusionQueryObjects = renderContextData.occlusionQueryObjects;
  47739. renderContextData.lastOcclusionObject = null;
  47740. renderContextData.occlusionQueries = new Array( occlusionQueryCount );
  47741. renderContextData.occlusionQueryObjects = new Array( occlusionQueryCount );
  47742. renderContextData.occlusionQueryIndex = 0;
  47743. }
  47744. }
  47745. /**
  47746. * This method is executed at the end of a render call and finalizes work
  47747. * after draw calls.
  47748. *
  47749. * @param {RenderContext} renderContext - The render context.
  47750. */
  47751. finishRender( renderContext ) {
  47752. const { gl, state } = this;
  47753. const renderContextData = this.get( renderContext );
  47754. const previousContext = renderContextData.previousContext;
  47755. state.resetVertexState();
  47756. const occlusionQueryCount = renderContext.occlusionQueryCount;
  47757. if ( occlusionQueryCount > 0 ) {
  47758. if ( occlusionQueryCount > renderContextData.occlusionQueryIndex ) {
  47759. gl.endQuery( gl.ANY_SAMPLES_PASSED );
  47760. }
  47761. this.resolveOccludedAsync( renderContext );
  47762. }
  47763. const textures = renderContext.textures;
  47764. if ( textures !== null ) {
  47765. for ( let i = 0; i < textures.length; i ++ ) {
  47766. const texture = textures[ i ];
  47767. if ( texture.generateMipmaps ) {
  47768. this.generateMipmaps( texture );
  47769. }
  47770. }
  47771. }
  47772. this._currentContext = previousContext;
  47773. this._resolveRenderTarget( renderContext );
  47774. if ( previousContext !== null ) {
  47775. this._setFramebuffer( previousContext );
  47776. if ( previousContext.viewport ) {
  47777. this.updateViewport( previousContext );
  47778. } else {
  47779. const { width, height } = this.getDrawingBufferSize();
  47780. state.viewport( 0, 0, width, height );
  47781. }
  47782. }
  47783. this.prepareTimestampBuffer( TimestampQuery.RENDER, this.getTimestampUID( renderContext ) );
  47784. }
  47785. /**
  47786. * This method processes the result of occlusion queries and writes it
  47787. * into render context data.
  47788. *
  47789. * @async
  47790. * @param {RenderContext} renderContext - The render context.
  47791. */
  47792. resolveOccludedAsync( renderContext ) {
  47793. const renderContextData = this.get( renderContext );
  47794. // handle occlusion query results
  47795. const { currentOcclusionQueries, currentOcclusionQueryObjects } = renderContextData;
  47796. if ( currentOcclusionQueries && currentOcclusionQueryObjects ) {
  47797. const occluded = new WeakSet();
  47798. const { gl } = this;
  47799. renderContextData.currentOcclusionQueryObjects = null;
  47800. renderContextData.currentOcclusionQueries = null;
  47801. const check = () => {
  47802. let completed = 0;
  47803. // check all queries and requeue as appropriate
  47804. for ( let i = 0; i < currentOcclusionQueries.length; i ++ ) {
  47805. const query = currentOcclusionQueries[ i ];
  47806. if ( query === null ) continue;
  47807. if ( gl.getQueryParameter( query, gl.QUERY_RESULT_AVAILABLE ) ) {
  47808. if ( gl.getQueryParameter( query, gl.QUERY_RESULT ) === 0 ) occluded.add( currentOcclusionQueryObjects[ i ] );
  47809. currentOcclusionQueries[ i ] = null;
  47810. gl.deleteQuery( query );
  47811. completed ++;
  47812. }
  47813. }
  47814. if ( completed < currentOcclusionQueries.length ) {
  47815. requestAnimationFrame( check );
  47816. } else {
  47817. renderContextData.occluded = occluded;
  47818. }
  47819. };
  47820. check();
  47821. }
  47822. }
  47823. /**
  47824. * Returns `true` if the given 3D object is fully occluded by other
  47825. * 3D objects in the scene.
  47826. *
  47827. * @param {RenderContext} renderContext - The render context.
  47828. * @param {Object3D} object - The 3D object to test.
  47829. * @return {boolean} Whether the 3D object is fully occluded or not.
  47830. */
  47831. isOccluded( renderContext, object ) {
  47832. const renderContextData = this.get( renderContext );
  47833. return renderContextData.occluded && renderContextData.occluded.has( object );
  47834. }
  47835. /**
  47836. * Updates the viewport with the values from the given render context.
  47837. *
  47838. * @param {RenderContext} renderContext - The render context.
  47839. */
  47840. updateViewport( renderContext ) {
  47841. const { state } = this;
  47842. const { x, y, width, height } = renderContext.viewportValue;
  47843. state.viewport( x, renderContext.height - height - y, width, height );
  47844. }
  47845. /**
  47846. * Defines the scissor test.
  47847. *
  47848. * @param {boolean} boolean - Whether the scissor test should be enabled or not.
  47849. */
  47850. setScissorTest( boolean ) {
  47851. const state = this.state;
  47852. state.setScissorTest( boolean );
  47853. }
  47854. /**
  47855. * Returns the clear color and alpha into a single
  47856. * color object.
  47857. *
  47858. * @return {Color4} The clear color.
  47859. */
  47860. getClearColor() {
  47861. const clearColor = super.getClearColor();
  47862. // Since the canvas is always created with alpha: true,
  47863. // WebGL must always premultiply the clear color.
  47864. clearColor.r *= clearColor.a;
  47865. clearColor.g *= clearColor.a;
  47866. clearColor.b *= clearColor.a;
  47867. return clearColor;
  47868. }
  47869. /**
  47870. * Performs a clear operation.
  47871. *
  47872. * @param {boolean} color - Whether the color buffer should be cleared or not.
  47873. * @param {boolean} depth - Whether the depth buffer should be cleared or not.
  47874. * @param {boolean} stencil - Whether the stencil buffer should be cleared or not.
  47875. * @param {?Object} [descriptor=null] - The render context of the current set render target.
  47876. * @param {boolean} [setFrameBuffer=true] - Controls whether the intermediate framebuffer should be set or not.
  47877. * @param {boolean} [resolveRenderTarget=true] - Controls whether an active render target should be resolved
  47878. * or not. Only relevant for explicit clears.
  47879. */
  47880. clear( color, depth, stencil, descriptor = null, setFrameBuffer = true, resolveRenderTarget = true ) {
  47881. const { gl, renderer } = this;
  47882. if ( descriptor === null ) {
  47883. const clearColor = this.getClearColor();
  47884. descriptor = {
  47885. textures: null,
  47886. clearColorValue: clearColor
  47887. };
  47888. }
  47889. //
  47890. let clear = 0;
  47891. if ( color ) clear |= gl.COLOR_BUFFER_BIT;
  47892. if ( depth ) clear |= gl.DEPTH_BUFFER_BIT;
  47893. if ( stencil ) clear |= gl.STENCIL_BUFFER_BIT;
  47894. if ( clear !== 0 ) {
  47895. let clearColor;
  47896. if ( descriptor.clearColorValue ) {
  47897. clearColor = descriptor.clearColorValue;
  47898. } else {
  47899. clearColor = this.getClearColor();
  47900. }
  47901. const clearDepth = renderer.getClearDepth();
  47902. const clearStencil = renderer.getClearStencil();
  47903. if ( depth ) this.state.setDepthMask( true );
  47904. if ( descriptor.textures === null ) {
  47905. gl.clearColor( clearColor.r, clearColor.g, clearColor.b, clearColor.a );
  47906. gl.clear( clear );
  47907. } else {
  47908. if ( setFrameBuffer ) this._setFramebuffer( descriptor );
  47909. if ( color ) {
  47910. for ( let i = 0; i < descriptor.textures.length; i ++ ) {
  47911. if ( i === 0 ) {
  47912. gl.clearBufferfv( gl.COLOR, i, [ clearColor.r, clearColor.g, clearColor.b, clearColor.a ] );
  47913. } else {
  47914. gl.clearBufferfv( gl.COLOR, i, [ 0, 0, 0, 1 ] );
  47915. }
  47916. }
  47917. }
  47918. if ( depth && stencil ) {
  47919. gl.clearBufferfi( gl.DEPTH_STENCIL, 0, clearDepth, clearStencil );
  47920. } else if ( depth ) {
  47921. gl.clearBufferfv( gl.DEPTH, 0, [ clearDepth ] );
  47922. } else if ( stencil ) {
  47923. gl.clearBufferiv( gl.STENCIL, 0, [ clearStencil ] );
  47924. }
  47925. if ( setFrameBuffer && resolveRenderTarget ) this._resolveRenderTarget( descriptor );
  47926. }
  47927. }
  47928. }
  47929. /**
  47930. * This method is executed at the beginning of a compute call and
  47931. * prepares the state for upcoming compute tasks.
  47932. *
  47933. * @param {Node|Array<Node>} computeGroup - The compute node(s).
  47934. */
  47935. beginCompute( computeGroup ) {
  47936. const { state, gl } = this;
  47937. //
  47938. state.bindFramebuffer( gl.FRAMEBUFFER, null );
  47939. this.initTimestampQuery( TimestampQuery.COMPUTE, this.getTimestampUID( computeGroup ) );
  47940. }
  47941. /**
  47942. * Executes a compute command for the given compute node.
  47943. *
  47944. * @param {Node|Array<Node>} computeGroup - The group of compute nodes of a compute call. Can be a single compute node.
  47945. * @param {Node} computeNode - The compute node.
  47946. * @param {Array<BindGroup>} bindings - The bindings.
  47947. * @param {ComputePipeline} pipeline - The compute pipeline.
  47948. * @param {?number} [count=null] - The count of compute invocations. If `null`, the count is determined by the compute node.
  47949. */
  47950. compute( computeGroup, computeNode, bindings, pipeline, count = null ) {
  47951. const { state, gl } = this;
  47952. if ( this.discard === false ) {
  47953. // required here to handle async behaviour of render.compute()
  47954. gl.enable( gl.RASTERIZER_DISCARD );
  47955. this.discard = true;
  47956. }
  47957. const { programGPU, transformBuffers, attributes } = this.get( pipeline );
  47958. const vaoKey = this._getVaoKey( attributes );
  47959. const vaoGPU = this.vaoCache[ vaoKey ];
  47960. if ( vaoGPU === undefined ) {
  47961. this.vaoCache[ vaoKey ] = this._createVao( attributes );
  47962. } else {
  47963. state.setVertexState( vaoGPU );
  47964. }
  47965. state.useProgram( programGPU );
  47966. this._bindUniforms( bindings );
  47967. const transformFeedbackGPU = this._getTransformFeedback( transformBuffers );
  47968. gl.bindTransformFeedback( gl.TRANSFORM_FEEDBACK, transformFeedbackGPU );
  47969. gl.beginTransformFeedback( gl.POINTS );
  47970. count = ( count !== null ) ? count : computeNode.count;
  47971. if ( Array.isArray( count ) ) {
  47972. warnOnce( 'WebGLBackend.compute(): The count parameter must be a single number, not an array.' );
  47973. count = count[ 0 ];
  47974. } else if ( count && typeof count === 'object' && count.isIndirectStorageBufferAttribute ) {
  47975. warnOnce( 'WebGLBackend.compute(): The count parameter must be a single number, not IndirectStorageBufferAttribute' );
  47976. count = computeNode.count;
  47977. }
  47978. if ( attributes[ 0 ].isStorageInstancedBufferAttribute ) {
  47979. gl.drawArraysInstanced( gl.POINTS, 0, 1, count );
  47980. } else {
  47981. gl.drawArrays( gl.POINTS, 0, count );
  47982. }
  47983. gl.endTransformFeedback();
  47984. gl.bindTransformFeedback( gl.TRANSFORM_FEEDBACK, null );
  47985. // switch active buffers
  47986. for ( let i = 0; i < transformBuffers.length; i ++ ) {
  47987. const dualAttributeData = transformBuffers[ i ];
  47988. if ( dualAttributeData.pbo && this.has( dualAttributeData.pbo ) ) {
  47989. this.textureUtils.copyBufferToTexture( dualAttributeData.transformBuffer, dualAttributeData.pbo );
  47990. }
  47991. dualAttributeData.switchBuffers();
  47992. }
  47993. }
  47994. /**
  47995. * This method is executed at the end of a compute call and
  47996. * finalizes work after compute tasks.
  47997. *
  47998. * @param {Node|Array<Node>} computeGroup - The compute node(s).
  47999. */
  48000. finishCompute( computeGroup ) {
  48001. const gl = this.gl;
  48002. this.discard = false;
  48003. gl.disable( gl.RASTERIZER_DISCARD );
  48004. this.prepareTimestampBuffer( TimestampQuery.COMPUTE, this.getTimestampUID( computeGroup ) );
  48005. if ( this._currentContext ) {
  48006. this._setFramebuffer( this._currentContext );
  48007. }
  48008. }
  48009. /**
  48010. * Internal to determine if the current render target is a render target array with depth 2D array texture.
  48011. *
  48012. * @param {RenderContext} renderContext - The render context.
  48013. * @return {boolean} Whether the render target is a render target array with depth 2D array texture.
  48014. *
  48015. * @private
  48016. */
  48017. _isRenderCameraDepthArray( renderContext ) {
  48018. return renderContext.depthTexture && renderContext.depthTexture.isArrayTexture && renderContext.camera.isArrayCamera;
  48019. }
  48020. /**
  48021. * Executes a draw command for the given render object.
  48022. *
  48023. * @param {RenderObject} renderObject - The render object to draw.
  48024. * @param {Info} info - Holds a series of statistical information about the GPU memory and the rendering process.
  48025. */
  48026. draw( renderObject/*, info*/ ) {
  48027. const { object, pipeline, material, context, hardwareClippingPlanes } = renderObject;
  48028. const { programGPU } = this.get( pipeline );
  48029. const { gl, state } = this;
  48030. const contextData = this.get( context );
  48031. const drawParams = renderObject.getDrawParameters();
  48032. if ( drawParams === null ) return;
  48033. //
  48034. this._bindUniforms( renderObject.getBindings() );
  48035. const frontFaceCW = ( object.isMesh && object.matrixWorld.determinant() < 0 );
  48036. state.setMaterial( material, frontFaceCW, hardwareClippingPlanes );
  48037. state.useProgram( programGPU );
  48038. // vertex state
  48039. const attributes = renderObject.getAttributes();
  48040. const attributesData = this.get( attributes );
  48041. let vaoGPU = attributesData.vaoGPU;
  48042. if ( vaoGPU === undefined ) {
  48043. const vaoKey = this._getVaoKey( attributes );
  48044. vaoGPU = this.vaoCache[ vaoKey ];
  48045. if ( vaoGPU === undefined ) {
  48046. vaoGPU = this._createVao( attributes );
  48047. this.vaoCache[ vaoKey ] = vaoGPU;
  48048. attributesData.vaoGPU = vaoGPU;
  48049. }
  48050. }
  48051. const index = renderObject.getIndex();
  48052. const indexGPU = ( index !== null ) ? this.get( index ).bufferGPU : null;
  48053. state.setVertexState( vaoGPU, indexGPU );
  48054. //
  48055. const lastObject = contextData.lastOcclusionObject;
  48056. if ( lastObject !== object && lastObject !== undefined ) {
  48057. if ( lastObject !== null && lastObject.occlusionTest === true ) {
  48058. gl.endQuery( gl.ANY_SAMPLES_PASSED );
  48059. contextData.occlusionQueryIndex ++;
  48060. }
  48061. if ( object.occlusionTest === true ) {
  48062. const query = gl.createQuery();
  48063. gl.beginQuery( gl.ANY_SAMPLES_PASSED, query );
  48064. contextData.occlusionQueries[ contextData.occlusionQueryIndex ] = query;
  48065. contextData.occlusionQueryObjects[ contextData.occlusionQueryIndex ] = object;
  48066. }
  48067. contextData.lastOcclusionObject = object;
  48068. }
  48069. //
  48070. const renderer = this.bufferRenderer;
  48071. if ( object.isPoints ) renderer.mode = gl.POINTS;
  48072. else if ( object.isLineSegments ) renderer.mode = gl.LINES;
  48073. else if ( object.isLine ) renderer.mode = gl.LINE_STRIP;
  48074. else if ( object.isLineLoop ) renderer.mode = gl.LINE_LOOP;
  48075. else {
  48076. if ( material.wireframe === true ) {
  48077. state.setLineWidth( material.wireframeLinewidth * this.renderer.getPixelRatio() );
  48078. renderer.mode = gl.LINES;
  48079. } else {
  48080. renderer.mode = gl.TRIANGLES;
  48081. }
  48082. }
  48083. //
  48084. const { vertexCount, instanceCount } = drawParams;
  48085. let { firstVertex } = drawParams;
  48086. renderer.object = object;
  48087. if ( index !== null ) {
  48088. firstVertex *= index.array.BYTES_PER_ELEMENT;
  48089. const indexData = this.get( index );
  48090. renderer.index = index.count;
  48091. renderer.type = indexData.type;
  48092. } else {
  48093. renderer.index = 0;
  48094. }
  48095. const draw = () => {
  48096. if ( object.isBatchedMesh ) {
  48097. if ( object._multiDrawInstances !== null ) {
  48098. // @deprecated, r174
  48099. warnOnce( 'WebGLBackend: renderMultiDrawInstances has been deprecated and will be removed in r184. Append to renderMultiDraw arguments and use indirection.' );
  48100. renderer.renderMultiDrawInstances( object._multiDrawStarts, object._multiDrawCounts, object._multiDrawCount, object._multiDrawInstances );
  48101. } else if ( ! this.hasFeature( 'WEBGL_multi_draw' ) ) {
  48102. warnOnce( 'WebGLBackend: WEBGL_multi_draw not supported.' );
  48103. } else {
  48104. renderer.renderMultiDraw( object._multiDrawStarts, object._multiDrawCounts, object._multiDrawCount );
  48105. }
  48106. } else if ( instanceCount > 1 ) {
  48107. renderer.renderInstances( firstVertex, vertexCount, instanceCount );
  48108. } else {
  48109. renderer.render( firstVertex, vertexCount );
  48110. }
  48111. };
  48112. if ( renderObject.camera.isArrayCamera === true && renderObject.camera.cameras.length > 0 && renderObject.camera.isMultiViewCamera === false ) {
  48113. const cameraData = this.get( renderObject.camera );
  48114. const cameras = renderObject.camera.cameras;
  48115. const cameraIndex = renderObject.getBindingGroup( 'cameraIndex' ).bindings[ 0 ];
  48116. if ( cameraData.indexesGPU === undefined || cameraData.indexesGPU.length !== cameras.length ) {
  48117. const data = new Uint32Array( [ 0, 0, 0, 0 ] );
  48118. const indexesGPU = [];
  48119. for ( let i = 0, len = cameras.length; i < len; i ++ ) {
  48120. const bufferGPU = gl.createBuffer();
  48121. data[ 0 ] = i;
  48122. gl.bindBuffer( gl.UNIFORM_BUFFER, bufferGPU );
  48123. gl.bufferData( gl.UNIFORM_BUFFER, data, gl.STATIC_DRAW );
  48124. indexesGPU.push( bufferGPU );
  48125. }
  48126. cameraData.indexesGPU = indexesGPU; // TODO: Create a global library for this
  48127. }
  48128. const cameraIndexData = this.get( cameraIndex );
  48129. const pixelRatio = this.renderer.getPixelRatio();
  48130. const renderTarget = this._currentContext.renderTarget;
  48131. const isRenderCameraDepthArray = this._isRenderCameraDepthArray( this._currentContext );
  48132. const prevActiveCubeFace = this._currentContext.activeCubeFace;
  48133. if ( isRenderCameraDepthArray ) {
  48134. // Clear the depth texture
  48135. const textureData = this.get( renderTarget.depthTexture );
  48136. if ( textureData.clearedRenderId !== this.renderer._nodes.nodeFrame.renderId ) {
  48137. textureData.clearedRenderId = this.renderer._nodes.nodeFrame.renderId;
  48138. const { stencilBuffer } = renderTarget;
  48139. for ( let i = 0, len = cameras.length; i < len; i ++ ) {
  48140. this.renderer._activeCubeFace = i;
  48141. this._currentContext.activeCubeFace = i;
  48142. this._setFramebuffer( this._currentContext );
  48143. this.clear( false, true, stencilBuffer, this._currentContext, false, false );
  48144. }
  48145. this.renderer._activeCubeFace = prevActiveCubeFace;
  48146. this._currentContext.activeCubeFace = prevActiveCubeFace;
  48147. }
  48148. }
  48149. for ( let i = 0, len = cameras.length; i < len; i ++ ) {
  48150. const subCamera = cameras[ i ];
  48151. if ( object.layers.test( subCamera.layers ) ) {
  48152. if ( isRenderCameraDepthArray ) {
  48153. // Update the active layer
  48154. this.renderer._activeCubeFace = i;
  48155. this._currentContext.activeCubeFace = i;
  48156. this._setFramebuffer( this._currentContext );
  48157. }
  48158. const vp = subCamera.viewport;
  48159. if ( vp !== undefined ) {
  48160. const x = vp.x * pixelRatio;
  48161. const y = vp.y * pixelRatio;
  48162. const width = vp.width * pixelRatio;
  48163. const height = vp.height * pixelRatio;
  48164. state.viewport(
  48165. Math.floor( x ),
  48166. Math.floor( renderObject.context.height - height - y ),
  48167. Math.floor( width ),
  48168. Math.floor( height )
  48169. );
  48170. }
  48171. state.bindBufferBase( gl.UNIFORM_BUFFER, cameraIndexData.index, cameraData.indexesGPU[ i ] );
  48172. draw();
  48173. }
  48174. this._currentContext.activeCubeFace = prevActiveCubeFace;
  48175. this.renderer._activeCubeFace = prevActiveCubeFace;
  48176. }
  48177. } else {
  48178. draw();
  48179. }
  48180. }
  48181. /**
  48182. * Explain why always null is returned.
  48183. *
  48184. * @param {RenderObject} renderObject - The render object.
  48185. * @return {boolean} Whether the render pipeline requires an update or not.
  48186. */
  48187. needsRenderUpdate( /*renderObject*/ ) {
  48188. return false;
  48189. }
  48190. /**
  48191. * Explain why no cache key is computed.
  48192. *
  48193. * @param {RenderObject} renderObject - The render object.
  48194. * @return {string} The cache key.
  48195. */
  48196. getRenderCacheKey( /*renderObject*/ ) {
  48197. return '';
  48198. }
  48199. // textures
  48200. /**
  48201. * Creates a default texture for the given texture that can be used
  48202. * as a placeholder until the actual texture is ready for usage.
  48203. *
  48204. * @param {Texture} texture - The texture to create a default texture for.
  48205. */
  48206. createDefaultTexture( texture ) {
  48207. this.textureUtils.createDefaultTexture( texture );
  48208. }
  48209. /**
  48210. * Defines a texture on the GPU for the given texture object.
  48211. *
  48212. * @param {Texture} texture - The texture.
  48213. * @param {Object} [options={}] - Optional configuration parameter.
  48214. */
  48215. createTexture( texture, options ) {
  48216. this.textureUtils.createTexture( texture, options );
  48217. }
  48218. /**
  48219. * Uploads the updated texture data to the GPU.
  48220. *
  48221. * @param {Texture} texture - The texture.
  48222. * @param {Object} [options={}] - Optional configuration parameter.
  48223. */
  48224. updateTexture( texture, options ) {
  48225. this.textureUtils.updateTexture( texture, options );
  48226. }
  48227. /**
  48228. * Generates mipmaps for the given texture.
  48229. *
  48230. * @param {Texture} texture - The texture.
  48231. */
  48232. generateMipmaps( texture ) {
  48233. this.textureUtils.generateMipmaps( texture );
  48234. }
  48235. /**
  48236. * Destroys the GPU data for the given texture object.
  48237. *
  48238. * @param {Texture} texture - The texture.
  48239. * @param {boolean} [isDefaultTexture=false] - Whether the texture uses a default GPU texture or not.
  48240. */
  48241. destroyTexture( texture, isDefaultTexture = false ) {
  48242. this.textureUtils.destroyTexture( texture, isDefaultTexture );
  48243. }
  48244. /**
  48245. * Returns texture data as a typed array.
  48246. *
  48247. * @async
  48248. * @param {Texture} texture - The texture to copy.
  48249. * @param {number} x - The x coordinate of the copy origin.
  48250. * @param {number} y - The y coordinate of the copy origin.
  48251. * @param {number} width - The width of the copy.
  48252. * @param {number} height - The height of the copy.
  48253. * @param {number} faceIndex - The face index.
  48254. * @return {Promise<TypedArray>} A Promise that resolves with a typed array when the copy operation has finished.
  48255. */
  48256. async copyTextureToBuffer( texture, x, y, width, height, faceIndex ) {
  48257. return this.textureUtils.copyTextureToBuffer( texture, x, y, width, height, faceIndex );
  48258. }
  48259. /**
  48260. * This method does nothing since WebGL 2 has no concept of samplers.
  48261. *
  48262. * @param {Texture} texture - The texture to update the sampler for.
  48263. * @return {string} The current sampler key.
  48264. */
  48265. updateSampler( /*texture*/ ) {
  48266. return '';
  48267. }
  48268. // node builder
  48269. /**
  48270. * Returns a node builder for the given render object.
  48271. *
  48272. * @param {RenderObject} object - The render object.
  48273. * @param {Renderer} renderer - The renderer.
  48274. * @return {GLSLNodeBuilder} The node builder.
  48275. */
  48276. createNodeBuilder( object, renderer ) {
  48277. return new GLSLNodeBuilder( object, renderer );
  48278. }
  48279. // program
  48280. /**
  48281. * Creates a shader program from the given programmable stage.
  48282. *
  48283. * @param {ProgrammableStage} program - The programmable stage.
  48284. */
  48285. createProgram( program ) {
  48286. const gl = this.gl;
  48287. const { stage, code } = program;
  48288. const shader = stage === 'fragment' ? gl.createShader( gl.FRAGMENT_SHADER ) : gl.createShader( gl.VERTEX_SHADER );
  48289. gl.shaderSource( shader, code );
  48290. gl.compileShader( shader );
  48291. this.set( program, {
  48292. shaderGPU: shader
  48293. } );
  48294. }
  48295. /**
  48296. * Destroys the shader program of the given programmable stage.
  48297. *
  48298. * @param {ProgrammableStage} program - The programmable stage.
  48299. */
  48300. destroyProgram( program ) {
  48301. this.delete( program );
  48302. }
  48303. /**
  48304. * Creates a render pipeline for the given render object.
  48305. *
  48306. * @param {RenderObject} renderObject - The render object.
  48307. * @param {Array<Promise>} promises - An array of compilation promises which are used in `compileAsync()`.
  48308. */
  48309. createRenderPipeline( renderObject, promises ) {
  48310. const gl = this.gl;
  48311. const pipeline = renderObject.pipeline;
  48312. // Program
  48313. const { fragmentProgram, vertexProgram } = pipeline;
  48314. const programGPU = gl.createProgram();
  48315. const fragmentShader = this.get( fragmentProgram ).shaderGPU;
  48316. const vertexShader = this.get( vertexProgram ).shaderGPU;
  48317. gl.attachShader( programGPU, fragmentShader );
  48318. gl.attachShader( programGPU, vertexShader );
  48319. gl.linkProgram( programGPU );
  48320. this.set( pipeline, {
  48321. programGPU,
  48322. fragmentShader,
  48323. vertexShader
  48324. } );
  48325. if ( promises !== null && this.parallel ) {
  48326. const p = new Promise( ( resolve /*, reject*/ ) => {
  48327. const parallel = this.parallel;
  48328. const checkStatus = () => {
  48329. if ( gl.getProgramParameter( programGPU, parallel.COMPLETION_STATUS_KHR ) ) {
  48330. this._completeCompile( renderObject, pipeline );
  48331. resolve();
  48332. } else {
  48333. requestAnimationFrame( checkStatus );
  48334. }
  48335. };
  48336. checkStatus();
  48337. } );
  48338. promises.push( p );
  48339. return;
  48340. }
  48341. this._completeCompile( renderObject, pipeline );
  48342. }
  48343. /**
  48344. * Formats the source code of error messages.
  48345. *
  48346. * @private
  48347. * @param {string} string - The code.
  48348. * @param {number} errorLine - The error line.
  48349. * @return {string} The formatted code.
  48350. */
  48351. _handleSource( string, errorLine ) {
  48352. const lines = string.split( '\n' );
  48353. const lines2 = [];
  48354. const from = Math.max( errorLine - 6, 0 );
  48355. const to = Math.min( errorLine + 6, lines.length );
  48356. for ( let i = from; i < to; i ++ ) {
  48357. const line = i + 1;
  48358. lines2.push( `${line === errorLine ? '>' : ' '} ${line}: ${lines[ i ]}` );
  48359. }
  48360. return lines2.join( '\n' );
  48361. }
  48362. /**
  48363. * Gets the shader compilation errors from the info log.
  48364. *
  48365. * @private
  48366. * @param {WebGL2RenderingContext} gl - The rendering context.
  48367. * @param {WebGLShader} shader - The WebGL shader object.
  48368. * @param {string} type - The shader type.
  48369. * @return {string} The shader errors.
  48370. */
  48371. _getShaderErrors( gl, shader, type ) {
  48372. const status = gl.getShaderParameter( shader, gl.COMPILE_STATUS );
  48373. const shaderInfoLog = gl.getShaderInfoLog( shader ) || '';
  48374. const errors = shaderInfoLog.trim();
  48375. if ( status && errors === '' ) return '';
  48376. const errorMatches = /ERROR: 0:(\d+)/.exec( errors );
  48377. if ( errorMatches ) {
  48378. const errorLine = parseInt( errorMatches[ 1 ] );
  48379. return type.toUpperCase() + '\n\n' + errors + '\n\n' + this._handleSource( gl.getShaderSource( shader ), errorLine );
  48380. } else {
  48381. return errors;
  48382. }
  48383. }
  48384. /**
  48385. * Logs shader compilation errors.
  48386. *
  48387. * @private
  48388. * @param {WebGLProgram} programGPU - The WebGL program.
  48389. * @param {WebGLShader} glFragmentShader - The fragment shader as a native WebGL shader object.
  48390. * @param {WebGLShader} glVertexShader - The vertex shader as a native WebGL shader object.
  48391. */
  48392. _logProgramError( programGPU, glFragmentShader, glVertexShader ) {
  48393. if ( this.renderer.debug.checkShaderErrors ) {
  48394. const gl = this.gl;
  48395. const programInfoLog = gl.getProgramInfoLog( programGPU ) || '';
  48396. const programLog = programInfoLog.trim();
  48397. if ( gl.getProgramParameter( programGPU, gl.LINK_STATUS ) === false ) {
  48398. if ( typeof this.renderer.debug.onShaderError === 'function' ) {
  48399. this.renderer.debug.onShaderError( gl, programGPU, glVertexShader, glFragmentShader );
  48400. } else {
  48401. // default error reporting
  48402. const vertexErrors = this._getShaderErrors( gl, glVertexShader, 'vertex' );
  48403. const fragmentErrors = this._getShaderErrors( gl, glFragmentShader, 'fragment' );
  48404. error(
  48405. 'THREE.WebGLProgram: Shader Error ' + gl.getError() + ' - ' +
  48406. 'VALIDATE_STATUS ' + gl.getProgramParameter( programGPU, gl.VALIDATE_STATUS ) + '\n\n' +
  48407. 'Program Info Log: ' + programLog + '\n' +
  48408. vertexErrors + '\n' +
  48409. fragmentErrors
  48410. );
  48411. }
  48412. } else if ( programLog !== '' ) {
  48413. warn( 'WebGLProgram: Program Info Log:', programLog );
  48414. }
  48415. }
  48416. }
  48417. /**
  48418. * Completes the shader program setup for the given render object.
  48419. *
  48420. * @private
  48421. * @param {RenderObject} renderObject - The render object.
  48422. * @param {RenderPipeline} pipeline - The render pipeline.
  48423. */
  48424. _completeCompile( renderObject, pipeline ) {
  48425. const { state, gl } = this;
  48426. const pipelineData = this.get( pipeline );
  48427. const { programGPU, fragmentShader, vertexShader } = pipelineData;
  48428. if ( gl.getProgramParameter( programGPU, gl.LINK_STATUS ) === false ) {
  48429. this._logProgramError( programGPU, fragmentShader, vertexShader );
  48430. }
  48431. state.useProgram( programGPU );
  48432. // Bindings
  48433. const bindings = renderObject.getBindings();
  48434. this._setupBindings( bindings, programGPU );
  48435. //
  48436. this.set( pipeline, {
  48437. programGPU
  48438. } );
  48439. }
  48440. /**
  48441. * Creates a compute pipeline for the given compute node.
  48442. *
  48443. * @param {ComputePipeline} computePipeline - The compute pipeline.
  48444. * @param {Array<BindGroup>} bindings - The bindings.
  48445. */
  48446. createComputePipeline( computePipeline, bindings ) {
  48447. const { state, gl } = this;
  48448. // Program
  48449. const fragmentProgram = {
  48450. stage: 'fragment',
  48451. code: '#version 300 es\nprecision highp float;\nvoid main() {}'
  48452. };
  48453. this.createProgram( fragmentProgram );
  48454. const { computeProgram } = computePipeline;
  48455. const programGPU = gl.createProgram();
  48456. const fragmentShader = this.get( fragmentProgram ).shaderGPU;
  48457. const vertexShader = this.get( computeProgram ).shaderGPU;
  48458. const transforms = computeProgram.transforms;
  48459. const transformVaryingNames = [];
  48460. const transformAttributeNodes = [];
  48461. for ( let i = 0; i < transforms.length; i ++ ) {
  48462. const transform = transforms[ i ];
  48463. transformVaryingNames.push( transform.varyingName );
  48464. transformAttributeNodes.push( transform.attributeNode );
  48465. }
  48466. gl.attachShader( programGPU, fragmentShader );
  48467. gl.attachShader( programGPU, vertexShader );
  48468. gl.transformFeedbackVaryings(
  48469. programGPU,
  48470. transformVaryingNames,
  48471. gl.SEPARATE_ATTRIBS
  48472. );
  48473. gl.linkProgram( programGPU );
  48474. if ( gl.getProgramParameter( programGPU, gl.LINK_STATUS ) === false ) {
  48475. this._logProgramError( programGPU, fragmentShader, vertexShader );
  48476. }
  48477. state.useProgram( programGPU );
  48478. // Bindings
  48479. this._setupBindings( bindings, programGPU );
  48480. const attributeNodes = computeProgram.attributes;
  48481. const attributes = [];
  48482. const transformBuffers = [];
  48483. for ( let i = 0; i < attributeNodes.length; i ++ ) {
  48484. const attribute = attributeNodes[ i ].node.attribute;
  48485. attributes.push( attribute );
  48486. if ( ! this.has( attribute ) ) this.attributeUtils.createAttribute( attribute, gl.ARRAY_BUFFER );
  48487. }
  48488. for ( let i = 0; i < transformAttributeNodes.length; i ++ ) {
  48489. const attribute = transformAttributeNodes[ i ].attribute;
  48490. if ( ! this.has( attribute ) ) this.attributeUtils.createAttribute( attribute, gl.ARRAY_BUFFER );
  48491. const attributeData = this.get( attribute );
  48492. transformBuffers.push( attributeData );
  48493. }
  48494. //
  48495. this.set( computePipeline, {
  48496. programGPU,
  48497. transformBuffers,
  48498. attributes
  48499. } );
  48500. }
  48501. /**
  48502. * Creates bindings from the given bind group definition.
  48503. *
  48504. * @param {BindGroup} bindGroup - The bind group.
  48505. * @param {Array<BindGroup>} bindings - Array of bind groups.
  48506. * @param {number} cacheIndex - The cache index.
  48507. * @param {number} version - The version.
  48508. */
  48509. createBindings( bindGroup, bindings /*, cacheIndex, version*/ ) {
  48510. if ( this._knownBindings.has( bindings ) === false ) {
  48511. this._knownBindings.add( bindings );
  48512. let uniformBuffers = 0;
  48513. let textures = 0;
  48514. for ( const bindGroup of bindings ) {
  48515. this.set( bindGroup, {
  48516. textures: textures,
  48517. uniformBuffers: uniformBuffers
  48518. } );
  48519. for ( const binding of bindGroup.bindings ) {
  48520. if ( binding.isUniformBuffer ) uniformBuffers ++;
  48521. if ( binding.isSampledTexture ) textures ++;
  48522. }
  48523. }
  48524. }
  48525. this.updateBindings( bindGroup, bindings );
  48526. }
  48527. /**
  48528. * Updates the given bind group definition.
  48529. *
  48530. * @param {BindGroup} bindGroup - The bind group.
  48531. * @param {Array<BindGroup>} bindings - Array of bind groups.
  48532. * @param {number} cacheIndex - The cache index.
  48533. * @param {number} version - The version.
  48534. */
  48535. updateBindings( bindGroup /*, bindings, cacheIndex, version*/ ) {
  48536. const { gl } = this;
  48537. const bindGroupData = this.get( bindGroup );
  48538. let i = bindGroupData.uniformBuffers;
  48539. let t = bindGroupData.textures;
  48540. for ( const binding of bindGroup.bindings ) {
  48541. const map = this.get( binding );
  48542. if ( binding.isUniformsGroup || binding.isUniformBuffer ) {
  48543. const data = binding.buffer;
  48544. let { bufferGPU } = this.get( data );
  48545. if ( bufferGPU === undefined ) {
  48546. // create
  48547. bufferGPU = gl.createBuffer();
  48548. gl.bindBuffer( gl.UNIFORM_BUFFER, bufferGPU );
  48549. gl.bufferData( gl.UNIFORM_BUFFER, data, gl.DYNAMIC_DRAW );
  48550. this.set( data, { bufferGPU } );
  48551. } else {
  48552. // update
  48553. gl.bindBuffer( gl.UNIFORM_BUFFER, bufferGPU );
  48554. gl.bufferSubData( gl.UNIFORM_BUFFER, 0, data );
  48555. }
  48556. map.index = i ++;
  48557. map.bufferGPU = bufferGPU;
  48558. this.set( binding, map );
  48559. } else if ( binding.isSampledTexture ) {
  48560. const { textureGPU, glTextureType } = this.get( binding.texture );
  48561. map.index = t ++;
  48562. map.textureGPU = textureGPU;
  48563. map.glTextureType = glTextureType;
  48564. this.set( binding, map );
  48565. }
  48566. }
  48567. }
  48568. /**
  48569. * Updates a buffer binding.
  48570. *
  48571. * @param {Buffer} binding - The buffer binding to update.
  48572. */
  48573. updateBinding( binding ) {
  48574. const gl = this.gl;
  48575. if ( binding.isUniformsGroup || binding.isUniformBuffer ) {
  48576. const bindingData = this.get( binding );
  48577. const bufferGPU = bindingData.bufferGPU;
  48578. const data = binding.buffer;
  48579. gl.bindBuffer( gl.UNIFORM_BUFFER, bufferGPU );
  48580. gl.bufferData( gl.UNIFORM_BUFFER, data, gl.DYNAMIC_DRAW );
  48581. }
  48582. }
  48583. // attributes
  48584. /**
  48585. * Creates the GPU buffer of an indexed shader attribute.
  48586. *
  48587. * @param {BufferAttribute} attribute - The indexed buffer attribute.
  48588. */
  48589. createIndexAttribute( attribute ) {
  48590. const gl = this.gl;
  48591. this.attributeUtils.createAttribute( attribute, gl.ELEMENT_ARRAY_BUFFER );
  48592. }
  48593. /**
  48594. * Creates the GPU buffer of a shader attribute.
  48595. *
  48596. * @param {BufferAttribute} attribute - The buffer attribute.
  48597. */
  48598. createAttribute( attribute ) {
  48599. if ( this.has( attribute ) ) return;
  48600. const gl = this.gl;
  48601. this.attributeUtils.createAttribute( attribute, gl.ARRAY_BUFFER );
  48602. }
  48603. /**
  48604. * Creates the GPU buffer of a storage attribute.
  48605. *
  48606. * @param {BufferAttribute} attribute - The buffer attribute.
  48607. */
  48608. createStorageAttribute( attribute ) {
  48609. if ( this.has( attribute ) ) return;
  48610. const gl = this.gl;
  48611. this.attributeUtils.createAttribute( attribute, gl.ARRAY_BUFFER );
  48612. }
  48613. /**
  48614. * Updates the GPU buffer of a shader attribute.
  48615. *
  48616. * @param {BufferAttribute} attribute - The buffer attribute to update.
  48617. */
  48618. updateAttribute( attribute ) {
  48619. this.attributeUtils.updateAttribute( attribute );
  48620. }
  48621. /**
  48622. * Destroys the GPU buffer of a shader attribute.
  48623. *
  48624. * @param {BufferAttribute} attribute - The buffer attribute to destroy.
  48625. */
  48626. destroyAttribute( attribute ) {
  48627. this.attributeUtils.destroyAttribute( attribute );
  48628. }
  48629. /**
  48630. * Checks if the given feature is supported by the backend.
  48631. *
  48632. * @param {string} name - The feature's name.
  48633. * @return {boolean} Whether the feature is supported or not.
  48634. */
  48635. hasFeature( name ) {
  48636. const keysMatching = Object.keys( GLFeatureName ).filter( key => GLFeatureName[ key ] === name );
  48637. const extensions = this.extensions;
  48638. for ( let i = 0; i < keysMatching.length; i ++ ) {
  48639. if ( extensions.has( keysMatching[ i ] ) ) return true;
  48640. }
  48641. return false;
  48642. }
  48643. /**
  48644. * Returns the maximum anisotropy texture filtering value.
  48645. *
  48646. * @return {number} The maximum anisotropy texture filtering value.
  48647. */
  48648. getMaxAnisotropy() {
  48649. return this.capabilities.getMaxAnisotropy();
  48650. }
  48651. /**
  48652. * Copies data of the given source texture to the given destination texture.
  48653. *
  48654. * @param {Texture} srcTexture - The source texture.
  48655. * @param {Texture} dstTexture - The destination texture.
  48656. * @param {?(Box3|Box2)} [srcRegion=null] - The region of the source texture to copy.
  48657. * @param {?(Vector2|Vector3)} [dstPosition=null] - The destination position of the copy.
  48658. * @param {number} [srcLevel=0] - The source mip level to copy from.
  48659. * @param {number} [dstLevel=0] - The destination mip level to copy to.
  48660. */
  48661. copyTextureToTexture( srcTexture, dstTexture, srcRegion = null, dstPosition = null, srcLevel = 0, dstLevel = 0 ) {
  48662. this.textureUtils.copyTextureToTexture( srcTexture, dstTexture, srcRegion, dstPosition, srcLevel, dstLevel );
  48663. }
  48664. /**
  48665. * Copies the current bound framebuffer to the given texture.
  48666. *
  48667. * @param {Texture} texture - The destination texture.
  48668. * @param {RenderContext} renderContext - The render context.
  48669. * @param {Vector4} rectangle - A four dimensional vector defining the origin and dimension of the copy.
  48670. */
  48671. copyFramebufferToTexture( texture, renderContext, rectangle ) {
  48672. this.textureUtils.copyFramebufferToTexture( texture, renderContext, rectangle );
  48673. }
  48674. /**
  48675. * Configures the active framebuffer from the given render context.
  48676. *
  48677. * @private
  48678. * @param {RenderContext} descriptor - The render context.
  48679. */
  48680. _setFramebuffer( descriptor ) {
  48681. const { gl, state } = this;
  48682. let currentFrameBuffer = null;
  48683. if ( descriptor.textures !== null ) {
  48684. const renderTarget = descriptor.renderTarget;
  48685. const renderTargetContextData = this.get( renderTarget );
  48686. const { samples, depthBuffer, stencilBuffer } = renderTarget;
  48687. const isCube = renderTarget.isWebGLCubeRenderTarget === true;
  48688. const isRenderTarget3D = renderTarget.isRenderTarget3D === true;
  48689. const isRenderTargetArray = renderTarget.depth > 1;
  48690. const isXRRenderTarget = renderTarget.isXRRenderTarget === true;
  48691. const _hasExternalTextures = ( isXRRenderTarget === true && renderTarget._hasExternalTextures === true );
  48692. let msaaFb = renderTargetContextData.msaaFrameBuffer;
  48693. let depthRenderbuffer = renderTargetContextData.depthRenderbuffer;
  48694. const multisampledRTTExt = this.extensions.get( 'WEBGL_multisampled_render_to_texture' );
  48695. const multiviewExt = this.extensions.get( 'OVR_multiview2' );
  48696. const useMultisampledRTT = this._useMultisampledExtension( renderTarget );
  48697. const cacheKey = getCacheKey( descriptor );
  48698. let fb;
  48699. if ( isCube ) {
  48700. renderTargetContextData.cubeFramebuffers || ( renderTargetContextData.cubeFramebuffers = {} );
  48701. fb = renderTargetContextData.cubeFramebuffers[ cacheKey ];
  48702. } else if ( isXRRenderTarget && _hasExternalTextures === false ) {
  48703. fb = this._xrFramebuffer;
  48704. } else {
  48705. renderTargetContextData.framebuffers || ( renderTargetContextData.framebuffers = {} );
  48706. fb = renderTargetContextData.framebuffers[ cacheKey ];
  48707. }
  48708. if ( fb === undefined ) {
  48709. fb = gl.createFramebuffer();
  48710. state.bindFramebuffer( gl.FRAMEBUFFER, fb );
  48711. const textures = descriptor.textures;
  48712. const depthInvalidationArray = [];
  48713. if ( isCube ) {
  48714. renderTargetContextData.cubeFramebuffers[ cacheKey ] = fb;
  48715. const { textureGPU } = this.get( textures[ 0 ] );
  48716. const cubeFace = this.renderer._activeCubeFace;
  48717. const mipLevel = this.renderer._activeMipmapLevel;
  48718. gl.framebufferTexture2D( gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + cubeFace, textureGPU, mipLevel );
  48719. } else {
  48720. renderTargetContextData.framebuffers[ cacheKey ] = fb;
  48721. for ( let i = 0; i < textures.length; i ++ ) {
  48722. const texture = textures[ i ];
  48723. const textureData = this.get( texture );
  48724. textureData.renderTarget = descriptor.renderTarget;
  48725. textureData.cacheKey = cacheKey; // required for copyTextureToTexture()
  48726. const attachment = gl.COLOR_ATTACHMENT0 + i;
  48727. if ( renderTarget.multiview ) {
  48728. multiviewExt.framebufferTextureMultisampleMultiviewOVR( gl.FRAMEBUFFER, attachment, textureData.textureGPU, 0, samples, 0, 2 );
  48729. } else if ( isRenderTarget3D || isRenderTargetArray ) {
  48730. const layer = this.renderer._activeCubeFace;
  48731. const mipLevel = this.renderer._activeMipmapLevel;
  48732. gl.framebufferTextureLayer( gl.FRAMEBUFFER, attachment, textureData.textureGPU, mipLevel, layer );
  48733. } else {
  48734. if ( useMultisampledRTT ) {
  48735. multisampledRTTExt.framebufferTexture2DMultisampleEXT( gl.FRAMEBUFFER, attachment, gl.TEXTURE_2D, textureData.textureGPU, 0, samples );
  48736. } else {
  48737. const mipLevel = this.renderer._activeMipmapLevel;
  48738. gl.framebufferTexture2D( gl.FRAMEBUFFER, attachment, gl.TEXTURE_2D, textureData.textureGPU, mipLevel );
  48739. }
  48740. }
  48741. }
  48742. }
  48743. const depthStyle = stencilBuffer ? gl.DEPTH_STENCIL_ATTACHMENT : gl.DEPTH_ATTACHMENT;
  48744. if ( renderTarget._autoAllocateDepthBuffer === true ) {
  48745. const renderbuffer = gl.createRenderbuffer();
  48746. this.textureUtils.setupRenderBufferStorage( renderbuffer, descriptor, 0, useMultisampledRTT );
  48747. renderTargetContextData.xrDepthRenderbuffer = renderbuffer;
  48748. depthInvalidationArray.push( stencilBuffer ? gl.DEPTH_STENCIL_ATTACHMENT : gl.DEPTH_ATTACHMENT );
  48749. gl.bindRenderbuffer( gl.RENDERBUFFER, renderbuffer );
  48750. gl.framebufferRenderbuffer( gl.FRAMEBUFFER, depthStyle, gl.RENDERBUFFER, renderbuffer );
  48751. } else {
  48752. if ( descriptor.depthTexture !== null ) {
  48753. depthInvalidationArray.push( stencilBuffer ? gl.DEPTH_STENCIL_ATTACHMENT : gl.DEPTH_ATTACHMENT );
  48754. const textureData = this.get( descriptor.depthTexture );
  48755. textureData.renderTarget = descriptor.renderTarget;
  48756. textureData.cacheKey = cacheKey; // required for copyTextureToTexture()
  48757. if ( renderTarget.multiview ) {
  48758. multiviewExt.framebufferTextureMultisampleMultiviewOVR( gl.FRAMEBUFFER, depthStyle, textureData.textureGPU, 0, samples, 0, 2 );
  48759. } else if ( _hasExternalTextures && useMultisampledRTT ) {
  48760. multisampledRTTExt.framebufferTexture2DMultisampleEXT( gl.FRAMEBUFFER, depthStyle, gl.TEXTURE_2D, textureData.textureGPU, 0, samples );
  48761. } else {
  48762. if ( descriptor.depthTexture.isArrayTexture ) {
  48763. const layer = this.renderer._activeCubeFace;
  48764. gl.framebufferTextureLayer( gl.FRAMEBUFFER, depthStyle, textureData.textureGPU, 0, layer );
  48765. } else {
  48766. gl.framebufferTexture2D( gl.FRAMEBUFFER, depthStyle, gl.TEXTURE_2D, textureData.textureGPU, 0 );
  48767. }
  48768. }
  48769. }
  48770. }
  48771. renderTargetContextData.depthInvalidationArray = depthInvalidationArray;
  48772. } else {
  48773. const isRenderCameraDepthArray = this._isRenderCameraDepthArray( descriptor );
  48774. if ( isRenderCameraDepthArray ) {
  48775. state.bindFramebuffer( gl.FRAMEBUFFER, fb );
  48776. const layer = this.renderer._activeCubeFace;
  48777. const depthData = this.get( descriptor.depthTexture );
  48778. const depthStyle = stencilBuffer ? gl.DEPTH_STENCIL_ATTACHMENT : gl.DEPTH_ATTACHMENT;
  48779. gl.framebufferTextureLayer(
  48780. gl.FRAMEBUFFER,
  48781. depthStyle,
  48782. depthData.textureGPU,
  48783. 0,
  48784. layer
  48785. );
  48786. }
  48787. // rebind external XR textures
  48788. if ( ( isXRRenderTarget || useMultisampledRTT || renderTarget.multiview ) && ( renderTarget._isOpaqueFramebuffer !== true ) ) {
  48789. state.bindFramebuffer( gl.FRAMEBUFFER, fb );
  48790. // rebind color
  48791. const textureData = this.get( descriptor.textures[ 0 ] );
  48792. if ( renderTarget.multiview ) {
  48793. multiviewExt.framebufferTextureMultisampleMultiviewOVR( gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, textureData.textureGPU, 0, samples, 0, 2 );
  48794. } else if ( useMultisampledRTT ) {
  48795. multisampledRTTExt.framebufferTexture2DMultisampleEXT( gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, textureData.textureGPU, 0, samples );
  48796. } else {
  48797. gl.framebufferTexture2D( gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, textureData.textureGPU, 0 );
  48798. }
  48799. // rebind depth
  48800. const depthStyle = stencilBuffer ? gl.DEPTH_STENCIL_ATTACHMENT : gl.DEPTH_ATTACHMENT;
  48801. if ( renderTarget._autoAllocateDepthBuffer === true ) {
  48802. const renderbuffer = renderTargetContextData.xrDepthRenderbuffer;
  48803. gl.bindRenderbuffer( gl.RENDERBUFFER, renderbuffer );
  48804. gl.framebufferRenderbuffer( gl.FRAMEBUFFER, depthStyle, gl.RENDERBUFFER, renderbuffer );
  48805. } else {
  48806. const textureData = this.get( descriptor.depthTexture );
  48807. if ( renderTarget.multiview ) {
  48808. multiviewExt.framebufferTextureMultisampleMultiviewOVR( gl.FRAMEBUFFER, depthStyle, textureData.textureGPU, 0, samples, 0, 2 );
  48809. } else if ( useMultisampledRTT ) {
  48810. multisampledRTTExt.framebufferTexture2DMultisampleEXT( gl.FRAMEBUFFER, depthStyle, gl.TEXTURE_2D, textureData.textureGPU, 0, samples );
  48811. } else {
  48812. gl.framebufferTexture2D( gl.FRAMEBUFFER, depthStyle, gl.TEXTURE_2D, textureData.textureGPU, 0 );
  48813. }
  48814. }
  48815. }
  48816. }
  48817. if ( samples > 0 && useMultisampledRTT === false && ! renderTarget.multiview ) {
  48818. if ( msaaFb === undefined ) {
  48819. const invalidationArray = [];
  48820. msaaFb = gl.createFramebuffer();
  48821. state.bindFramebuffer( gl.FRAMEBUFFER, msaaFb );
  48822. const msaaRenderbuffers = [];
  48823. const textures = descriptor.textures;
  48824. for ( let i = 0; i < textures.length; i ++ ) {
  48825. msaaRenderbuffers[ i ] = gl.createRenderbuffer();
  48826. gl.bindRenderbuffer( gl.RENDERBUFFER, msaaRenderbuffers[ i ] );
  48827. invalidationArray.push( gl.COLOR_ATTACHMENT0 + i );
  48828. const texture = descriptor.textures[ i ];
  48829. const textureData = this.get( texture );
  48830. gl.renderbufferStorageMultisample( gl.RENDERBUFFER, samples, textureData.glInternalFormat, descriptor.width, descriptor.height );
  48831. gl.framebufferRenderbuffer( gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0 + i, gl.RENDERBUFFER, msaaRenderbuffers[ i ] );
  48832. }
  48833. gl.bindRenderbuffer( gl.RENDERBUFFER, null );
  48834. renderTargetContextData.msaaFrameBuffer = msaaFb;
  48835. renderTargetContextData.msaaRenderbuffers = msaaRenderbuffers;
  48836. if ( depthBuffer && depthRenderbuffer === undefined ) {
  48837. depthRenderbuffer = gl.createRenderbuffer();
  48838. this.textureUtils.setupRenderBufferStorage( depthRenderbuffer, descriptor, samples );
  48839. renderTargetContextData.depthRenderbuffer = depthRenderbuffer;
  48840. const depthStyle = stencilBuffer ? gl.DEPTH_STENCIL_ATTACHMENT : gl.DEPTH_ATTACHMENT;
  48841. invalidationArray.push( depthStyle );
  48842. }
  48843. renderTargetContextData.invalidationArray = invalidationArray;
  48844. }
  48845. currentFrameBuffer = renderTargetContextData.msaaFrameBuffer;
  48846. } else {
  48847. currentFrameBuffer = fb;
  48848. }
  48849. state.drawBuffers( descriptor, fb );
  48850. }
  48851. state.bindFramebuffer( gl.FRAMEBUFFER, currentFrameBuffer );
  48852. }
  48853. /**
  48854. * Computes the VAO key for the given index and attributes.
  48855. *
  48856. * @private
  48857. * @param {Array<BufferAttribute>} attributes - An array of buffer attributes.
  48858. * @return {string} The VAO key.
  48859. */
  48860. _getVaoKey( attributes ) {
  48861. let key = '';
  48862. for ( let i = 0; i < attributes.length; i ++ ) {
  48863. const attributeData = this.get( attributes[ i ] );
  48864. key += ':' + attributeData.id;
  48865. }
  48866. return key;
  48867. }
  48868. /**
  48869. * Creates a VAO from the index and attributes.
  48870. *
  48871. * @private
  48872. * @param {Array<BufferAttribute>} attributes - An array of buffer attributes.
  48873. * @return {Object} The VAO data.
  48874. */
  48875. _createVao( attributes ) {
  48876. const { gl } = this;
  48877. const vaoGPU = gl.createVertexArray();
  48878. gl.bindVertexArray( vaoGPU );
  48879. for ( let i = 0; i < attributes.length; i ++ ) {
  48880. const attribute = attributes[ i ];
  48881. const attributeData = this.get( attribute );
  48882. gl.bindBuffer( gl.ARRAY_BUFFER, attributeData.bufferGPU );
  48883. gl.enableVertexAttribArray( i );
  48884. let stride, offset;
  48885. if ( attribute.isInterleavedBufferAttribute === true ) {
  48886. stride = attribute.data.stride * attributeData.bytesPerElement;
  48887. offset = attribute.offset * attributeData.bytesPerElement;
  48888. } else {
  48889. stride = 0;
  48890. offset = 0;
  48891. }
  48892. if ( attributeData.isInteger ) {
  48893. gl.vertexAttribIPointer( i, attribute.itemSize, attributeData.type, stride, offset );
  48894. } else {
  48895. gl.vertexAttribPointer( i, attribute.itemSize, attributeData.type, attribute.normalized, stride, offset );
  48896. }
  48897. if ( attribute.isInstancedBufferAttribute && ! attribute.isInterleavedBufferAttribute ) {
  48898. gl.vertexAttribDivisor( i, attribute.meshPerAttribute );
  48899. } else if ( attribute.isInterleavedBufferAttribute && attribute.data.isInstancedInterleavedBuffer ) {
  48900. gl.vertexAttribDivisor( i, attribute.data.meshPerAttribute );
  48901. }
  48902. }
  48903. gl.bindBuffer( gl.ARRAY_BUFFER, null );
  48904. return vaoGPU;
  48905. }
  48906. /**
  48907. * Creates a transform feedback from the given transform buffers.
  48908. *
  48909. * @private
  48910. * @param {Array<DualAttributeData>} transformBuffers - The transform buffers.
  48911. * @return {WebGLTransformFeedback} The transform feedback.
  48912. */
  48913. _getTransformFeedback( transformBuffers ) {
  48914. let key = '';
  48915. for ( let i = 0; i < transformBuffers.length; i ++ ) {
  48916. key += ':' + transformBuffers[ i ].id;
  48917. }
  48918. let transformFeedbackGPU = this.transformFeedbackCache[ key ];
  48919. if ( transformFeedbackGPU !== undefined ) {
  48920. return transformFeedbackGPU;
  48921. }
  48922. const { gl } = this;
  48923. transformFeedbackGPU = gl.createTransformFeedback();
  48924. gl.bindTransformFeedback( gl.TRANSFORM_FEEDBACK, transformFeedbackGPU );
  48925. for ( let i = 0; i < transformBuffers.length; i ++ ) {
  48926. const attributeData = transformBuffers[ i ];
  48927. gl.bindBufferBase( gl.TRANSFORM_FEEDBACK_BUFFER, i, attributeData.transformBuffer );
  48928. }
  48929. gl.bindTransformFeedback( gl.TRANSFORM_FEEDBACK, null );
  48930. this.transformFeedbackCache[ key ] = transformFeedbackGPU;
  48931. return transformFeedbackGPU;
  48932. }
  48933. /**
  48934. * Setups the given bindings.
  48935. *
  48936. * @private
  48937. * @param {Array<BindGroup>} bindings - The bindings.
  48938. * @param {WebGLProgram} programGPU - The WebGL program.
  48939. */
  48940. _setupBindings( bindings, programGPU ) {
  48941. const gl = this.gl;
  48942. for ( const bindGroup of bindings ) {
  48943. for ( const binding of bindGroup.bindings ) {
  48944. const bindingData = this.get( binding );
  48945. const index = bindingData.index;
  48946. if ( binding.isUniformsGroup || binding.isUniformBuffer ) {
  48947. const location = gl.getUniformBlockIndex( programGPU, binding.name );
  48948. gl.uniformBlockBinding( programGPU, location, index );
  48949. } else if ( binding.isSampledTexture ) {
  48950. const location = gl.getUniformLocation( programGPU, binding.name );
  48951. gl.uniform1i( location, index );
  48952. }
  48953. }
  48954. }
  48955. }
  48956. /**
  48957. * Binds the given uniforms.
  48958. *
  48959. * @private
  48960. * @param {Array<BindGroup>} bindings - The bindings.
  48961. */
  48962. _bindUniforms( bindings ) {
  48963. const { gl, state } = this;
  48964. for ( const bindGroup of bindings ) {
  48965. for ( const binding of bindGroup.bindings ) {
  48966. const bindingData = this.get( binding );
  48967. const index = bindingData.index;
  48968. if ( binding.isUniformsGroup || binding.isUniformBuffer ) {
  48969. // TODO USE bindBufferRange to group multiple uniform buffers
  48970. state.bindBufferBase( gl.UNIFORM_BUFFER, index, bindingData.bufferGPU );
  48971. } else if ( binding.isSampledTexture ) {
  48972. state.bindTexture( bindingData.glTextureType, bindingData.textureGPU, gl.TEXTURE0 + index );
  48973. }
  48974. }
  48975. }
  48976. }
  48977. /**
  48978. * The method ensures multisampled render targets are resolved.
  48979. *
  48980. * @private
  48981. * @param {RenderContext} renderContext - The render context.
  48982. */
  48983. _resolveRenderTarget( renderContext ) {
  48984. const { gl, state } = this;
  48985. const renderTarget = renderContext.renderTarget;
  48986. if ( renderContext.textures !== null && renderTarget ) {
  48987. const renderTargetContextData = this.get( renderTarget );
  48988. if ( renderTarget.samples > 0 && this._useMultisampledExtension( renderTarget ) === false ) {
  48989. const fb = renderTargetContextData.framebuffers[ renderContext.getCacheKey() ];
  48990. let mask = gl.COLOR_BUFFER_BIT;
  48991. if ( renderTarget.resolveDepthBuffer ) {
  48992. if ( renderTarget.depthBuffer ) mask |= gl.DEPTH_BUFFER_BIT;
  48993. if ( renderTarget.stencilBuffer && renderTarget.resolveStencilBuffer ) mask |= gl.STENCIL_BUFFER_BIT;
  48994. }
  48995. const msaaFrameBuffer = renderTargetContextData.msaaFrameBuffer;
  48996. const msaaRenderbuffers = renderTargetContextData.msaaRenderbuffers;
  48997. const textures = renderContext.textures;
  48998. const isMRT = textures.length > 1;
  48999. state.bindFramebuffer( gl.READ_FRAMEBUFFER, msaaFrameBuffer );
  49000. state.bindFramebuffer( gl.DRAW_FRAMEBUFFER, fb );
  49001. if ( isMRT ) {
  49002. // blitFramebuffer() can only copy/resolve the first color attachment of a framebuffer. When using MRT,
  49003. // the engine temporarily removes all attachments and then configures each attachment for the resolve.
  49004. for ( let i = 0; i < textures.length; i ++ ) {
  49005. gl.framebufferRenderbuffer( gl.READ_FRAMEBUFFER, gl.COLOR_ATTACHMENT0 + i, gl.RENDERBUFFER, null );
  49006. gl.framebufferTexture2D( gl.DRAW_FRAMEBUFFER, gl.COLOR_ATTACHMENT0 + i, gl.TEXTURE_2D, null, 0 );
  49007. }
  49008. }
  49009. for ( let i = 0; i < textures.length; i ++ ) {
  49010. if ( isMRT ) {
  49011. // configure attachment for resolve
  49012. const { textureGPU } = this.get( textures[ i ] );
  49013. gl.framebufferRenderbuffer( gl.READ_FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.RENDERBUFFER, msaaRenderbuffers[ i ] );
  49014. gl.framebufferTexture2D( gl.DRAW_FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, textureGPU, 0 );
  49015. }
  49016. if ( renderContext.scissor ) {
  49017. const { x, y, width, height } = renderContext.scissorValue;
  49018. const viewY = renderContext.height - height - y;
  49019. gl.blitFramebuffer( x, viewY, x + width, viewY + height, x, viewY, x + width, viewY + height, mask, gl.NEAREST );
  49020. } else {
  49021. gl.blitFramebuffer( 0, 0, renderContext.width, renderContext.height, 0, 0, renderContext.width, renderContext.height, mask, gl.NEAREST );
  49022. }
  49023. }
  49024. if ( isMRT ) {
  49025. // restore attachments
  49026. for ( let i = 0; i < textures.length; i ++ ) {
  49027. const { textureGPU } = this.get( textures[ i ] );
  49028. gl.framebufferRenderbuffer( gl.READ_FRAMEBUFFER, gl.COLOR_ATTACHMENT0 + i, gl.RENDERBUFFER, msaaRenderbuffers[ i ] );
  49029. gl.framebufferTexture2D( gl.DRAW_FRAMEBUFFER, gl.COLOR_ATTACHMENT0 + i, gl.TEXTURE_2D, textureGPU, 0 );
  49030. }
  49031. }
  49032. if ( this._supportsInvalidateFramebuffer === true ) {
  49033. gl.invalidateFramebuffer( gl.READ_FRAMEBUFFER, renderTargetContextData.invalidationArray );
  49034. }
  49035. } else if ( renderTarget.resolveDepthBuffer === false && renderTargetContextData.framebuffers ) {
  49036. const fb = renderTargetContextData.framebuffers[ renderContext.getCacheKey() ];
  49037. state.bindFramebuffer( gl.DRAW_FRAMEBUFFER, fb );
  49038. gl.invalidateFramebuffer( gl.DRAW_FRAMEBUFFER, renderTargetContextData.depthInvalidationArray );
  49039. }
  49040. }
  49041. }
  49042. /**
  49043. * Returns `true` if the `WEBGL_multisampled_render_to_texture` extension
  49044. * should be used when MSAA is enabled.
  49045. *
  49046. * @private
  49047. * @param {RenderTarget} renderTarget - The render target that should be multisampled.
  49048. * @return {boolean} Whether to use the `WEBGL_multisampled_render_to_texture` extension for MSAA or not.
  49049. */
  49050. _useMultisampledExtension( renderTarget ) {
  49051. if ( renderTarget.multiview === true ) {
  49052. return true;
  49053. }
  49054. return renderTarget.samples > 0 && this.extensions.has( 'WEBGL_multisampled_render_to_texture' ) === true && renderTarget._autoAllocateDepthBuffer !== false;
  49055. }
  49056. /**
  49057. * Frees internal resources.
  49058. */
  49059. dispose() {
  49060. if ( this.textureUtils !== null ) this.textureUtils.dispose();
  49061. const extension = this.extensions.get( 'WEBGL_lose_context' );
  49062. if ( extension ) extension.loseContext();
  49063. this.renderer.domElement.removeEventListener( 'webglcontextlost', this._onContextLost );
  49064. }
  49065. }
  49066. const GPUPrimitiveTopology = {
  49067. PointList: 'point-list',
  49068. LineList: 'line-list',
  49069. LineStrip: 'line-strip',
  49070. TriangleList: 'triangle-list',
  49071. TriangleStrip: 'triangle-strip',
  49072. };
  49073. const GPUCompareFunction = {
  49074. Never: 'never',
  49075. Less: 'less',
  49076. Equal: 'equal',
  49077. LessEqual: 'less-equal',
  49078. Greater: 'greater',
  49079. NotEqual: 'not-equal',
  49080. GreaterEqual: 'greater-equal',
  49081. Always: 'always'
  49082. };
  49083. const GPUStoreOp = {
  49084. Store: 'store'};
  49085. const GPULoadOp = {
  49086. Load: 'load',
  49087. Clear: 'clear'
  49088. };
  49089. const GPUFrontFace = {
  49090. CCW: 'ccw',
  49091. CW: 'cw'
  49092. };
  49093. const GPUCullMode = {
  49094. None: 'none',
  49095. Back: 'back'
  49096. };
  49097. const GPUIndexFormat = {
  49098. Uint16: 'uint16',
  49099. Uint32: 'uint32'
  49100. };
  49101. const GPUTextureFormat = {
  49102. // 8-bit formats
  49103. R8Unorm: 'r8unorm',
  49104. R8Snorm: 'r8snorm',
  49105. R8Uint: 'r8uint',
  49106. R8Sint: 'r8sint',
  49107. // 16-bit formats
  49108. R16Uint: 'r16uint',
  49109. R16Sint: 'r16sint',
  49110. R16Float: 'r16float',
  49111. RG8Unorm: 'rg8unorm',
  49112. RG8Snorm: 'rg8snorm',
  49113. RG8Uint: 'rg8uint',
  49114. RG8Sint: 'rg8sint',
  49115. // 32-bit formats
  49116. R32Uint: 'r32uint',
  49117. R32Sint: 'r32sint',
  49118. R32Float: 'r32float',
  49119. RG16Uint: 'rg16uint',
  49120. RG16Sint: 'rg16sint',
  49121. RG16Float: 'rg16float',
  49122. RGBA8Unorm: 'rgba8unorm',
  49123. RGBA8UnormSRGB: 'rgba8unorm-srgb',
  49124. RGBA8Snorm: 'rgba8snorm',
  49125. RGBA8Uint: 'rgba8uint',
  49126. RGBA8Sint: 'rgba8sint',
  49127. BGRA8Unorm: 'bgra8unorm',
  49128. BGRA8UnormSRGB: 'bgra8unorm-srgb',
  49129. // Packed 32-bit formats
  49130. RGB9E5UFloat: 'rgb9e5ufloat',
  49131. RGB10A2Unorm: 'rgb10a2unorm',
  49132. RG11B10UFloat: 'rg11b10ufloat',
  49133. // 64-bit formats
  49134. RG32Uint: 'rg32uint',
  49135. RG32Sint: 'rg32sint',
  49136. RG32Float: 'rg32float',
  49137. RGBA16Uint: 'rgba16uint',
  49138. RGBA16Sint: 'rgba16sint',
  49139. RGBA16Float: 'rgba16float',
  49140. // 128-bit formats
  49141. RGBA32Uint: 'rgba32uint',
  49142. RGBA32Sint: 'rgba32sint',
  49143. RGBA32Float: 'rgba32float',
  49144. Depth16Unorm: 'depth16unorm',
  49145. Depth24Plus: 'depth24plus',
  49146. Depth24PlusStencil8: 'depth24plus-stencil8',
  49147. Depth32Float: 'depth32float',
  49148. // 'depth32float-stencil8' extension
  49149. Depth32FloatStencil8: 'depth32float-stencil8',
  49150. // BC compressed formats usable if 'texture-compression-bc' is both
  49151. // supported by the device/user agent and enabled in requestDevice.
  49152. BC1RGBAUnorm: 'bc1-rgba-unorm',
  49153. BC1RGBAUnormSRGB: 'bc1-rgba-unorm-srgb',
  49154. BC2RGBAUnorm: 'bc2-rgba-unorm',
  49155. BC2RGBAUnormSRGB: 'bc2-rgba-unorm-srgb',
  49156. BC3RGBAUnorm: 'bc3-rgba-unorm',
  49157. BC3RGBAUnormSRGB: 'bc3-rgba-unorm-srgb',
  49158. BC4RUnorm: 'bc4-r-unorm',
  49159. BC4RSnorm: 'bc4-r-snorm',
  49160. BC5RGUnorm: 'bc5-rg-unorm',
  49161. BC5RGSnorm: 'bc5-rg-snorm',
  49162. BC6HRGBUFloat: 'bc6h-rgb-ufloat',
  49163. BC6HRGBFloat: 'bc6h-rgb-float',
  49164. BC7RGBAUnorm: 'bc7-rgba-unorm',
  49165. BC7RGBAUnormSRGB: 'bc7-rgba-unorm-srgb',
  49166. // ETC2 compressed formats usable if 'texture-compression-etc2' is both
  49167. // supported by the device/user agent and enabled in requestDevice.
  49168. ETC2RGB8Unorm: 'etc2-rgb8unorm',
  49169. ETC2RGB8UnormSRGB: 'etc2-rgb8unorm-srgb',
  49170. ETC2RGB8A1Unorm: 'etc2-rgb8a1unorm',
  49171. ETC2RGB8A1UnormSRGB: 'etc2-rgb8a1unorm-srgb',
  49172. ETC2RGBA8Unorm: 'etc2-rgba8unorm',
  49173. ETC2RGBA8UnormSRGB: 'etc2-rgba8unorm-srgb',
  49174. EACR11Unorm: 'eac-r11unorm',
  49175. EACR11Snorm: 'eac-r11snorm',
  49176. EACRG11Unorm: 'eac-rg11unorm',
  49177. EACRG11Snorm: 'eac-rg11snorm',
  49178. // ASTC compressed formats usable if 'texture-compression-astc' is both
  49179. // supported by the device/user agent and enabled in requestDevice.
  49180. ASTC4x4Unorm: 'astc-4x4-unorm',
  49181. ASTC4x4UnormSRGB: 'astc-4x4-unorm-srgb',
  49182. ASTC5x4Unorm: 'astc-5x4-unorm',
  49183. ASTC5x4UnormSRGB: 'astc-5x4-unorm-srgb',
  49184. ASTC5x5Unorm: 'astc-5x5-unorm',
  49185. ASTC5x5UnormSRGB: 'astc-5x5-unorm-srgb',
  49186. ASTC6x5Unorm: 'astc-6x5-unorm',
  49187. ASTC6x5UnormSRGB: 'astc-6x5-unorm-srgb',
  49188. ASTC6x6Unorm: 'astc-6x6-unorm',
  49189. ASTC6x6UnormSRGB: 'astc-6x6-unorm-srgb',
  49190. ASTC8x5Unorm: 'astc-8x5-unorm',
  49191. ASTC8x5UnormSRGB: 'astc-8x5-unorm-srgb',
  49192. ASTC8x6Unorm: 'astc-8x6-unorm',
  49193. ASTC8x6UnormSRGB: 'astc-8x6-unorm-srgb',
  49194. ASTC8x8Unorm: 'astc-8x8-unorm',
  49195. ASTC8x8UnormSRGB: 'astc-8x8-unorm-srgb',
  49196. ASTC10x5Unorm: 'astc-10x5-unorm',
  49197. ASTC10x5UnormSRGB: 'astc-10x5-unorm-srgb',
  49198. ASTC10x6Unorm: 'astc-10x6-unorm',
  49199. ASTC10x6UnormSRGB: 'astc-10x6-unorm-srgb',
  49200. ASTC10x8Unorm: 'astc-10x8-unorm',
  49201. ASTC10x8UnormSRGB: 'astc-10x8-unorm-srgb',
  49202. ASTC10x10Unorm: 'astc-10x10-unorm',
  49203. ASTC10x10UnormSRGB: 'astc-10x10-unorm-srgb',
  49204. ASTC12x10Unorm: 'astc-12x10-unorm',
  49205. ASTC12x10UnormSRGB: 'astc-12x10-unorm-srgb',
  49206. ASTC12x12Unorm: 'astc-12x12-unorm',
  49207. ASTC12x12UnormSRGB: 'astc-12x12-unorm-srgb',
  49208. };
  49209. const GPUAddressMode = {
  49210. ClampToEdge: 'clamp-to-edge',
  49211. Repeat: 'repeat',
  49212. MirrorRepeat: 'mirror-repeat'
  49213. };
  49214. const GPUFilterMode = {
  49215. Linear: 'linear',
  49216. Nearest: 'nearest'
  49217. };
  49218. const GPUBlendFactor = {
  49219. Zero: 'zero',
  49220. One: 'one',
  49221. Src: 'src',
  49222. OneMinusSrc: 'one-minus-src',
  49223. SrcAlpha: 'src-alpha',
  49224. OneMinusSrcAlpha: 'one-minus-src-alpha',
  49225. Dst: 'dst',
  49226. OneMinusDst: 'one-minus-dst',
  49227. DstAlpha: 'dst-alpha',
  49228. OneMinusDstAlpha: 'one-minus-dst-alpha',
  49229. SrcAlphaSaturated: 'src-alpha-saturated',
  49230. Constant: 'constant',
  49231. OneMinusConstant: 'one-minus-constant'
  49232. };
  49233. const GPUBlendOperation = {
  49234. Add: 'add',
  49235. Subtract: 'subtract',
  49236. ReverseSubtract: 'reverse-subtract',
  49237. Min: 'min',
  49238. Max: 'max'
  49239. };
  49240. const GPUColorWriteFlags = {
  49241. None: 0,
  49242. All: 0xF
  49243. };
  49244. const GPUStencilOperation = {
  49245. Keep: 'keep',
  49246. Zero: 'zero',
  49247. Replace: 'replace',
  49248. Invert: 'invert',
  49249. IncrementClamp: 'increment-clamp',
  49250. DecrementClamp: 'decrement-clamp',
  49251. IncrementWrap: 'increment-wrap',
  49252. DecrementWrap: 'decrement-wrap'
  49253. };
  49254. const GPUBufferBindingType = {
  49255. Storage: 'storage',
  49256. ReadOnlyStorage: 'read-only-storage'
  49257. };
  49258. const GPUStorageTextureAccess = {
  49259. WriteOnly: 'write-only',
  49260. ReadOnly: 'read-only',
  49261. ReadWrite: 'read-write',
  49262. };
  49263. const GPUSamplerBindingType = {
  49264. NonFiltering: 'non-filtering',
  49265. Comparison: 'comparison'
  49266. };
  49267. const GPUTextureSampleType = {
  49268. Float: 'float',
  49269. UnfilterableFloat: 'unfilterable-float',
  49270. Depth: 'depth',
  49271. SInt: 'sint',
  49272. UInt: 'uint'
  49273. };
  49274. const GPUTextureDimension = {
  49275. TwoD: '2d',
  49276. ThreeD: '3d'
  49277. };
  49278. const GPUTextureViewDimension = {
  49279. TwoD: '2d',
  49280. TwoDArray: '2d-array',
  49281. Cube: 'cube',
  49282. ThreeD: '3d'
  49283. };
  49284. const GPUTextureAspect = {
  49285. All: 'all'};
  49286. const GPUInputStepMode = {
  49287. Vertex: 'vertex',
  49288. Instance: 'instance'
  49289. };
  49290. const GPUFeatureName = {
  49291. CoreFeaturesAndLimits: 'core-features-and-limits',
  49292. DepthClipControl: 'depth-clip-control',
  49293. Depth32FloatStencil8: 'depth32float-stencil8',
  49294. TextureCompressionBC: 'texture-compression-bc',
  49295. TextureCompressionBCSliced3D: 'texture-compression-bc-sliced-3d',
  49296. TextureCompressionETC2: 'texture-compression-etc2',
  49297. TextureCompressionASTC: 'texture-compression-astc',
  49298. TextureCompressionASTCSliced3D: 'texture-compression-astc-sliced-3d',
  49299. TimestampQuery: 'timestamp-query',
  49300. IndirectFirstInstance: 'indirect-first-instance',
  49301. ShaderF16: 'shader-f16',
  49302. RG11B10UFloat: 'rg11b10ufloat-renderable',
  49303. BGRA8UNormStorage: 'bgra8unorm-storage',
  49304. Float32Filterable: 'float32-filterable',
  49305. Float32Blendable: 'float32-blendable',
  49306. ClipDistances: 'clip-distances',
  49307. DualSourceBlending: 'dual-source-blending',
  49308. Subgroups: 'subgroups',
  49309. TextureFormatsTier1: 'texture-formats-tier1',
  49310. TextureFormatsTier2: 'texture-formats-tier2'
  49311. };
  49312. const GPUFeatureMap = {
  49313. 'texture-compression-s3tc': 'texture-compression-bc',
  49314. 'texture-compression-etc1': 'texture-compression-etc2'
  49315. };
  49316. /**
  49317. * A special form of sampler binding type.
  49318. * It's texture value is managed by a node object.
  49319. *
  49320. * @private
  49321. * @augments Sampler
  49322. */
  49323. class NodeSampler extends Sampler {
  49324. /**
  49325. * Constructs a new node-based sampler.
  49326. *
  49327. * @param {string} name - The samplers's name.
  49328. * @param {TextureNode} textureNode - The texture node.
  49329. * @param {UniformGroupNode} groupNode - The uniform group node.
  49330. */
  49331. constructor( name, textureNode, groupNode ) {
  49332. super( name, textureNode ? textureNode.value : null );
  49333. /**
  49334. * The texture node.
  49335. *
  49336. * @type {TextureNode}
  49337. */
  49338. this.textureNode = textureNode;
  49339. /**
  49340. * The uniform group node.
  49341. *
  49342. * @type {UniformGroupNode}
  49343. */
  49344. this.groupNode = groupNode;
  49345. }
  49346. /**
  49347. * Updates the texture value of this sampler.
  49348. *
  49349. * @return {boolean} Whether the sampler needs an update or not.
  49350. */
  49351. update() {
  49352. const { textureNode } = this;
  49353. if ( this.texture !== textureNode.value ) {
  49354. this.texture = textureNode.value;
  49355. return true;
  49356. }
  49357. return super.update();
  49358. }
  49359. }
  49360. /**
  49361. * Represents a storage buffer binding type.
  49362. *
  49363. * @private
  49364. * @augments Buffer
  49365. */
  49366. class StorageBuffer extends Buffer {
  49367. /**
  49368. * Constructs a new uniform buffer.
  49369. *
  49370. * @param {string} name - The buffer's name.
  49371. * @param {BufferAttribute} attribute - The buffer attribute.
  49372. */
  49373. constructor( name, attribute ) {
  49374. super( name, attribute ? attribute.array : null );
  49375. /**
  49376. * This flag can be used for type testing.
  49377. *
  49378. * @type {BufferAttribute}
  49379. */
  49380. this.attribute = attribute;
  49381. /**
  49382. * This flag can be used for type testing.
  49383. *
  49384. * @type {boolean}
  49385. * @readonly
  49386. * @default true
  49387. */
  49388. this.isStorageBuffer = true;
  49389. }
  49390. }
  49391. let _id = 0;
  49392. /**
  49393. * A special form of storage buffer binding type.
  49394. * It's buffer value is managed by a node object.
  49395. *
  49396. * @private
  49397. * @augments StorageBuffer
  49398. */
  49399. class NodeStorageBuffer extends StorageBuffer {
  49400. /**
  49401. * Constructs a new node-based storage buffer.
  49402. *
  49403. * @param {StorageBufferNode} nodeUniform - The storage buffer node.
  49404. * @param {UniformGroupNode} groupNode - The uniform group node.
  49405. */
  49406. constructor( nodeUniform, groupNode ) {
  49407. super( 'StorageBuffer_' + _id ++, nodeUniform ? nodeUniform.value : null );
  49408. /**
  49409. * The node uniform.
  49410. *
  49411. * @type {StorageBufferNode}
  49412. */
  49413. this.nodeUniform = nodeUniform;
  49414. /**
  49415. * The access type.
  49416. *
  49417. * @type {string}
  49418. */
  49419. this.access = nodeUniform ? nodeUniform.access : NodeAccess.READ_WRITE;
  49420. /**
  49421. * The uniform group node.
  49422. *
  49423. * @type {UniformGroupNode}
  49424. */
  49425. this.groupNode = groupNode;
  49426. }
  49427. /**
  49428. * The storage buffer.
  49429. *
  49430. * @type {BufferAttribute}
  49431. */
  49432. get buffer() {
  49433. return this.nodeUniform.value;
  49434. }
  49435. }
  49436. /**
  49437. * A WebGPU backend utility module used by {@link WebGPUTextureUtils}.
  49438. *
  49439. * @private
  49440. */
  49441. class WebGPUTexturePassUtils extends DataMap {
  49442. /**
  49443. * Constructs a new utility object.
  49444. *
  49445. * @param {GPUDevice} device - The WebGPU device.
  49446. */
  49447. constructor( device ) {
  49448. super();
  49449. /**
  49450. * The WebGPU device.
  49451. *
  49452. * @type {GPUDevice}
  49453. */
  49454. this.device = device;
  49455. const mipmapVertexSource = `
  49456. struct VarysStruct {
  49457. @builtin( position ) Position: vec4<f32>,
  49458. @location( 0 ) vTex : vec2<f32>
  49459. };
  49460. @vertex
  49461. fn main( @builtin( vertex_index ) vertexIndex : u32 ) -> VarysStruct {
  49462. var Varys : VarysStruct;
  49463. var pos = array< vec2<f32>, 4 >(
  49464. vec2<f32>( -1.0, 1.0 ),
  49465. vec2<f32>( 1.0, 1.0 ),
  49466. vec2<f32>( -1.0, -1.0 ),
  49467. vec2<f32>( 1.0, -1.0 )
  49468. );
  49469. var tex = array< vec2<f32>, 4 >(
  49470. vec2<f32>( 0.0, 0.0 ),
  49471. vec2<f32>( 1.0, 0.0 ),
  49472. vec2<f32>( 0.0, 1.0 ),
  49473. vec2<f32>( 1.0, 1.0 )
  49474. );
  49475. Varys.vTex = tex[ vertexIndex ];
  49476. Varys.Position = vec4<f32>( pos[ vertexIndex ], 0.0, 1.0 );
  49477. return Varys;
  49478. }
  49479. `;
  49480. const mipmapFragmentSource = `
  49481. @group( 0 ) @binding( 0 )
  49482. var imgSampler : sampler;
  49483. @group( 0 ) @binding( 1 )
  49484. var img : texture_2d<f32>;
  49485. @fragment
  49486. fn main( @location( 0 ) vTex : vec2<f32> ) -> @location( 0 ) vec4<f32> {
  49487. return textureSample( img, imgSampler, vTex );
  49488. }
  49489. `;
  49490. const flipYFragmentSource = `
  49491. @group( 0 ) @binding( 0 )
  49492. var imgSampler : sampler;
  49493. @group( 0 ) @binding( 1 )
  49494. var img : texture_2d<f32>;
  49495. @fragment
  49496. fn main( @location( 0 ) vTex : vec2<f32> ) -> @location( 0 ) vec4<f32> {
  49497. return textureSample( img, imgSampler, vec2( vTex.x, 1.0 - vTex.y ) );
  49498. }
  49499. `;
  49500. /**
  49501. * The mipmap GPU sampler.
  49502. *
  49503. * @type {GPUSampler}
  49504. */
  49505. this.mipmapSampler = device.createSampler( { minFilter: GPUFilterMode.Linear } );
  49506. /**
  49507. * The flipY GPU sampler.
  49508. *
  49509. * @type {GPUSampler}
  49510. */
  49511. this.flipYSampler = device.createSampler( { minFilter: GPUFilterMode.Nearest } ); //@TODO?: Consider using textureLoad()
  49512. /**
  49513. * A cache for GPU render pipelines used for copy/transfer passes.
  49514. * Every texture format requires a unique pipeline.
  49515. *
  49516. * @type {Object<string,GPURenderPipeline>}
  49517. */
  49518. this.transferPipelines = {};
  49519. /**
  49520. * A cache for GPU render pipelines used for flipY passes.
  49521. * Every texture format requires a unique pipeline.
  49522. *
  49523. * @type {Object<string,GPURenderPipeline>}
  49524. */
  49525. this.flipYPipelines = {};
  49526. /**
  49527. * The mipmap vertex shader module.
  49528. *
  49529. * @type {GPUShaderModule}
  49530. */
  49531. this.mipmapVertexShaderModule = device.createShaderModule( {
  49532. label: 'mipmapVertex',
  49533. code: mipmapVertexSource
  49534. } );
  49535. /**
  49536. * The mipmap fragment shader module.
  49537. *
  49538. * @type {GPUShaderModule}
  49539. */
  49540. this.mipmapFragmentShaderModule = device.createShaderModule( {
  49541. label: 'mipmapFragment',
  49542. code: mipmapFragmentSource
  49543. } );
  49544. /**
  49545. * The flipY fragment shader module.
  49546. *
  49547. * @type {GPUShaderModule}
  49548. */
  49549. this.flipYFragmentShaderModule = device.createShaderModule( {
  49550. label: 'flipYFragment',
  49551. code: flipYFragmentSource
  49552. } );
  49553. }
  49554. /**
  49555. * Returns a render pipeline for the internal copy render pass. The pass
  49556. * requires a unique render pipeline for each texture format.
  49557. *
  49558. * @param {string} format - The GPU texture format
  49559. * @return {GPURenderPipeline} The GPU render pipeline.
  49560. */
  49561. getTransferPipeline( format ) {
  49562. let pipeline = this.transferPipelines[ format ];
  49563. if ( pipeline === undefined ) {
  49564. pipeline = this.device.createRenderPipeline( {
  49565. label: `mipmap-${ format }`,
  49566. vertex: {
  49567. module: this.mipmapVertexShaderModule,
  49568. entryPoint: 'main'
  49569. },
  49570. fragment: {
  49571. module: this.mipmapFragmentShaderModule,
  49572. entryPoint: 'main',
  49573. targets: [ { format } ]
  49574. },
  49575. primitive: {
  49576. topology: GPUPrimitiveTopology.TriangleStrip,
  49577. stripIndexFormat: GPUIndexFormat.Uint32
  49578. },
  49579. layout: 'auto'
  49580. } );
  49581. this.transferPipelines[ format ] = pipeline;
  49582. }
  49583. return pipeline;
  49584. }
  49585. /**
  49586. * Returns a render pipeline for the flipY render pass. The pass
  49587. * requires a unique render pipeline for each texture format.
  49588. *
  49589. * @param {string} format - The GPU texture format
  49590. * @return {GPURenderPipeline} The GPU render pipeline.
  49591. */
  49592. getFlipYPipeline( format ) {
  49593. let pipeline = this.flipYPipelines[ format ];
  49594. if ( pipeline === undefined ) {
  49595. pipeline = this.device.createRenderPipeline( {
  49596. label: `flipY-${ format }`,
  49597. vertex: {
  49598. module: this.mipmapVertexShaderModule,
  49599. entryPoint: 'main'
  49600. },
  49601. fragment: {
  49602. module: this.flipYFragmentShaderModule,
  49603. entryPoint: 'main',
  49604. targets: [ { format } ]
  49605. },
  49606. primitive: {
  49607. topology: GPUPrimitiveTopology.TriangleStrip,
  49608. stripIndexFormat: GPUIndexFormat.Uint32
  49609. },
  49610. layout: 'auto'
  49611. } );
  49612. this.flipYPipelines[ format ] = pipeline;
  49613. }
  49614. return pipeline;
  49615. }
  49616. /**
  49617. * Flip the contents of the given GPU texture along its vertical axis.
  49618. *
  49619. * @param {GPUTexture} textureGPU - The GPU texture object.
  49620. * @param {Object} textureGPUDescriptor - The texture descriptor.
  49621. * @param {number} [baseArrayLayer=0] - The index of the first array layer accessible to the texture view.
  49622. */
  49623. flipY( textureGPU, textureGPUDescriptor, baseArrayLayer = 0 ) {
  49624. const format = textureGPUDescriptor.format;
  49625. const { width, height } = textureGPUDescriptor.size;
  49626. const transferPipeline = this.getTransferPipeline( format );
  49627. const flipYPipeline = this.getFlipYPipeline( format );
  49628. const tempTexture = this.device.createTexture( {
  49629. size: { width, height, depthOrArrayLayers: 1 },
  49630. format,
  49631. usage: GPUTextureUsage.RENDER_ATTACHMENT | GPUTextureUsage.TEXTURE_BINDING
  49632. } );
  49633. const srcView = textureGPU.createView( {
  49634. baseMipLevel: 0,
  49635. mipLevelCount: 1,
  49636. dimension: GPUTextureViewDimension.TwoD,
  49637. baseArrayLayer
  49638. } );
  49639. const dstView = tempTexture.createView( {
  49640. baseMipLevel: 0,
  49641. mipLevelCount: 1,
  49642. dimension: GPUTextureViewDimension.TwoD,
  49643. baseArrayLayer: 0
  49644. } );
  49645. const commandEncoder = this.device.createCommandEncoder( {} );
  49646. const pass = ( pipeline, sourceView, destinationView ) => {
  49647. const bindGroupLayout = pipeline.getBindGroupLayout( 0 ); // @TODO: Consider making this static.
  49648. const bindGroup = this.device.createBindGroup( {
  49649. layout: bindGroupLayout,
  49650. entries: [ {
  49651. binding: 0,
  49652. resource: this.flipYSampler
  49653. }, {
  49654. binding: 1,
  49655. resource: sourceView
  49656. } ]
  49657. } );
  49658. const passEncoder = commandEncoder.beginRenderPass( {
  49659. colorAttachments: [ {
  49660. view: destinationView,
  49661. loadOp: GPULoadOp.Clear,
  49662. storeOp: GPUStoreOp.Store,
  49663. clearValue: [ 0, 0, 0, 0 ]
  49664. } ]
  49665. } );
  49666. passEncoder.setPipeline( pipeline );
  49667. passEncoder.setBindGroup( 0, bindGroup );
  49668. passEncoder.draw( 4, 1, 0, 0 );
  49669. passEncoder.end();
  49670. };
  49671. pass( transferPipeline, srcView, dstView );
  49672. pass( flipYPipeline, dstView, srcView );
  49673. this.device.queue.submit( [ commandEncoder.finish() ] );
  49674. tempTexture.destroy();
  49675. }
  49676. /**
  49677. * Generates mipmaps for the given GPU texture.
  49678. *
  49679. * @param {GPUTexture} textureGPU - The GPU texture object.
  49680. * @param {Object} textureGPUDescriptor - The texture descriptor.
  49681. * @param {number} [baseArrayLayer=0] - The index of the first array layer accessible to the texture view.
  49682. * @param {?GPUCommandEncoder} [encoder=null] - An optional command encoder used to generate mipmaps.
  49683. */
  49684. generateMipmaps( textureGPU, textureGPUDescriptor, baseArrayLayer = 0, encoder = null ) {
  49685. const textureData = this.get( textureGPU );
  49686. if ( textureData.layers === undefined ) {
  49687. textureData.layers = [];
  49688. }
  49689. const passes = textureData.layers[ baseArrayLayer ] || this._mipmapCreateBundles( textureGPU, textureGPUDescriptor, baseArrayLayer );
  49690. const commandEncoder = encoder || this.device.createCommandEncoder( { label: 'mipmapEncoder' } );
  49691. this._mipmapRunBundles( commandEncoder, passes );
  49692. if ( encoder === null ) this.device.queue.submit( [ commandEncoder.finish() ] );
  49693. textureData.layers[ baseArrayLayer ] = passes;
  49694. }
  49695. /**
  49696. * Since multiple copy render passes are required to generate mipmaps, the passes
  49697. * are managed as render bundles to improve performance.
  49698. *
  49699. * @param {GPUTexture} textureGPU - The GPU texture object.
  49700. * @param {Object} textureGPUDescriptor - The texture descriptor.
  49701. * @param {number} baseArrayLayer - The index of the first array layer accessible to the texture view.
  49702. * @return {Array<Object>} An array of render bundles.
  49703. */
  49704. _mipmapCreateBundles( textureGPU, textureGPUDescriptor, baseArrayLayer ) {
  49705. const pipeline = this.getTransferPipeline( textureGPUDescriptor.format );
  49706. const bindGroupLayout = pipeline.getBindGroupLayout( 0 ); // @TODO: Consider making this static.
  49707. let srcView = textureGPU.createView( {
  49708. baseMipLevel: 0,
  49709. mipLevelCount: 1,
  49710. dimension: GPUTextureViewDimension.TwoD,
  49711. baseArrayLayer
  49712. } );
  49713. const passes = [];
  49714. for ( let i = 1; i < textureGPUDescriptor.mipLevelCount; i ++ ) {
  49715. const bindGroup = this.device.createBindGroup( {
  49716. layout: bindGroupLayout,
  49717. entries: [ {
  49718. binding: 0,
  49719. resource: this.mipmapSampler
  49720. }, {
  49721. binding: 1,
  49722. resource: srcView
  49723. } ]
  49724. } );
  49725. const dstView = textureGPU.createView( {
  49726. baseMipLevel: i,
  49727. mipLevelCount: 1,
  49728. dimension: GPUTextureViewDimension.TwoD,
  49729. baseArrayLayer
  49730. } );
  49731. const passDescriptor = {
  49732. colorAttachments: [ {
  49733. view: dstView,
  49734. loadOp: GPULoadOp.Clear,
  49735. storeOp: GPUStoreOp.Store,
  49736. clearValue: [ 0, 0, 0, 0 ]
  49737. } ]
  49738. };
  49739. const passEncoder = this.device.createRenderBundleEncoder( {
  49740. colorFormats: [ textureGPUDescriptor.format ]
  49741. } );
  49742. passEncoder.setPipeline( pipeline );
  49743. passEncoder.setBindGroup( 0, bindGroup );
  49744. passEncoder.draw( 4, 1, 0, 0 );
  49745. passes.push( {
  49746. renderBundles: [ passEncoder.finish() ],
  49747. passDescriptor
  49748. } );
  49749. srcView = dstView;
  49750. }
  49751. return passes;
  49752. }
  49753. /**
  49754. * Executes the render bundles.
  49755. *
  49756. * @param {GPUCommandEncoder} commandEncoder - The GPU command encoder.
  49757. * @param {Array<Object>} passes - An array of render bundles.
  49758. */
  49759. _mipmapRunBundles( commandEncoder, passes ) {
  49760. const levels = passes.length;
  49761. for ( let i = 0; i < levels; i ++ ) {
  49762. const pass = passes[ i ];
  49763. const passEncoder = commandEncoder.beginRenderPass( pass.passDescriptor );
  49764. passEncoder.executeBundles( pass.renderBundles );
  49765. passEncoder.end();
  49766. }
  49767. }
  49768. }
  49769. const _compareToWebGPU = {
  49770. [ NeverCompare ]: 'never',
  49771. [ LessCompare ]: 'less',
  49772. [ EqualCompare ]: 'equal',
  49773. [ LessEqualCompare ]: 'less-equal',
  49774. [ GreaterCompare ]: 'greater',
  49775. [ GreaterEqualCompare ]: 'greater-equal',
  49776. [ AlwaysCompare ]: 'always',
  49777. [ NotEqualCompare ]: 'not-equal'
  49778. };
  49779. const _flipMap = [ 0, 1, 3, 2, 4, 5 ];
  49780. /**
  49781. * A WebGPU backend utility module for managing textures.
  49782. *
  49783. * @private
  49784. */
  49785. class WebGPUTextureUtils {
  49786. /**
  49787. * Constructs a new utility object.
  49788. *
  49789. * @param {WebGPUBackend} backend - The WebGPU backend.
  49790. */
  49791. constructor( backend ) {
  49792. /**
  49793. * A reference to the WebGPU backend.
  49794. *
  49795. * @type {WebGPUBackend}
  49796. */
  49797. this.backend = backend;
  49798. /**
  49799. * A reference to the pass utils.
  49800. *
  49801. * @type {?WebGPUTexturePassUtils}
  49802. * @default null
  49803. */
  49804. this._passUtils = null;
  49805. /**
  49806. * A dictionary for managing default textures. The key
  49807. * is the texture format, the value the texture object.
  49808. *
  49809. * @type {Object<string,Texture>}
  49810. */
  49811. this.defaultTexture = {};
  49812. /**
  49813. * A dictionary for managing default cube textures. The key
  49814. * is the texture format, the value the texture object.
  49815. *
  49816. * @type {Object<string,CubeTexture>}
  49817. */
  49818. this.defaultCubeTexture = {};
  49819. /**
  49820. * A default video frame.
  49821. *
  49822. * @type {?VideoFrame}
  49823. * @default null
  49824. */
  49825. this.defaultVideoFrame = null;
  49826. /**
  49827. * A cache of shared texture samplers.
  49828. *
  49829. * @type {Map<string, Object>}
  49830. */
  49831. this._samplerCache = new Map();
  49832. }
  49833. /**
  49834. * Creates a GPU sampler for the given texture.
  49835. *
  49836. * @param {Texture} texture - The texture to create the sampler for.
  49837. * @return {string} The current sampler key.
  49838. */
  49839. updateSampler( texture ) {
  49840. const backend = this.backend;
  49841. const samplerKey = texture.minFilter + '-' + texture.magFilter + '-' +
  49842. texture.wrapS + '-' + texture.wrapT + '-' + ( texture.wrapR || '0' ) + '-' +
  49843. texture.anisotropy + '-' + ( texture.compareFunction || 0 );
  49844. let samplerData = this._samplerCache.get( samplerKey );
  49845. if ( samplerData === undefined ) {
  49846. const samplerDescriptorGPU = {
  49847. addressModeU: this._convertAddressMode( texture.wrapS ),
  49848. addressModeV: this._convertAddressMode( texture.wrapT ),
  49849. addressModeW: this._convertAddressMode( texture.wrapR ),
  49850. magFilter: this._convertFilterMode( texture.magFilter ),
  49851. minFilter: this._convertFilterMode( texture.minFilter ),
  49852. mipmapFilter: this._convertFilterMode( texture.minFilter ),
  49853. maxAnisotropy: 1
  49854. };
  49855. // anisotropy can only be used when all filter modes are set to linear.
  49856. if ( samplerDescriptorGPU.magFilter === GPUFilterMode.Linear && samplerDescriptorGPU.minFilter === GPUFilterMode.Linear && samplerDescriptorGPU.mipmapFilter === GPUFilterMode.Linear ) {
  49857. samplerDescriptorGPU.maxAnisotropy = texture.anisotropy;
  49858. }
  49859. if ( texture.isDepthTexture && texture.compareFunction !== null ) {
  49860. samplerDescriptorGPU.compare = _compareToWebGPU[ texture.compareFunction ];
  49861. }
  49862. const sampler = backend.device.createSampler( samplerDescriptorGPU );
  49863. samplerData = { sampler, usedTimes: 0 };
  49864. this._samplerCache.set( samplerKey, samplerData );
  49865. }
  49866. const textureData = backend.get( texture );
  49867. if ( textureData.sampler !== samplerData.sampler ) {
  49868. // check if previous sampler is unused so it can be deleted
  49869. if ( textureData.sampler !== undefined ) {
  49870. const oldSamplerData = this._samplerCache.get( textureData.samplerKey );
  49871. oldSamplerData.usedTimes --;
  49872. if ( oldSamplerData.usedTimes === 0 ) {
  49873. this._samplerCache.delete( textureData.samplerKey );
  49874. }
  49875. }
  49876. // update to new sampler data
  49877. textureData.samplerKey = samplerKey;
  49878. textureData.sampler = samplerData.sampler;
  49879. samplerData.usedTimes ++;
  49880. }
  49881. return samplerKey;
  49882. }
  49883. /**
  49884. * Creates a default texture for the given texture that can be used
  49885. * as a placeholder until the actual texture is ready for usage.
  49886. *
  49887. * @param {Texture} texture - The texture to create a default texture for.
  49888. */
  49889. createDefaultTexture( texture ) {
  49890. let textureGPU;
  49891. const format = getFormat( texture );
  49892. if ( texture.isCubeTexture ) {
  49893. textureGPU = this._getDefaultCubeTextureGPU( format );
  49894. } else {
  49895. textureGPU = this._getDefaultTextureGPU( format );
  49896. }
  49897. this.backend.get( texture ).texture = textureGPU;
  49898. }
  49899. /**
  49900. * Defines a texture on the GPU for the given texture object.
  49901. *
  49902. * @param {Texture} texture - The texture.
  49903. * @param {Object} [options={}] - Optional configuration parameter.
  49904. */
  49905. createTexture( texture, options = {} ) {
  49906. const backend = this.backend;
  49907. const textureData = backend.get( texture );
  49908. if ( textureData.initialized ) {
  49909. throw new Error( 'WebGPUTextureUtils: Texture already initialized.' );
  49910. }
  49911. if ( texture.isExternalTexture ) {
  49912. textureData.texture = texture.sourceTexture;
  49913. textureData.initialized = true;
  49914. return;
  49915. }
  49916. if ( options.needsMipmaps === undefined ) options.needsMipmaps = false;
  49917. if ( options.levels === undefined ) options.levels = 1;
  49918. if ( options.depth === undefined ) options.depth = 1;
  49919. const { width, height, depth, levels } = options;
  49920. if ( texture.isFramebufferTexture ) {
  49921. if ( options.renderTarget ) {
  49922. options.format = this.backend.utils.getCurrentColorFormat( options.renderTarget );
  49923. } else {
  49924. options.format = this.backend.utils.getPreferredCanvasFormat();
  49925. }
  49926. }
  49927. const dimension = this._getDimension( texture );
  49928. const format = texture.internalFormat || options.format || getFormat( texture, backend.device );
  49929. textureData.format = format;
  49930. const { samples, primarySamples, isMSAA } = backend.utils.getTextureSampleData( texture );
  49931. let usage = GPUTextureUsage.TEXTURE_BINDING | GPUTextureUsage.COPY_DST | GPUTextureUsage.COPY_SRC;
  49932. if ( texture.isStorageTexture === true ) {
  49933. usage |= GPUTextureUsage.STORAGE_BINDING;
  49934. }
  49935. if ( texture.isCompressedTexture !== true && texture.isCompressedArrayTexture !== true && format !== GPUTextureFormat.RGB9E5UFloat ) {
  49936. usage |= GPUTextureUsage.RENDER_ATTACHMENT;
  49937. }
  49938. const textureDescriptorGPU = {
  49939. label: texture.name,
  49940. size: {
  49941. width: width,
  49942. height: height,
  49943. depthOrArrayLayers: depth,
  49944. },
  49945. mipLevelCount: levels,
  49946. sampleCount: primarySamples,
  49947. dimension: dimension,
  49948. format: format,
  49949. usage: usage
  49950. };
  49951. // texture creation
  49952. if ( format === undefined ) {
  49953. warn( 'WebGPURenderer: Texture format not supported.' );
  49954. this.createDefaultTexture( texture );
  49955. return;
  49956. }
  49957. if ( texture.isCubeTexture ) {
  49958. textureDescriptorGPU.textureBindingViewDimension = GPUTextureViewDimension.Cube;
  49959. }
  49960. textureData.texture = backend.device.createTexture( textureDescriptorGPU );
  49961. if ( isMSAA ) {
  49962. const msaaTextureDescriptorGPU = Object.assign( {}, textureDescriptorGPU );
  49963. msaaTextureDescriptorGPU.label = msaaTextureDescriptorGPU.label + '-msaa';
  49964. msaaTextureDescriptorGPU.sampleCount = samples;
  49965. msaaTextureDescriptorGPU.mipLevelCount = 1; // See https://www.w3.org/TR/webgpu/#texture-creation
  49966. textureData.msaaTexture = backend.device.createTexture( msaaTextureDescriptorGPU );
  49967. }
  49968. textureData.initialized = true;
  49969. textureData.textureDescriptorGPU = textureDescriptorGPU;
  49970. }
  49971. /**
  49972. * Destroys the GPU data for the given texture object.
  49973. *
  49974. * @param {Texture} texture - The texture.
  49975. * @param {boolean} [isDefaultTexture=false] - Whether the texture uses a default GPU texture or not.
  49976. */
  49977. destroyTexture( texture, isDefaultTexture = false ) {
  49978. const backend = this.backend;
  49979. const textureData = backend.get( texture );
  49980. if ( textureData.texture !== undefined && isDefaultTexture === false ) textureData.texture.destroy();
  49981. if ( textureData.msaaTexture !== undefined ) textureData.msaaTexture.destroy();
  49982. backend.delete( texture );
  49983. }
  49984. /**
  49985. * Generates mipmaps for the given texture.
  49986. *
  49987. * @param {Texture} texture - The texture.
  49988. * @param {?GPUCommandEncoder} [encoder=null] - An optional command encoder used to generate mipmaps.
  49989. */
  49990. generateMipmaps( texture, encoder = null ) {
  49991. const textureData = this.backend.get( texture );
  49992. if ( texture.isCubeTexture ) {
  49993. for ( let i = 0; i < 6; i ++ ) {
  49994. this._generateMipmaps( textureData.texture, textureData.textureDescriptorGPU, i, encoder );
  49995. }
  49996. } else {
  49997. const depth = texture.image.depth || 1;
  49998. for ( let i = 0; i < depth; i ++ ) {
  49999. this._generateMipmaps( textureData.texture, textureData.textureDescriptorGPU, i, encoder );
  50000. }
  50001. }
  50002. }
  50003. /**
  50004. * Returns the color buffer representing the color
  50005. * attachment of the default framebuffer.
  50006. *
  50007. * @return {GPUTexture} The color buffer.
  50008. */
  50009. getColorBuffer() {
  50010. const backend = this.backend;
  50011. const canvasTarget = backend.renderer.getCanvasTarget();
  50012. const { width, height } = backend.getDrawingBufferSize();
  50013. const samples = backend.renderer.currentSamples;
  50014. const colorTexture = canvasTarget.colorTexture;
  50015. const colorTextureData = backend.get( colorTexture );
  50016. if ( colorTexture.width === width && colorTexture.height === height && colorTexture.samples === samples ) {
  50017. return colorTextureData.texture;
  50018. }
  50019. // recreate
  50020. let colorBuffer = colorTextureData.texture;
  50021. if ( colorBuffer ) colorBuffer.destroy();
  50022. colorBuffer = backend.device.createTexture( {
  50023. label: 'colorBuffer',
  50024. size: {
  50025. width: width,
  50026. height: height,
  50027. depthOrArrayLayers: 1
  50028. },
  50029. sampleCount: backend.utils.getSampleCount( backend.renderer.currentSamples ),
  50030. format: backend.utils.getPreferredCanvasFormat(),
  50031. usage: GPUTextureUsage.RENDER_ATTACHMENT | GPUTextureUsage.COPY_SRC
  50032. } );
  50033. //
  50034. colorTexture.source.width = width;
  50035. colorTexture.source.height = height;
  50036. colorTexture.samples = samples;
  50037. colorTextureData.texture = colorBuffer;
  50038. return colorBuffer;
  50039. }
  50040. /**
  50041. * Returns the depth buffer representing the depth
  50042. * attachment of the default framebuffer.
  50043. *
  50044. * @param {boolean} [depth=true] - Whether depth is enabled or not.
  50045. * @param {boolean} [stencil=false] - Whether stencil is enabled or not.
  50046. * @return {GPUTexture} The depth buffer.
  50047. */
  50048. getDepthBuffer( depth = true, stencil = false ) {
  50049. const backend = this.backend;
  50050. const canvasTarget = backend.renderer.getCanvasTarget();
  50051. const { width, height } = backend.getDrawingBufferSize();
  50052. const samples = backend.renderer.currentSamples;
  50053. const depthTexture = canvasTarget.depthTexture;
  50054. if ( depthTexture.width === width &&
  50055. depthTexture.height === height &&
  50056. depthTexture.samples === samples &&
  50057. depthTexture.depth === depth &&
  50058. depthTexture.stencil === stencil ) {
  50059. return backend.get( depthTexture ).texture;
  50060. }
  50061. //
  50062. const depthTextureGPU = backend.get( depthTexture ).texture;
  50063. let format, type;
  50064. if ( stencil ) {
  50065. format = DepthStencilFormat;
  50066. type = UnsignedInt248Type;
  50067. } else if ( depth ) {
  50068. format = DepthFormat;
  50069. type = UnsignedIntType;
  50070. }
  50071. if ( depthTextureGPU !== undefined ) {
  50072. if ( depthTexture.image.width === width && depthTexture.image.height === height && depthTexture.format === format && depthTexture.type === type && depthTexture.samples === samples ) {
  50073. return depthTextureGPU;
  50074. }
  50075. this.destroyTexture( depthTexture );
  50076. }
  50077. // recreate
  50078. depthTexture.name = 'depthBuffer';
  50079. depthTexture.format = format;
  50080. depthTexture.type = type;
  50081. depthTexture.image.width = width;
  50082. depthTexture.image.height = height;
  50083. depthTexture.samples = samples;
  50084. this.createTexture( depthTexture, { width, height } );
  50085. return backend.get( depthTexture ).texture;
  50086. }
  50087. /**
  50088. * Uploads the updated texture data to the GPU.
  50089. *
  50090. * @param {Texture} texture - The texture.
  50091. * @param {Object} [options={}] - Optional configuration parameter.
  50092. */
  50093. updateTexture( texture, options ) {
  50094. const textureData = this.backend.get( texture );
  50095. const mipmaps = texture.mipmaps;
  50096. const { textureDescriptorGPU } = textureData;
  50097. if ( texture.isRenderTargetTexture || ( textureDescriptorGPU === undefined /* unsupported texture format */ ) )
  50098. return;
  50099. // transfer texture data
  50100. if ( texture.isDataTexture ) {
  50101. if ( mipmaps.length > 0 ) {
  50102. for ( let i = 0, il = mipmaps.length; i < il; i ++ ) {
  50103. const mipmap = mipmaps[ i ];
  50104. this._copyBufferToTexture( mipmap, textureData.texture, textureDescriptorGPU, 0, texture.flipY, 0, i );
  50105. }
  50106. } else {
  50107. this._copyBufferToTexture( options.image, textureData.texture, textureDescriptorGPU, 0, texture.flipY );
  50108. }
  50109. } else if ( texture.isArrayTexture || texture.isDataArrayTexture || texture.isData3DTexture ) {
  50110. for ( let i = 0; i < options.image.depth; i ++ ) {
  50111. this._copyBufferToTexture( options.image, textureData.texture, textureDescriptorGPU, i, texture.flipY, i );
  50112. }
  50113. } else if ( texture.isCompressedTexture || texture.isCompressedArrayTexture ) {
  50114. this._copyCompressedBufferToTexture( texture.mipmaps, textureData.texture, textureDescriptorGPU );
  50115. } else if ( texture.isCubeTexture ) {
  50116. this._copyCubeMapToTexture( texture, textureData.texture, textureDescriptorGPU );
  50117. } else {
  50118. if ( mipmaps.length > 0 ) {
  50119. for ( let i = 0, il = mipmaps.length; i < il; i ++ ) {
  50120. const mipmap = mipmaps[ i ];
  50121. this._copyImageToTexture( mipmap, textureData.texture, textureDescriptorGPU, 0, texture.flipY, texture.premultiplyAlpha, i );
  50122. }
  50123. } else {
  50124. this._copyImageToTexture( options.image, textureData.texture, textureDescriptorGPU, 0, texture.flipY, texture.premultiplyAlpha );
  50125. }
  50126. }
  50127. //
  50128. textureData.version = texture.version;
  50129. }
  50130. /**
  50131. * Returns texture data as a typed array.
  50132. *
  50133. * @async
  50134. * @param {Texture} texture - The texture to copy.
  50135. * @param {number} x - The x coordinate of the copy origin.
  50136. * @param {number} y - The y coordinate of the copy origin.
  50137. * @param {number} width - The width of the copy.
  50138. * @param {number} height - The height of the copy.
  50139. * @param {number} faceIndex - The face index.
  50140. * @return {Promise<TypedArray>} A Promise that resolves with a typed array when the copy operation has finished.
  50141. */
  50142. async copyTextureToBuffer( texture, x, y, width, height, faceIndex ) {
  50143. const device = this.backend.device;
  50144. const textureData = this.backend.get( texture );
  50145. const textureGPU = textureData.texture;
  50146. const format = textureData.textureDescriptorGPU.format;
  50147. const bytesPerTexel = this._getBytesPerTexel( format );
  50148. let bytesPerRow = width * bytesPerTexel;
  50149. bytesPerRow = Math.ceil( bytesPerRow / 256 ) * 256; // Align to 256 bytes
  50150. const readBuffer = device.createBuffer(
  50151. {
  50152. size: ( ( height - 1 ) * bytesPerRow ) + ( width * bytesPerTexel ), // see https://github.com/mrdoob/three.js/issues/31658#issuecomment-3229442010
  50153. usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ
  50154. }
  50155. );
  50156. const encoder = device.createCommandEncoder();
  50157. encoder.copyTextureToBuffer(
  50158. {
  50159. texture: textureGPU,
  50160. origin: { x, y, z: faceIndex },
  50161. },
  50162. {
  50163. buffer: readBuffer,
  50164. bytesPerRow: bytesPerRow
  50165. },
  50166. {
  50167. width: width,
  50168. height: height
  50169. }
  50170. );
  50171. const typedArrayType = this._getTypedArrayType( format );
  50172. device.queue.submit( [ encoder.finish() ] );
  50173. await readBuffer.mapAsync( GPUMapMode.READ );
  50174. const buffer = readBuffer.getMappedRange();
  50175. return new typedArrayType( buffer );
  50176. }
  50177. /**
  50178. * Frees all internal resources.
  50179. */
  50180. dispose() {
  50181. this._samplerCache.clear();
  50182. }
  50183. /**
  50184. * Returns the default GPU texture for the given format.
  50185. *
  50186. * @private
  50187. * @param {string} format - The GPU format.
  50188. * @return {GPUTexture} The GPU texture.
  50189. */
  50190. _getDefaultTextureGPU( format ) {
  50191. let defaultTexture = this.defaultTexture[ format ];
  50192. if ( defaultTexture === undefined ) {
  50193. const texture = new Texture();
  50194. texture.minFilter = NearestFilter;
  50195. texture.magFilter = NearestFilter;
  50196. this.createTexture( texture, { width: 1, height: 1, format } );
  50197. this.defaultTexture[ format ] = defaultTexture = texture;
  50198. }
  50199. return this.backend.get( defaultTexture ).texture;
  50200. }
  50201. /**
  50202. * Returns the default GPU cube texture for the given format.
  50203. *
  50204. * @private
  50205. * @param {string} format - The GPU format.
  50206. * @return {GPUTexture} The GPU texture.
  50207. */
  50208. _getDefaultCubeTextureGPU( format ) {
  50209. let defaultCubeTexture = this.defaultTexture[ format ];
  50210. if ( defaultCubeTexture === undefined ) {
  50211. const texture = new CubeTexture();
  50212. texture.minFilter = NearestFilter;
  50213. texture.magFilter = NearestFilter;
  50214. this.createTexture( texture, { width: 1, height: 1, depth: 6 } );
  50215. this.defaultCubeTexture[ format ] = defaultCubeTexture = texture;
  50216. }
  50217. return this.backend.get( defaultCubeTexture ).texture;
  50218. }
  50219. /**
  50220. * Uploads cube texture image data to the GPU memory.
  50221. *
  50222. * @private
  50223. * @param {CubeTexture} texture - The cube texture.
  50224. * @param {GPUTexture} textureGPU - The GPU texture.
  50225. * @param {Object} textureDescriptorGPU - The GPU texture descriptor.
  50226. */
  50227. _copyCubeMapToTexture( texture, textureGPU, textureDescriptorGPU ) {
  50228. const images = texture.images;
  50229. const mipmaps = texture.mipmaps;
  50230. for ( let i = 0; i < 6; i ++ ) {
  50231. const image = images[ i ];
  50232. const flipIndex = texture.flipY === true ? _flipMap[ i ] : i;
  50233. if ( image.isDataTexture ) {
  50234. this._copyBufferToTexture( image.image, textureGPU, textureDescriptorGPU, flipIndex, texture.flipY );
  50235. } else {
  50236. this._copyImageToTexture( image, textureGPU, textureDescriptorGPU, flipIndex, texture.flipY, texture.premultiplyAlpha );
  50237. }
  50238. for ( let j = 0; j < mipmaps.length; j ++ ) {
  50239. const mipmap = mipmaps[ j ];
  50240. const image = mipmap.images[ i ];
  50241. if ( image.isDataTexture ) {
  50242. this._copyBufferToTexture( image.image, textureGPU, textureDescriptorGPU, flipIndex, texture.flipY, 0, j + 1 );
  50243. } else {
  50244. this._copyImageToTexture( image, textureGPU, textureDescriptorGPU, flipIndex, texture.flipY, texture.premultiplyAlpha, j + 1 );
  50245. }
  50246. }
  50247. }
  50248. }
  50249. /**
  50250. * Uploads texture image data to the GPU memory.
  50251. *
  50252. * @private
  50253. * @param {HTMLImageElement|ImageBitmap|HTMLCanvasElement} image - The image data.
  50254. * @param {GPUTexture} textureGPU - The GPU texture.
  50255. * @param {Object} textureDescriptorGPU - The GPU texture descriptor.
  50256. * @param {number} originDepth - The origin depth.
  50257. * @param {boolean} flipY - Whether to flip texture data along their vertical axis or not.
  50258. * @param {boolean} premultiplyAlpha - Whether the texture should have its RGB channels premultiplied by the alpha channel or not.
  50259. * @param {number} [mipLevel=0] - The mip level where the data should be copied to.
  50260. */
  50261. _copyImageToTexture( image, textureGPU, textureDescriptorGPU, originDepth, flipY, premultiplyAlpha, mipLevel = 0 ) {
  50262. const device = this.backend.device;
  50263. const width = ( mipLevel > 0 ) ? image.width : textureDescriptorGPU.size.width;
  50264. const height = ( mipLevel > 0 ) ? image.height : textureDescriptorGPU.size.height;
  50265. device.queue.copyExternalImageToTexture(
  50266. {
  50267. source: image,
  50268. flipY: flipY
  50269. }, {
  50270. texture: textureGPU,
  50271. mipLevel: mipLevel,
  50272. origin: { x: 0, y: 0, z: originDepth },
  50273. premultipliedAlpha: premultiplyAlpha
  50274. }, {
  50275. width: width,
  50276. height: height,
  50277. depthOrArrayLayers: 1
  50278. }
  50279. );
  50280. }
  50281. /**
  50282. * Returns the pass utils singleton.
  50283. *
  50284. * @private
  50285. * @return {WebGPUTexturePassUtils} The utils instance.
  50286. */
  50287. _getPassUtils() {
  50288. let passUtils = this._passUtils;
  50289. if ( passUtils === null ) {
  50290. this._passUtils = passUtils = new WebGPUTexturePassUtils( this.backend.device );
  50291. }
  50292. return passUtils;
  50293. }
  50294. /**
  50295. * Generates mipmaps for the given GPU texture.
  50296. *
  50297. * @private
  50298. * @param {GPUTexture} textureGPU - The GPU texture object.
  50299. * @param {Object} textureDescriptorGPU - The texture descriptor.
  50300. * @param {number} [baseArrayLayer=0] - The index of the first array layer accessible to the texture view.
  50301. * @param {?GPUCommandEncoder} [encoder=null] - An optional command encoder used to generate mipmaps.
  50302. */
  50303. _generateMipmaps( textureGPU, textureDescriptorGPU, baseArrayLayer = 0, encoder = null ) {
  50304. this._getPassUtils().generateMipmaps( textureGPU, textureDescriptorGPU, baseArrayLayer, encoder );
  50305. }
  50306. /**
  50307. * Flip the contents of the given GPU texture along its vertical axis.
  50308. *
  50309. * @private
  50310. * @param {GPUTexture} textureGPU - The GPU texture object.
  50311. * @param {Object} textureDescriptorGPU - The texture descriptor.
  50312. * @param {number} [originDepth=0] - The origin depth.
  50313. */
  50314. _flipY( textureGPU, textureDescriptorGPU, originDepth = 0 ) {
  50315. this._getPassUtils().flipY( textureGPU, textureDescriptorGPU, originDepth );
  50316. }
  50317. /**
  50318. * Uploads texture buffer data to the GPU memory.
  50319. *
  50320. * @private
  50321. * @param {Object} image - An object defining the image buffer data.
  50322. * @param {GPUTexture} textureGPU - The GPU texture.
  50323. * @param {Object} textureDescriptorGPU - The GPU texture descriptor.
  50324. * @param {number} originDepth - The origin depth.
  50325. * @param {boolean} flipY - Whether to flip texture data along their vertical axis or not.
  50326. * @param {number} [depth=0] - The depth offset when copying array or 3D texture data.
  50327. * @param {number} [mipLevel=0] - The mip level where the data should be copied to.
  50328. */
  50329. _copyBufferToTexture( image, textureGPU, textureDescriptorGPU, originDepth, flipY, depth = 0, mipLevel = 0 ) {
  50330. // @TODO: Consider to use GPUCommandEncoder.copyBufferToTexture()
  50331. // @TODO: Consider to support valid buffer layouts with other formats like RGB
  50332. const device = this.backend.device;
  50333. const data = image.data;
  50334. const bytesPerTexel = this._getBytesPerTexel( textureDescriptorGPU.format );
  50335. const bytesPerRow = image.width * bytesPerTexel;
  50336. device.queue.writeTexture(
  50337. {
  50338. texture: textureGPU,
  50339. mipLevel: mipLevel,
  50340. origin: { x: 0, y: 0, z: originDepth }
  50341. },
  50342. data,
  50343. {
  50344. offset: image.width * image.height * bytesPerTexel * depth,
  50345. bytesPerRow
  50346. },
  50347. {
  50348. width: image.width,
  50349. height: image.height,
  50350. depthOrArrayLayers: 1
  50351. } );
  50352. if ( flipY === true ) {
  50353. this._flipY( textureGPU, textureDescriptorGPU, originDepth );
  50354. }
  50355. }
  50356. /**
  50357. * Uploads compressed texture data to the GPU memory.
  50358. *
  50359. * @private
  50360. * @param {Array<Object>} mipmaps - An array with mipmap data.
  50361. * @param {GPUTexture} textureGPU - The GPU texture.
  50362. * @param {Object} textureDescriptorGPU - The GPU texture descriptor.
  50363. */
  50364. _copyCompressedBufferToTexture( mipmaps, textureGPU, textureDescriptorGPU ) {
  50365. // @TODO: Consider to use GPUCommandEncoder.copyBufferToTexture()
  50366. const device = this.backend.device;
  50367. const blockData = this._getBlockData( textureDescriptorGPU.format );
  50368. const isArrayTexture = textureDescriptorGPU.size.depthOrArrayLayers > 1;
  50369. for ( let i = 0; i < mipmaps.length; i ++ ) {
  50370. const mipmap = mipmaps[ i ];
  50371. const width = mipmap.width;
  50372. const height = mipmap.height;
  50373. const depth = isArrayTexture ? textureDescriptorGPU.size.depthOrArrayLayers : 1;
  50374. const bytesPerRow = Math.ceil( width / blockData.width ) * blockData.byteLength;
  50375. const bytesPerImage = bytesPerRow * Math.ceil( height / blockData.height );
  50376. for ( let j = 0; j < depth; j ++ ) {
  50377. device.queue.writeTexture(
  50378. {
  50379. texture: textureGPU,
  50380. mipLevel: i,
  50381. origin: { x: 0, y: 0, z: j }
  50382. },
  50383. mipmap.data,
  50384. {
  50385. offset: j * bytesPerImage,
  50386. bytesPerRow,
  50387. rowsPerImage: Math.ceil( height / blockData.height )
  50388. },
  50389. {
  50390. width: Math.ceil( width / blockData.width ) * blockData.width,
  50391. height: Math.ceil( height / blockData.height ) * blockData.height,
  50392. depthOrArrayLayers: 1
  50393. }
  50394. );
  50395. }
  50396. }
  50397. }
  50398. /**
  50399. * This method is only relevant for compressed texture formats. It returns a block
  50400. * data descriptor for the given GPU compressed texture format.
  50401. *
  50402. * @private
  50403. * @param {string} format - The GPU compressed texture format.
  50404. * @return {Object} The block data descriptor.
  50405. */
  50406. _getBlockData( format ) {
  50407. if ( format === GPUTextureFormat.BC1RGBAUnorm || format === GPUTextureFormat.BC1RGBAUnormSRGB ) return { byteLength: 8, width: 4, height: 4 }; // DXT1
  50408. if ( format === GPUTextureFormat.BC2RGBAUnorm || format === GPUTextureFormat.BC2RGBAUnormSRGB ) return { byteLength: 16, width: 4, height: 4 }; // DXT3
  50409. if ( format === GPUTextureFormat.BC3RGBAUnorm || format === GPUTextureFormat.BC3RGBAUnormSRGB ) return { byteLength: 16, width: 4, height: 4 }; // DXT5
  50410. if ( format === GPUTextureFormat.BC4RUnorm || format === GPUTextureFormat.BC4RSnorm ) return { byteLength: 8, width: 4, height: 4 }; // RGTC1
  50411. if ( format === GPUTextureFormat.BC5RGUnorm || format === GPUTextureFormat.BC5RGSnorm ) return { byteLength: 16, width: 4, height: 4 }; // RGTC2
  50412. if ( format === GPUTextureFormat.BC6HRGBUFloat || format === GPUTextureFormat.BC6HRGBFloat ) return { byteLength: 16, width: 4, height: 4 }; // BPTC (float)
  50413. if ( format === GPUTextureFormat.BC7RGBAUnorm || format === GPUTextureFormat.BC7RGBAUnormSRGB ) return { byteLength: 16, width: 4, height: 4 }; // BPTC (unorm)
  50414. if ( format === GPUTextureFormat.ETC2RGB8Unorm || format === GPUTextureFormat.ETC2RGB8UnormSRGB ) return { byteLength: 8, width: 4, height: 4 };
  50415. if ( format === GPUTextureFormat.ETC2RGB8A1Unorm || format === GPUTextureFormat.ETC2RGB8A1UnormSRGB ) return { byteLength: 8, width: 4, height: 4 };
  50416. if ( format === GPUTextureFormat.ETC2RGBA8Unorm || format === GPUTextureFormat.ETC2RGBA8UnormSRGB ) return { byteLength: 16, width: 4, height: 4 };
  50417. if ( format === GPUTextureFormat.EACR11Unorm ) return { byteLength: 8, width: 4, height: 4 };
  50418. if ( format === GPUTextureFormat.EACR11Snorm ) return { byteLength: 8, width: 4, height: 4 };
  50419. if ( format === GPUTextureFormat.EACRG11Unorm ) return { byteLength: 16, width: 4, height: 4 };
  50420. if ( format === GPUTextureFormat.EACRG11Snorm ) return { byteLength: 16, width: 4, height: 4 };
  50421. if ( format === GPUTextureFormat.ASTC4x4Unorm || format === GPUTextureFormat.ASTC4x4UnormSRGB ) return { byteLength: 16, width: 4, height: 4 };
  50422. if ( format === GPUTextureFormat.ASTC5x4Unorm || format === GPUTextureFormat.ASTC5x4UnormSRGB ) return { byteLength: 16, width: 5, height: 4 };
  50423. if ( format === GPUTextureFormat.ASTC5x5Unorm || format === GPUTextureFormat.ASTC5x5UnormSRGB ) return { byteLength: 16, width: 5, height: 5 };
  50424. if ( format === GPUTextureFormat.ASTC6x5Unorm || format === GPUTextureFormat.ASTC6x5UnormSRGB ) return { byteLength: 16, width: 6, height: 5 };
  50425. if ( format === GPUTextureFormat.ASTC6x6Unorm || format === GPUTextureFormat.ASTC6x6UnormSRGB ) return { byteLength: 16, width: 6, height: 6 };
  50426. if ( format === GPUTextureFormat.ASTC8x5Unorm || format === GPUTextureFormat.ASTC8x5UnormSRGB ) return { byteLength: 16, width: 8, height: 5 };
  50427. if ( format === GPUTextureFormat.ASTC8x6Unorm || format === GPUTextureFormat.ASTC8x6UnormSRGB ) return { byteLength: 16, width: 8, height: 6 };
  50428. if ( format === GPUTextureFormat.ASTC8x8Unorm || format === GPUTextureFormat.ASTC8x8UnormSRGB ) return { byteLength: 16, width: 8, height: 8 };
  50429. if ( format === GPUTextureFormat.ASTC10x5Unorm || format === GPUTextureFormat.ASTC10x5UnormSRGB ) return { byteLength: 16, width: 10, height: 5 };
  50430. if ( format === GPUTextureFormat.ASTC10x6Unorm || format === GPUTextureFormat.ASTC10x6UnormSRGB ) return { byteLength: 16, width: 10, height: 6 };
  50431. if ( format === GPUTextureFormat.ASTC10x8Unorm || format === GPUTextureFormat.ASTC10x8UnormSRGB ) return { byteLength: 16, width: 10, height: 8 };
  50432. if ( format === GPUTextureFormat.ASTC10x10Unorm || format === GPUTextureFormat.ASTC10x10UnormSRGB ) return { byteLength: 16, width: 10, height: 10 };
  50433. if ( format === GPUTextureFormat.ASTC12x10Unorm || format === GPUTextureFormat.ASTC12x10UnormSRGB ) return { byteLength: 16, width: 12, height: 10 };
  50434. if ( format === GPUTextureFormat.ASTC12x12Unorm || format === GPUTextureFormat.ASTC12x12UnormSRGB ) return { byteLength: 16, width: 12, height: 12 };
  50435. }
  50436. /**
  50437. * Converts the three.js uv wrapping constants to GPU address mode constants.
  50438. *
  50439. * @private
  50440. * @param {number} value - The three.js constant defining a uv wrapping mode.
  50441. * @return {string} The GPU address mode.
  50442. */
  50443. _convertAddressMode( value ) {
  50444. let addressMode = GPUAddressMode.ClampToEdge;
  50445. if ( value === RepeatWrapping ) {
  50446. addressMode = GPUAddressMode.Repeat;
  50447. } else if ( value === MirroredRepeatWrapping ) {
  50448. addressMode = GPUAddressMode.MirrorRepeat;
  50449. }
  50450. return addressMode;
  50451. }
  50452. /**
  50453. * Converts the three.js filter constants to GPU filter constants.
  50454. *
  50455. * @private
  50456. * @param {number} value - The three.js constant defining a filter mode.
  50457. * @return {string} The GPU filter mode.
  50458. */
  50459. _convertFilterMode( value ) {
  50460. let filterMode = GPUFilterMode.Linear;
  50461. if ( value === NearestFilter || value === NearestMipmapNearestFilter || value === NearestMipmapLinearFilter ) {
  50462. filterMode = GPUFilterMode.Nearest;
  50463. }
  50464. return filterMode;
  50465. }
  50466. /**
  50467. * Returns the bytes-per-texel value for the given GPU texture format.
  50468. *
  50469. * @private
  50470. * @param {string} format - The GPU texture format.
  50471. * @return {number} The bytes-per-texel.
  50472. */
  50473. _getBytesPerTexel( format ) {
  50474. // 8-bit formats
  50475. if ( format === GPUTextureFormat.R8Unorm ||
  50476. format === GPUTextureFormat.R8Snorm ||
  50477. format === GPUTextureFormat.R8Uint ||
  50478. format === GPUTextureFormat.R8Sint ) return 1;
  50479. // 16-bit formats
  50480. if ( format === GPUTextureFormat.R16Uint ||
  50481. format === GPUTextureFormat.R16Sint ||
  50482. format === GPUTextureFormat.R16Float ||
  50483. format === GPUTextureFormat.RG8Unorm ||
  50484. format === GPUTextureFormat.RG8Snorm ||
  50485. format === GPUTextureFormat.RG8Uint ||
  50486. format === GPUTextureFormat.RG8Sint ) return 2;
  50487. // 32-bit formats
  50488. if ( format === GPUTextureFormat.R32Uint ||
  50489. format === GPUTextureFormat.R32Sint ||
  50490. format === GPUTextureFormat.R32Float ||
  50491. format === GPUTextureFormat.RG16Uint ||
  50492. format === GPUTextureFormat.RG16Sint ||
  50493. format === GPUTextureFormat.RG16Float ||
  50494. format === GPUTextureFormat.RGBA8Unorm ||
  50495. format === GPUTextureFormat.RGBA8UnormSRGB ||
  50496. format === GPUTextureFormat.RGBA8Snorm ||
  50497. format === GPUTextureFormat.RGBA8Uint ||
  50498. format === GPUTextureFormat.RGBA8Sint ||
  50499. format === GPUTextureFormat.BGRA8Unorm ||
  50500. format === GPUTextureFormat.BGRA8UnormSRGB ||
  50501. // Packed 32-bit formats
  50502. format === GPUTextureFormat.RGB9E5UFloat ||
  50503. format === GPUTextureFormat.RGB10A2Unorm ||
  50504. format === GPUTextureFormat.RG11B10UFloat ||
  50505. format === GPUTextureFormat.Depth32Float ||
  50506. format === GPUTextureFormat.Depth24Plus ||
  50507. format === GPUTextureFormat.Depth24PlusStencil8 ||
  50508. format === GPUTextureFormat.Depth32FloatStencil8 ) return 4;
  50509. // 64-bit formats
  50510. if ( format === GPUTextureFormat.RG32Uint ||
  50511. format === GPUTextureFormat.RG32Sint ||
  50512. format === GPUTextureFormat.RG32Float ||
  50513. format === GPUTextureFormat.RGBA16Uint ||
  50514. format === GPUTextureFormat.RGBA16Sint ||
  50515. format === GPUTextureFormat.RGBA16Float ) return 8;
  50516. // 128-bit formats
  50517. if ( format === GPUTextureFormat.RGBA32Uint ||
  50518. format === GPUTextureFormat.RGBA32Sint ||
  50519. format === GPUTextureFormat.RGBA32Float ) return 16;
  50520. }
  50521. /**
  50522. * Returns the corresponding typed array type for the given GPU texture format.
  50523. *
  50524. * @private
  50525. * @param {string} format - The GPU texture format.
  50526. * @return {TypedArray.constructor} The typed array type.
  50527. */
  50528. _getTypedArrayType( format ) {
  50529. if ( format === GPUTextureFormat.R8Uint ) return Uint8Array;
  50530. if ( format === GPUTextureFormat.R8Sint ) return Int8Array;
  50531. if ( format === GPUTextureFormat.R8Unorm ) return Uint8Array;
  50532. if ( format === GPUTextureFormat.R8Snorm ) return Int8Array;
  50533. if ( format === GPUTextureFormat.RG8Uint ) return Uint8Array;
  50534. if ( format === GPUTextureFormat.RG8Sint ) return Int8Array;
  50535. if ( format === GPUTextureFormat.RG8Unorm ) return Uint8Array;
  50536. if ( format === GPUTextureFormat.RG8Snorm ) return Int8Array;
  50537. if ( format === GPUTextureFormat.RGBA8Uint ) return Uint8Array;
  50538. if ( format === GPUTextureFormat.RGBA8Sint ) return Int8Array;
  50539. if ( format === GPUTextureFormat.RGBA8Unorm || format === GPUTextureFormat.RGBA8UnormSRGB ) return Uint8Array;
  50540. if ( format === GPUTextureFormat.RGBA8Snorm ) return Int8Array;
  50541. if ( format === GPUTextureFormat.R16Uint ) return Uint16Array;
  50542. if ( format === GPUTextureFormat.R16Sint ) return Int16Array;
  50543. if ( format === GPUTextureFormat.RG16Uint ) return Uint16Array;
  50544. if ( format === GPUTextureFormat.RG16Sint ) return Int16Array;
  50545. if ( format === GPUTextureFormat.RGBA16Uint ) return Uint16Array;
  50546. if ( format === GPUTextureFormat.RGBA16Sint ) return Int16Array;
  50547. if ( format === GPUTextureFormat.R16Float ) return Uint16Array;
  50548. if ( format === GPUTextureFormat.RG16Float ) return Uint16Array;
  50549. if ( format === GPUTextureFormat.RGBA16Float ) return Uint16Array;
  50550. if ( format === GPUTextureFormat.R32Uint ) return Uint32Array;
  50551. if ( format === GPUTextureFormat.R32Sint ) return Int32Array;
  50552. if ( format === GPUTextureFormat.R32Float ) return Float32Array;
  50553. if ( format === GPUTextureFormat.RG32Uint ) return Uint32Array;
  50554. if ( format === GPUTextureFormat.RG32Sint ) return Int32Array;
  50555. if ( format === GPUTextureFormat.RG32Float ) return Float32Array;
  50556. if ( format === GPUTextureFormat.RGBA32Uint ) return Uint32Array;
  50557. if ( format === GPUTextureFormat.RGBA32Sint ) return Int32Array;
  50558. if ( format === GPUTextureFormat.RGBA32Float ) return Float32Array;
  50559. if ( format === GPUTextureFormat.BGRA8Unorm || format === GPUTextureFormat.BGRA8UnormSRGB ) return Uint8Array;
  50560. if ( format === GPUTextureFormat.RGB10A2Unorm ) return Uint32Array;
  50561. if ( format === GPUTextureFormat.RGB9E5UFloat ) return Uint32Array;
  50562. if ( format === GPUTextureFormat.RG11B10UFloat ) return Uint32Array;
  50563. if ( format === GPUTextureFormat.Depth32Float ) return Float32Array;
  50564. if ( format === GPUTextureFormat.Depth24Plus ) return Uint32Array;
  50565. if ( format === GPUTextureFormat.Depth24PlusStencil8 ) return Uint32Array;
  50566. if ( format === GPUTextureFormat.Depth32FloatStencil8 ) return Float32Array;
  50567. }
  50568. /**
  50569. * Returns the GPU dimensions for the given texture.
  50570. *
  50571. * @private
  50572. * @param {Texture} texture - The texture.
  50573. * @return {string} The GPU dimension.
  50574. */
  50575. _getDimension( texture ) {
  50576. let dimension;
  50577. if ( texture.is3DTexture || texture.isData3DTexture ) {
  50578. dimension = GPUTextureDimension.ThreeD;
  50579. } else {
  50580. dimension = GPUTextureDimension.TwoD;
  50581. }
  50582. return dimension;
  50583. }
  50584. }
  50585. /**
  50586. * Returns the GPU format for the given texture.
  50587. *
  50588. * @param {Texture} texture - The texture.
  50589. * @param {?GPUDevice} [device=null] - The GPU device which is used for feature detection.
  50590. * It is not necessary to apply the device for most formats.
  50591. * @return {string} The GPU format.
  50592. */
  50593. function getFormat( texture, device = null ) {
  50594. const format = texture.format;
  50595. const type = texture.type;
  50596. const colorSpace = texture.colorSpace;
  50597. const transfer = ColorManagement.getTransfer( colorSpace );
  50598. let formatGPU;
  50599. if ( texture.isCompressedTexture === true || texture.isCompressedArrayTexture === true ) {
  50600. switch ( format ) {
  50601. case RGB_S3TC_DXT1_Format:
  50602. case RGBA_S3TC_DXT1_Format:
  50603. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.BC1RGBAUnormSRGB : GPUTextureFormat.BC1RGBAUnorm;
  50604. break;
  50605. case RGBA_S3TC_DXT3_Format:
  50606. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.BC2RGBAUnormSRGB : GPUTextureFormat.BC2RGBAUnorm;
  50607. break;
  50608. case RGBA_S3TC_DXT5_Format:
  50609. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.BC3RGBAUnormSRGB : GPUTextureFormat.BC3RGBAUnorm;
  50610. break;
  50611. case RED_RGTC1_Format:
  50612. formatGPU = GPUTextureFormat.BC4RUnorm;
  50613. break;
  50614. case SIGNED_RED_RGTC1_Format:
  50615. formatGPU = GPUTextureFormat.BC4RSnorm;
  50616. break;
  50617. case RED_GREEN_RGTC2_Format:
  50618. formatGPU = GPUTextureFormat.BC5RGUnorm;
  50619. break;
  50620. case SIGNED_RED_GREEN_RGTC2_Format:
  50621. formatGPU = GPUTextureFormat.BC5RGSnorm;
  50622. break;
  50623. case RGBA_BPTC_Format:
  50624. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.BC7RGBAUnormSRGB : GPUTextureFormat.BC7RGBAUnorm;
  50625. break;
  50626. case RGB_ETC2_Format:
  50627. case RGB_ETC1_Format:
  50628. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ETC2RGB8UnormSRGB : GPUTextureFormat.ETC2RGB8Unorm;
  50629. break;
  50630. case RGBA_ETC2_EAC_Format:
  50631. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ETC2RGBA8UnormSRGB : GPUTextureFormat.ETC2RGBA8Unorm;
  50632. break;
  50633. case RGBA_ASTC_4x4_Format:
  50634. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ASTC4x4UnormSRGB : GPUTextureFormat.ASTC4x4Unorm;
  50635. break;
  50636. case RGBA_ASTC_5x4_Format:
  50637. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ASTC5x4UnormSRGB : GPUTextureFormat.ASTC5x4Unorm;
  50638. break;
  50639. case RGBA_ASTC_5x5_Format:
  50640. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ASTC5x5UnormSRGB : GPUTextureFormat.ASTC5x5Unorm;
  50641. break;
  50642. case RGBA_ASTC_6x5_Format:
  50643. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ASTC6x5UnormSRGB : GPUTextureFormat.ASTC6x5Unorm;
  50644. break;
  50645. case RGBA_ASTC_6x6_Format:
  50646. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ASTC6x6UnormSRGB : GPUTextureFormat.ASTC6x6Unorm;
  50647. break;
  50648. case RGBA_ASTC_8x5_Format:
  50649. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ASTC8x5UnormSRGB : GPUTextureFormat.ASTC8x5Unorm;
  50650. break;
  50651. case RGBA_ASTC_8x6_Format:
  50652. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ASTC8x6UnormSRGB : GPUTextureFormat.ASTC8x6Unorm;
  50653. break;
  50654. case RGBA_ASTC_8x8_Format:
  50655. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ASTC8x8UnormSRGB : GPUTextureFormat.ASTC8x8Unorm;
  50656. break;
  50657. case RGBA_ASTC_10x5_Format:
  50658. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ASTC10x5UnormSRGB : GPUTextureFormat.ASTC10x5Unorm;
  50659. break;
  50660. case RGBA_ASTC_10x6_Format:
  50661. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ASTC10x6UnormSRGB : GPUTextureFormat.ASTC10x6Unorm;
  50662. break;
  50663. case RGBA_ASTC_10x8_Format:
  50664. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ASTC10x8UnormSRGB : GPUTextureFormat.ASTC10x8Unorm;
  50665. break;
  50666. case RGBA_ASTC_10x10_Format:
  50667. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ASTC10x10UnormSRGB : GPUTextureFormat.ASTC10x10Unorm;
  50668. break;
  50669. case RGBA_ASTC_12x10_Format:
  50670. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ASTC12x10UnormSRGB : GPUTextureFormat.ASTC12x10Unorm;
  50671. break;
  50672. case RGBA_ASTC_12x12_Format:
  50673. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ASTC12x12UnormSRGB : GPUTextureFormat.ASTC12x12Unorm;
  50674. break;
  50675. case RGBAFormat:
  50676. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.RGBA8UnormSRGB : GPUTextureFormat.RGBA8Unorm;
  50677. break;
  50678. default:
  50679. error( 'WebGPURenderer: Unsupported texture format.', format );
  50680. }
  50681. } else {
  50682. switch ( format ) {
  50683. case RGBAFormat:
  50684. switch ( type ) {
  50685. case ByteType:
  50686. formatGPU = GPUTextureFormat.RGBA8Snorm;
  50687. break;
  50688. case ShortType:
  50689. formatGPU = GPUTextureFormat.RGBA16Sint;
  50690. break;
  50691. case UnsignedShortType:
  50692. formatGPU = GPUTextureFormat.RGBA16Uint;
  50693. break;
  50694. case UnsignedIntType:
  50695. formatGPU = GPUTextureFormat.RGBA32Uint;
  50696. break;
  50697. case IntType:
  50698. formatGPU = GPUTextureFormat.RGBA32Sint;
  50699. break;
  50700. case UnsignedByteType:
  50701. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.RGBA8UnormSRGB : GPUTextureFormat.RGBA8Unorm;
  50702. break;
  50703. case HalfFloatType:
  50704. formatGPU = GPUTextureFormat.RGBA16Float;
  50705. break;
  50706. case FloatType:
  50707. formatGPU = GPUTextureFormat.RGBA32Float;
  50708. break;
  50709. default:
  50710. error( 'WebGPURenderer: Unsupported texture type with RGBAFormat.', type );
  50711. }
  50712. break;
  50713. case RGBFormat:
  50714. switch ( type ) {
  50715. case UnsignedInt5999Type:
  50716. formatGPU = GPUTextureFormat.RGB9E5UFloat;
  50717. break;
  50718. case UnsignedInt101111Type:
  50719. formatGPU = GPUTextureFormat.RG11B10UFloat;
  50720. break;
  50721. default:
  50722. error( 'WebGPURenderer: Unsupported texture type with RGBFormat.', type );
  50723. }
  50724. break;
  50725. case RedFormat:
  50726. switch ( type ) {
  50727. case ByteType:
  50728. formatGPU = GPUTextureFormat.R8Snorm;
  50729. break;
  50730. case ShortType:
  50731. formatGPU = GPUTextureFormat.R16Sint;
  50732. break;
  50733. case UnsignedShortType:
  50734. formatGPU = GPUTextureFormat.R16Uint;
  50735. break;
  50736. case UnsignedIntType:
  50737. formatGPU = GPUTextureFormat.R32Uint;
  50738. break;
  50739. case IntType:
  50740. formatGPU = GPUTextureFormat.R32Sint;
  50741. break;
  50742. case UnsignedByteType:
  50743. formatGPU = GPUTextureFormat.R8Unorm;
  50744. break;
  50745. case HalfFloatType:
  50746. formatGPU = GPUTextureFormat.R16Float;
  50747. break;
  50748. case FloatType:
  50749. formatGPU = GPUTextureFormat.R32Float;
  50750. break;
  50751. default:
  50752. error( 'WebGPURenderer: Unsupported texture type with RedFormat.', type );
  50753. }
  50754. break;
  50755. case RGFormat:
  50756. switch ( type ) {
  50757. case ByteType:
  50758. formatGPU = GPUTextureFormat.RG8Snorm;
  50759. break;
  50760. case ShortType:
  50761. formatGPU = GPUTextureFormat.RG16Sint;
  50762. break;
  50763. case UnsignedShortType:
  50764. formatGPU = GPUTextureFormat.RG16Uint;
  50765. break;
  50766. case UnsignedIntType:
  50767. formatGPU = GPUTextureFormat.RG32Uint;
  50768. break;
  50769. case IntType:
  50770. formatGPU = GPUTextureFormat.RG32Sint;
  50771. break;
  50772. case UnsignedByteType:
  50773. formatGPU = GPUTextureFormat.RG8Unorm;
  50774. break;
  50775. case HalfFloatType:
  50776. formatGPU = GPUTextureFormat.RG16Float;
  50777. break;
  50778. case FloatType:
  50779. formatGPU = GPUTextureFormat.RG32Float;
  50780. break;
  50781. default:
  50782. error( 'WebGPURenderer: Unsupported texture type with RGFormat.', type );
  50783. }
  50784. break;
  50785. case DepthFormat:
  50786. switch ( type ) {
  50787. case UnsignedShortType:
  50788. formatGPU = GPUTextureFormat.Depth16Unorm;
  50789. break;
  50790. case UnsignedIntType:
  50791. formatGPU = GPUTextureFormat.Depth24Plus;
  50792. break;
  50793. case FloatType:
  50794. formatGPU = GPUTextureFormat.Depth32Float;
  50795. break;
  50796. default:
  50797. error( 'WebGPURenderer: Unsupported texture type with DepthFormat.', type );
  50798. }
  50799. break;
  50800. case DepthStencilFormat:
  50801. switch ( type ) {
  50802. case UnsignedInt248Type:
  50803. formatGPU = GPUTextureFormat.Depth24PlusStencil8;
  50804. break;
  50805. case FloatType:
  50806. if ( device && device.features.has( GPUFeatureName.Depth32FloatStencil8 ) === false ) {
  50807. error( 'WebGPURenderer: Depth textures with DepthStencilFormat + FloatType can only be used with the "depth32float-stencil8" GPU feature.' );
  50808. }
  50809. formatGPU = GPUTextureFormat.Depth32FloatStencil8;
  50810. break;
  50811. default:
  50812. error( 'WebGPURenderer: Unsupported texture type with DepthStencilFormat.', type );
  50813. }
  50814. break;
  50815. case RedIntegerFormat:
  50816. switch ( type ) {
  50817. case IntType:
  50818. formatGPU = GPUTextureFormat.R32Sint;
  50819. break;
  50820. case UnsignedIntType:
  50821. formatGPU = GPUTextureFormat.R32Uint;
  50822. break;
  50823. default:
  50824. error( 'WebGPURenderer: Unsupported texture type with RedIntegerFormat.', type );
  50825. }
  50826. break;
  50827. case RGIntegerFormat:
  50828. switch ( type ) {
  50829. case IntType:
  50830. formatGPU = GPUTextureFormat.RG32Sint;
  50831. break;
  50832. case UnsignedIntType:
  50833. formatGPU = GPUTextureFormat.RG32Uint;
  50834. break;
  50835. default:
  50836. error( 'WebGPURenderer: Unsupported texture type with RGIntegerFormat.', type );
  50837. }
  50838. break;
  50839. case RGBAIntegerFormat:
  50840. switch ( type ) {
  50841. case IntType:
  50842. formatGPU = GPUTextureFormat.RGBA32Sint;
  50843. break;
  50844. case UnsignedIntType:
  50845. formatGPU = GPUTextureFormat.RGBA32Uint;
  50846. break;
  50847. default:
  50848. error( 'WebGPURenderer: Unsupported texture type with RGBAIntegerFormat.', type );
  50849. }
  50850. break;
  50851. default:
  50852. error( 'WebGPURenderer: Unsupported texture format.', format );
  50853. }
  50854. }
  50855. return formatGPU;
  50856. }
  50857. const declarationRegexp = /^[fn]*\s*([a-z_0-9]+)?\s*\(([\s\S]*?)\)\s*[\-\>]*\s*([a-z_0-9]+(?:<[\s\S]+?>)?)/i;
  50858. const propertiesRegexp = /([a-z_0-9]+)\s*:\s*([a-z_0-9]+(?:<[\s\S]+?>)?)/ig;
  50859. const wgslTypeLib$1 = {
  50860. 'f32': 'float',
  50861. 'i32': 'int',
  50862. 'u32': 'uint',
  50863. 'bool': 'bool',
  50864. 'vec2<f32>': 'vec2',
  50865. 'vec2<i32>': 'ivec2',
  50866. 'vec2<u32>': 'uvec2',
  50867. 'vec2<bool>': 'bvec2',
  50868. 'vec2f': 'vec2',
  50869. 'vec2i': 'ivec2',
  50870. 'vec2u': 'uvec2',
  50871. 'vec2b': 'bvec2',
  50872. 'vec3<f32>': 'vec3',
  50873. 'vec3<i32>': 'ivec3',
  50874. 'vec3<u32>': 'uvec3',
  50875. 'vec3<bool>': 'bvec3',
  50876. 'vec3f': 'vec3',
  50877. 'vec3i': 'ivec3',
  50878. 'vec3u': 'uvec3',
  50879. 'vec3b': 'bvec3',
  50880. 'vec4<f32>': 'vec4',
  50881. 'vec4<i32>': 'ivec4',
  50882. 'vec4<u32>': 'uvec4',
  50883. 'vec4<bool>': 'bvec4',
  50884. 'vec4f': 'vec4',
  50885. 'vec4i': 'ivec4',
  50886. 'vec4u': 'uvec4',
  50887. 'vec4b': 'bvec4',
  50888. 'mat2x2<f32>': 'mat2',
  50889. 'mat2x2f': 'mat2',
  50890. 'mat3x3<f32>': 'mat3',
  50891. 'mat3x3f': 'mat3',
  50892. 'mat4x4<f32>': 'mat4',
  50893. 'mat4x4f': 'mat4',
  50894. 'sampler': 'sampler',
  50895. 'texture_1d': 'texture',
  50896. 'texture_2d': 'texture',
  50897. 'texture_2d_array': 'texture',
  50898. 'texture_multisampled_2d': 'cubeTexture',
  50899. 'texture_depth_2d': 'depthTexture',
  50900. 'texture_depth_2d_array': 'depthTexture',
  50901. 'texture_depth_multisampled_2d': 'depthTexture',
  50902. 'texture_depth_cube': 'depthTexture',
  50903. 'texture_depth_cube_array': 'depthTexture',
  50904. 'texture_3d': 'texture3D',
  50905. 'texture_cube': 'cubeTexture',
  50906. 'texture_cube_array': 'cubeTexture',
  50907. 'texture_storage_1d': 'storageTexture',
  50908. 'texture_storage_2d': 'storageTexture',
  50909. 'texture_storage_2d_array': 'storageTexture',
  50910. 'texture_storage_3d': 'storageTexture'
  50911. };
  50912. const parse = ( source ) => {
  50913. source = source.trim();
  50914. const declaration = source.match( declarationRegexp );
  50915. if ( declaration !== null && declaration.length === 4 ) {
  50916. const inputsCode = declaration[ 2 ];
  50917. const propsMatches = [];
  50918. let match = null;
  50919. while ( ( match = propertiesRegexp.exec( inputsCode ) ) !== null ) {
  50920. propsMatches.push( { name: match[ 1 ], type: match[ 2 ] } );
  50921. }
  50922. // Process matches to correctly pair names and types
  50923. const inputs = [];
  50924. for ( let i = 0; i < propsMatches.length; i ++ ) {
  50925. const { name, type } = propsMatches[ i ];
  50926. let resolvedType = type;
  50927. if ( resolvedType.startsWith( 'ptr' ) ) {
  50928. resolvedType = 'pointer';
  50929. } else {
  50930. if ( resolvedType.startsWith( 'texture' ) ) {
  50931. resolvedType = type.split( '<' )[ 0 ];
  50932. }
  50933. resolvedType = wgslTypeLib$1[ resolvedType ];
  50934. }
  50935. inputs.push( new NodeFunctionInput( resolvedType, name ) );
  50936. }
  50937. const blockCode = source.substring( declaration[ 0 ].length );
  50938. const outputType = declaration[ 3 ] || 'void';
  50939. const name = declaration[ 1 ] !== undefined ? declaration[ 1 ] : '';
  50940. const type = wgslTypeLib$1[ outputType ] || outputType;
  50941. return {
  50942. type,
  50943. inputs,
  50944. name,
  50945. inputsCode,
  50946. blockCode,
  50947. outputType
  50948. };
  50949. } else {
  50950. throw new Error( 'FunctionNode: Function is not a WGSL code.' );
  50951. }
  50952. };
  50953. /**
  50954. * This class represents a WSL node function.
  50955. *
  50956. * @augments NodeFunction
  50957. */
  50958. class WGSLNodeFunction extends NodeFunction {
  50959. /**
  50960. * Constructs a new WGSL node function.
  50961. *
  50962. * @param {string} source - The WGSL source.
  50963. */
  50964. constructor( source ) {
  50965. const { type, inputs, name, inputsCode, blockCode, outputType } = parse( source );
  50966. super( type, inputs, name );
  50967. this.inputsCode = inputsCode;
  50968. this.blockCode = blockCode;
  50969. this.outputType = outputType;
  50970. }
  50971. /**
  50972. * This method returns the WGSL code of the node function.
  50973. *
  50974. * @param {string} [name=this.name] - The function's name.
  50975. * @return {string} The shader code.
  50976. */
  50977. getCode( name = this.name ) {
  50978. const outputType = this.outputType !== 'void' ? '-> ' + this.outputType : '';
  50979. return `fn ${ name } ( ${ this.inputsCode.trim() } ) ${ outputType }` + this.blockCode;
  50980. }
  50981. }
  50982. /**
  50983. * A WGSL node parser.
  50984. *
  50985. * @augments NodeParser
  50986. */
  50987. class WGSLNodeParser extends NodeParser {
  50988. /**
  50989. * The method parses the given WGSL code an returns a node function.
  50990. *
  50991. * @param {string} source - The WGSL code.
  50992. * @return {WGSLNodeFunction} A node function.
  50993. */
  50994. parseFunction( source ) {
  50995. return new WGSLNodeFunction( source );
  50996. }
  50997. }
  50998. // GPUShaderStage is not defined in browsers not supporting WebGPU
  50999. const GPUShaderStage = ( typeof self !== 'undefined' ) ? self.GPUShaderStage : { VERTEX: 1, FRAGMENT: 2, COMPUTE: 4 };
  51000. const accessNames = {
  51001. [ NodeAccess.READ_ONLY ]: 'read',
  51002. [ NodeAccess.WRITE_ONLY ]: 'write',
  51003. [ NodeAccess.READ_WRITE ]: 'read_write'
  51004. };
  51005. const wrapNames = {
  51006. [ RepeatWrapping ]: 'repeat',
  51007. [ ClampToEdgeWrapping ]: 'clamp',
  51008. [ MirroredRepeatWrapping ]: 'mirror'
  51009. };
  51010. const gpuShaderStageLib = {
  51011. 'vertex': GPUShaderStage ? GPUShaderStage.VERTEX : 1,
  51012. 'fragment': GPUShaderStage ? GPUShaderStage.FRAGMENT : 2,
  51013. 'compute': GPUShaderStage ? GPUShaderStage.COMPUTE : 4
  51014. };
  51015. const supports = {
  51016. instance: true,
  51017. swizzleAssign: false,
  51018. storageBuffer: true
  51019. };
  51020. const wgslFnOpLib = {
  51021. '^^': 'tsl_xor'
  51022. };
  51023. const wgslTypeLib = {
  51024. float: 'f32',
  51025. int: 'i32',
  51026. uint: 'u32',
  51027. bool: 'bool',
  51028. color: 'vec3<f32>',
  51029. vec2: 'vec2<f32>',
  51030. ivec2: 'vec2<i32>',
  51031. uvec2: 'vec2<u32>',
  51032. bvec2: 'vec2<bool>',
  51033. vec3: 'vec3<f32>',
  51034. ivec3: 'vec3<i32>',
  51035. uvec3: 'vec3<u32>',
  51036. bvec3: 'vec3<bool>',
  51037. vec4: 'vec4<f32>',
  51038. ivec4: 'vec4<i32>',
  51039. uvec4: 'vec4<u32>',
  51040. bvec4: 'vec4<bool>',
  51041. mat2: 'mat2x2<f32>',
  51042. mat3: 'mat3x3<f32>',
  51043. mat4: 'mat4x4<f32>'
  51044. };
  51045. const wgslCodeCache = {};
  51046. const wgslPolyfill = {
  51047. tsl_xor: new CodeNode( 'fn tsl_xor( a : bool, b : bool ) -> bool { return ( a || b ) && !( a && b ); }' ),
  51048. mod_float: new CodeNode( 'fn tsl_mod_float( x : f32, y : f32 ) -> f32 { return x - y * floor( x / y ); }' ),
  51049. mod_vec2: new CodeNode( 'fn tsl_mod_vec2( x : vec2f, y : vec2f ) -> vec2f { return x - y * floor( x / y ); }' ),
  51050. mod_vec3: new CodeNode( 'fn tsl_mod_vec3( x : vec3f, y : vec3f ) -> vec3f { return x - y * floor( x / y ); }' ),
  51051. mod_vec4: new CodeNode( 'fn tsl_mod_vec4( x : vec4f, y : vec4f ) -> vec4f { return x - y * floor( x / y ); }' ),
  51052. equals_bool: new CodeNode( 'fn tsl_equals_bool( a : bool, b : bool ) -> bool { return a == b; }' ),
  51053. 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 ); }' ),
  51054. 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 ); }' ),
  51055. 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 ); }' ),
  51056. repeatWrapping_float: new CodeNode( 'fn tsl_repeatWrapping_float( coord: f32 ) -> f32 { return fract( coord ); }' ),
  51057. 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 ); }' ),
  51058. clampWrapping_float: new CodeNode( 'fn tsl_clampWrapping_float( coord: f32 ) -> f32 { return clamp( coord, 0.0, 1.0 ); }' ),
  51059. biquadraticTexture: new CodeNode( /* wgsl */`
  51060. fn tsl_biquadraticTexture( map : texture_2d<f32>, coord : vec2f, iRes : vec2u, level : u32 ) -> vec4f {
  51061. let res = vec2f( iRes );
  51062. let uvScaled = coord * res;
  51063. let uvWrapping = ( ( uvScaled % res ) + res ) % res;
  51064. // https://www.shadertoy.com/view/WtyXRy
  51065. let uv = uvWrapping - 0.5;
  51066. let iuv = floor( uv );
  51067. let f = fract( uv );
  51068. let rg1 = textureLoad( map, vec2u( iuv + vec2( 0.5, 0.5 ) ) % iRes, level );
  51069. let rg2 = textureLoad( map, vec2u( iuv + vec2( 1.5, 0.5 ) ) % iRes, level );
  51070. let rg3 = textureLoad( map, vec2u( iuv + vec2( 0.5, 1.5 ) ) % iRes, level );
  51071. let rg4 = textureLoad( map, vec2u( iuv + vec2( 1.5, 1.5 ) ) % iRes, level );
  51072. return mix( mix( rg1, rg2, f.x ), mix( rg3, rg4, f.x ), f.y );
  51073. }
  51074. ` )
  51075. };
  51076. const wgslMethods = {
  51077. dFdx: 'dpdx',
  51078. dFdy: '- dpdy',
  51079. mod_float: 'tsl_mod_float',
  51080. mod_vec2: 'tsl_mod_vec2',
  51081. mod_vec3: 'tsl_mod_vec3',
  51082. mod_vec4: 'tsl_mod_vec4',
  51083. equals_bool: 'tsl_equals_bool',
  51084. equals_bvec2: 'tsl_equals_bvec2',
  51085. equals_bvec3: 'tsl_equals_bvec3',
  51086. equals_bvec4: 'tsl_equals_bvec4',
  51087. inversesqrt: 'inverseSqrt',
  51088. bitcast: 'bitcast<f32>'
  51089. };
  51090. //
  51091. let diagnostics = '';
  51092. if ( ( typeof navigator !== 'undefined' && /Firefox|Deno/g.test( navigator.userAgent ) ) !== true ) {
  51093. diagnostics += 'diagnostic( off, derivative_uniformity );\n';
  51094. }
  51095. /**
  51096. * A node builder targeting WGSL.
  51097. *
  51098. * This module generates WGSL shader code from node materials and also
  51099. * generates the respective bindings and vertex buffer definitions. These
  51100. * data are later used by the renderer to create render and compute pipelines
  51101. * for render objects.
  51102. *
  51103. * @augments NodeBuilder
  51104. */
  51105. class WGSLNodeBuilder extends NodeBuilder {
  51106. /**
  51107. * Constructs a new WGSL node builder renderer.
  51108. *
  51109. * @param {Object3D} object - The 3D object.
  51110. * @param {Renderer} renderer - The renderer.
  51111. */
  51112. constructor( object, renderer ) {
  51113. super( object, renderer, new WGSLNodeParser() );
  51114. /**
  51115. * A dictionary that holds for each shader stage ('vertex', 'fragment', 'compute')
  51116. * another dictionary which manages UBOs per group ('render','frame','object').
  51117. *
  51118. * @type {Object<string,Object<string,NodeUniformsGroup>>}
  51119. */
  51120. this.uniformGroups = {};
  51121. /**
  51122. * A dictionary that holds for each shader stage a Map of builtins.
  51123. *
  51124. * @type {Object<string,Map<string,Object>>}
  51125. */
  51126. this.builtins = {};
  51127. /**
  51128. * A dictionary that holds for each shader stage a Set of directives.
  51129. *
  51130. * @type {Object<string,Set<string>>}
  51131. */
  51132. this.directives = {};
  51133. /**
  51134. * A map for managing scope arrays. Only relevant for when using
  51135. * {@link WorkgroupInfoNode} in context of compute shaders.
  51136. *
  51137. * @type {Map<string,Object>}
  51138. */
  51139. this.scopedArrays = new Map();
  51140. }
  51141. /**
  51142. * Generates the WGSL snippet for sampled textures.
  51143. *
  51144. * @private
  51145. * @param {Texture} texture - The texture.
  51146. * @param {string} textureProperty - The name of the texture uniform in the shader.
  51147. * @param {string} uvSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  51148. * @param {?string} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  51149. * @param {?string} offsetSnippet - A WGSL snippet that represents the offset that will be applied to the unnormalized texture coordinate before sampling the texture.
  51150. * @param {string} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  51151. * @return {string} The WGSL snippet.
  51152. */
  51153. _generateTextureSample( texture, textureProperty, uvSnippet, depthSnippet, offsetSnippet, shaderStage = this.shaderStage ) {
  51154. if ( shaderStage === 'fragment' ) {
  51155. if ( depthSnippet ) {
  51156. if ( offsetSnippet ) {
  51157. return `textureSample( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ depthSnippet }, ${ offsetSnippet } )`;
  51158. }
  51159. return `textureSample( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ depthSnippet } )`;
  51160. } else {
  51161. if ( offsetSnippet ) {
  51162. return `textureSample( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ offsetSnippet } )`;
  51163. }
  51164. return `textureSample( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet } )`;
  51165. }
  51166. } else {
  51167. return this.generateTextureSampleLevel( texture, textureProperty, uvSnippet, '0', depthSnippet );
  51168. }
  51169. }
  51170. /**
  51171. * Generates the WGSL snippet when sampling textures with explicit mip level.
  51172. *
  51173. * @private
  51174. * @param {Texture} texture - The texture.
  51175. * @param {string} textureProperty - The name of the texture uniform in the shader.
  51176. * @param {string} uvSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  51177. * @param {string} levelSnippet - A WGSL snippet that represents the mip level, with level 0 containing a full size version of the texture.
  51178. * @param {string} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  51179. * @param {?string} offsetSnippet - A WGSL snippet that represents the offset that will be applied to the unnormalized texture coordinate before sampling the texture.
  51180. * @return {string} The WGSL snippet.
  51181. */
  51182. generateTextureSampleLevel( texture, textureProperty, uvSnippet, levelSnippet, depthSnippet, offsetSnippet ) {
  51183. if ( this.isUnfilterable( texture ) === false ) {
  51184. if ( offsetSnippet ) {
  51185. return `textureSampleLevel( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ levelSnippet }, ${ offsetSnippet } )`;
  51186. }
  51187. return `textureSampleLevel( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ levelSnippet } )`;
  51188. } else if ( this.isFilteredTexture( texture ) ) {
  51189. return this.generateFilteredTexture( texture, textureProperty, uvSnippet, offsetSnippet, levelSnippet );
  51190. } else {
  51191. return this.generateTextureLod( texture, textureProperty, uvSnippet, depthSnippet, offsetSnippet, levelSnippet );
  51192. }
  51193. }
  51194. /**
  51195. * Generates a wrap function used in context of textures.
  51196. *
  51197. * @param {Texture} texture - The texture to generate the function for.
  51198. * @return {string} The name of the generated function.
  51199. */
  51200. generateWrapFunction( texture ) {
  51201. const functionName = `tsl_coord_${ wrapNames[ texture.wrapS ] }S_${ wrapNames[ texture.wrapT ] }_${ texture.is3DTexture || texture.isData3DTexture ? '3d' : '2d' }T`;
  51202. let nodeCode = wgslCodeCache[ functionName ];
  51203. if ( nodeCode === undefined ) {
  51204. const includes = [];
  51205. // For 3D textures, use vec3f; for texture arrays, keep vec2f since array index is separate
  51206. const coordType = texture.is3DTexture || texture.isData3DTexture ? 'vec3f' : 'vec2f';
  51207. let code = `fn ${ functionName }( coord : ${ coordType } ) -> ${ coordType } {\n\n\treturn ${ coordType }(\n`;
  51208. const addWrapSnippet = ( wrap, axis ) => {
  51209. if ( wrap === RepeatWrapping ) {
  51210. includes.push( wgslPolyfill.repeatWrapping_float );
  51211. code += `\t\ttsl_repeatWrapping_float( coord.${ axis } )`;
  51212. } else if ( wrap === ClampToEdgeWrapping ) {
  51213. includes.push( wgslPolyfill.clampWrapping_float );
  51214. code += `\t\ttsl_clampWrapping_float( coord.${ axis } )`;
  51215. } else if ( wrap === MirroredRepeatWrapping ) {
  51216. includes.push( wgslPolyfill.mirrorWrapping_float );
  51217. code += `\t\ttsl_mirrorWrapping_float( coord.${ axis } )`;
  51218. } else {
  51219. code += `\t\tcoord.${ axis }`;
  51220. warn( `WebGPURenderer: Unsupported texture wrap type "${ wrap }" for vertex shader.` );
  51221. }
  51222. };
  51223. addWrapSnippet( texture.wrapS, 'x' );
  51224. code += ',\n';
  51225. addWrapSnippet( texture.wrapT, 'y' );
  51226. if ( texture.is3DTexture || texture.isData3DTexture ) {
  51227. code += ',\n';
  51228. addWrapSnippet( texture.wrapR, 'z' );
  51229. }
  51230. code += '\n\t);\n\n}\n';
  51231. wgslCodeCache[ functionName ] = nodeCode = new CodeNode( code, includes );
  51232. }
  51233. nodeCode.build( this );
  51234. return functionName;
  51235. }
  51236. /**
  51237. * Generates the array declaration string.
  51238. *
  51239. * @param {string} type - The type.
  51240. * @param {?number} [count] - The count.
  51241. * @return {string} The generated value as a shader string.
  51242. */
  51243. generateArrayDeclaration( type, count ) {
  51244. return `array< ${ this.getType( type ) }, ${ count } >`;
  51245. }
  51246. /**
  51247. * Generates a WGSL variable that holds the texture dimension of the given texture.
  51248. * It also returns information about the number of layers (elements) of an arrayed
  51249. * texture as well as the cube face count of cube textures.
  51250. *
  51251. * @param {Texture} texture - The texture to generate the function for.
  51252. * @param {string} textureProperty - The name of the video texture uniform in the shader.
  51253. * @param {string} levelSnippet - A WGSL snippet that represents the mip level, with level 0 containing a full size version of the texture.
  51254. * @return {string} The name of the dimension variable.
  51255. */
  51256. generateTextureDimension( texture, textureProperty, levelSnippet ) {
  51257. const textureData = this.getDataFromNode( texture, this.shaderStage, this.globalCache );
  51258. if ( textureData.dimensionsSnippet === undefined ) textureData.dimensionsSnippet = {};
  51259. let textureDimensionNode = textureData.dimensionsSnippet[ levelSnippet ];
  51260. if ( textureData.dimensionsSnippet[ levelSnippet ] === undefined ) {
  51261. let textureDimensionsParams;
  51262. let dimensionType;
  51263. const { primarySamples } = this.renderer.backend.utils.getTextureSampleData( texture );
  51264. const isMultisampled = primarySamples > 1;
  51265. if ( texture.is3DTexture || texture.isData3DTexture ) {
  51266. dimensionType = 'vec3<u32>';
  51267. } else {
  51268. // Regular 2D textures, depth textures, etc.
  51269. dimensionType = 'vec2<u32>';
  51270. }
  51271. // Build parameters string based on texture type and multisampling
  51272. if ( isMultisampled || texture.isStorageTexture ) {
  51273. textureDimensionsParams = textureProperty;
  51274. } else {
  51275. textureDimensionsParams = `${textureProperty}${levelSnippet ? `, u32( ${ levelSnippet } )` : ''}`;
  51276. }
  51277. textureDimensionNode = new VarNode( new ExpressionNode( `textureDimensions( ${ textureDimensionsParams } )`, dimensionType ) );
  51278. textureData.dimensionsSnippet[ levelSnippet ] = textureDimensionNode;
  51279. if ( texture.isArrayTexture || texture.isDataArrayTexture || texture.is3DTexture || texture.isData3DTexture ) {
  51280. textureData.arrayLayerCount = new VarNode(
  51281. new ExpressionNode(
  51282. `textureNumLayers(${textureProperty})`,
  51283. 'u32'
  51284. )
  51285. );
  51286. }
  51287. // For cube textures, we know it's always 6 faces
  51288. if ( texture.isTextureCube ) {
  51289. textureData.cubeFaceCount = new VarNode(
  51290. new ExpressionNode( '6u', 'u32' )
  51291. );
  51292. }
  51293. }
  51294. return textureDimensionNode.build( this );
  51295. }
  51296. /**
  51297. * Generates the WGSL snippet for a manual filtered texture.
  51298. *
  51299. * @param {Texture} texture - The texture.
  51300. * @param {string} textureProperty - The name of the texture uniform in the shader.
  51301. * @param {string} uvSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  51302. * @param {?string} offsetSnippet - A WGSL snippet that represents the offset that will be applied to the unnormalized texture coordinate before sampling the texture.
  51303. * @param {string} [levelSnippet='0u'] - A WGSL snippet that represents the mip level, with level 0 containing a full size version of the texture.
  51304. * @return {string} The WGSL snippet.
  51305. */
  51306. generateFilteredTexture( texture, textureProperty, uvSnippet, offsetSnippet, levelSnippet = '0u' ) {
  51307. this._include( 'biquadraticTexture' );
  51308. const wrapFunction = this.generateWrapFunction( texture );
  51309. const textureDimension = this.generateTextureDimension( texture, textureProperty, levelSnippet );
  51310. if ( offsetSnippet ) {
  51311. uvSnippet = `${ uvSnippet } + vec2<f32>(${ offsetSnippet }) / ${ textureDimension }`;
  51312. }
  51313. return `tsl_biquadraticTexture( ${ textureProperty }, ${ wrapFunction }( ${ uvSnippet } ), ${ textureDimension }, u32( ${ levelSnippet } ) )`;
  51314. }
  51315. /**
  51316. * Generates the WGSL snippet for a texture lookup with explicit level-of-detail.
  51317. * Since it's a lookup, no sampling or filtering is applied.
  51318. *
  51319. * @param {Texture} texture - The texture.
  51320. * @param {string} textureProperty - The name of the texture uniform in the shader.
  51321. * @param {string} uvSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  51322. * @param {?string} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  51323. * @param {?string} offsetSnippet - A WGSL snippet that represents the offset that will be applied to the unnormalized texture coordinate before sampling the texture.
  51324. * @param {string} [levelSnippet='0u'] - A WGSL snippet that represents the mip level, with level 0 containing a full size version of the texture.
  51325. * @return {string} The WGSL snippet.
  51326. */
  51327. generateTextureLod( texture, textureProperty, uvSnippet, depthSnippet, offsetSnippet, levelSnippet = '0u' ) {
  51328. const wrapFunction = this.generateWrapFunction( texture );
  51329. const textureDimension = this.generateTextureDimension( texture, textureProperty, levelSnippet );
  51330. const vecType = texture.is3DTexture || texture.isData3DTexture ? 'vec3' : 'vec2';
  51331. if ( offsetSnippet ) {
  51332. uvSnippet = `${ uvSnippet } + ${ vecType }<f32>(${ offsetSnippet }) / ${ vecType }<f32>( ${ textureDimension } )`;
  51333. }
  51334. const coordSnippet = `${ vecType }<u32>( ${ wrapFunction }( ${ uvSnippet } ) * ${ vecType }<f32>( ${ textureDimension } ) )`;
  51335. return this.generateTextureLoad( texture, textureProperty, coordSnippet, levelSnippet, depthSnippet, null );
  51336. }
  51337. /**
  51338. * Generates the WGSL snippet that reads a single texel from a texture without sampling or filtering.
  51339. *
  51340. * @param {Texture} texture - The texture.
  51341. * @param {string} textureProperty - The name of the texture uniform in the shader.
  51342. * @param {string} uvIndexSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  51343. * @param {?string} levelSnippet - A WGSL snippet that represents the mip level, with level 0 containing a full size version of the texture.
  51344. * @param {?string} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  51345. * @param {?string} offsetSnippet - A WGSL snippet that represents the offset that will be applied to the unnormalized texture coordinate before sampling the texture.
  51346. * @return {string} The WGSL snippet.
  51347. */
  51348. generateTextureLoad( texture, textureProperty, uvIndexSnippet, levelSnippet, depthSnippet, offsetSnippet ) {
  51349. if ( levelSnippet === null ) levelSnippet = '0u';
  51350. if ( offsetSnippet ) {
  51351. uvIndexSnippet = `${ uvIndexSnippet } + ${ offsetSnippet }`;
  51352. }
  51353. let snippet;
  51354. if ( depthSnippet ) {
  51355. snippet = `textureLoad( ${ textureProperty }, ${ uvIndexSnippet }, ${ depthSnippet }, u32( ${ levelSnippet } ) )`;
  51356. } else {
  51357. snippet = `textureLoad( ${ textureProperty }, ${ uvIndexSnippet }, u32( ${ levelSnippet } ) )`;
  51358. if ( this.renderer.backend.compatibilityMode && texture.isDepthTexture ) {
  51359. snippet += '.x';
  51360. }
  51361. }
  51362. return snippet;
  51363. }
  51364. /**
  51365. * Generates the WGSL snippet that writes a single texel to a texture.
  51366. *
  51367. * @param {Texture} texture - The texture.
  51368. * @param {string} textureProperty - The name of the texture uniform in the shader.
  51369. * @param {string} uvIndexSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  51370. * @param {?string} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  51371. * @param {string} valueSnippet - A WGSL snippet that represent the new texel value.
  51372. * @return {string} The WGSL snippet.
  51373. */
  51374. generateTextureStore( texture, textureProperty, uvIndexSnippet, depthSnippet, valueSnippet ) {
  51375. let snippet;
  51376. if ( depthSnippet ) {
  51377. snippet = `textureStore( ${ textureProperty }, ${ uvIndexSnippet }, ${ depthSnippet }, ${ valueSnippet } )`;
  51378. } else {
  51379. snippet = `textureStore( ${ textureProperty }, ${ uvIndexSnippet }, ${ valueSnippet } )`;
  51380. }
  51381. return snippet;
  51382. }
  51383. /**
  51384. * Returns `true` if the sampled values of the given texture should be compared against a reference value.
  51385. *
  51386. * @param {Texture} texture - The texture.
  51387. * @return {boolean} Whether the sampled values of the given texture should be compared against a reference value or not.
  51388. */
  51389. isSampleCompare( texture ) {
  51390. return texture.isDepthTexture === true && texture.compareFunction !== null;
  51391. }
  51392. /**
  51393. * Returns `true` if the given texture is unfilterable.
  51394. *
  51395. * @param {Texture} texture - The texture.
  51396. * @return {boolean} Whether the given texture is unfilterable or not.
  51397. */
  51398. isUnfilterable( texture ) {
  51399. return this.getComponentTypeFromTexture( texture ) !== 'float' ||
  51400. ( ! this.isAvailable( 'float32Filterable' ) && texture.isDataTexture === true && texture.type === FloatType ) ||
  51401. ( this.isSampleCompare( texture ) === false && texture.minFilter === NearestFilter && texture.magFilter === NearestFilter ) ||
  51402. this.renderer.backend.utils.getTextureSampleData( texture ).primarySamples > 1;
  51403. }
  51404. /**
  51405. * Generates the WGSL snippet for sampling/loading the given texture.
  51406. *
  51407. * @param {Texture} texture - The texture.
  51408. * @param {string} textureProperty - The name of the texture uniform in the shader.
  51409. * @param {string} uvSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  51410. * @param {?string} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  51411. * @param {?string} offsetSnippet - A WGSL snippet that represents the offset that will be applied to the unnormalized texture coordinate before sampling the texture.
  51412. * @param {string} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  51413. * @return {string} The WGSL snippet.
  51414. */
  51415. generateTexture( texture, textureProperty, uvSnippet, depthSnippet, offsetSnippet, shaderStage = this.shaderStage ) {
  51416. let snippet = null;
  51417. if ( this.isUnfilterable( texture ) ) {
  51418. snippet = this.generateTextureLod( texture, textureProperty, uvSnippet, depthSnippet, offsetSnippet, '0', shaderStage );
  51419. } else {
  51420. snippet = this._generateTextureSample( texture, textureProperty, uvSnippet, depthSnippet, offsetSnippet, shaderStage );
  51421. }
  51422. return snippet;
  51423. }
  51424. /**
  51425. * Generates the WGSL snippet for sampling/loading the given texture using explicit gradients.
  51426. *
  51427. * @param {Texture} texture - The texture.
  51428. * @param {string} textureProperty - The name of the texture uniform in the shader.
  51429. * @param {string} uvSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  51430. * @param {Array<string>} gradSnippet - An array holding both gradient WGSL snippets.
  51431. * @param {?string} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  51432. * @param {?string} offsetSnippet - A WGSL snippet that represents the offset that will be applied to the unnormalized texture coordinate before sampling the texture.
  51433. * @param {string} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  51434. * @return {string} The WGSL snippet.
  51435. */
  51436. generateTextureGrad( texture, textureProperty, uvSnippet, gradSnippet, depthSnippet, offsetSnippet, shaderStage = this.shaderStage ) {
  51437. if ( shaderStage === 'fragment' ) {
  51438. // TODO handle i32 or u32 --> uvSnippet, array_index: A, ddx, ddy
  51439. if ( offsetSnippet ) {
  51440. return `textureSampleGrad( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ gradSnippet[ 0 ] }, ${ gradSnippet[ 1 ] }, ${ offsetSnippet } )`;
  51441. }
  51442. return `textureSampleGrad( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ gradSnippet[ 0 ] }, ${ gradSnippet[ 1 ] } )`;
  51443. } else {
  51444. error( `WebGPURenderer: THREE.TextureNode.gradient() does not support ${ shaderStage } shader.` );
  51445. }
  51446. }
  51447. /**
  51448. * Generates the WGSL snippet for sampling a depth texture and comparing the sampled depth values
  51449. * against a reference value.
  51450. *
  51451. * @param {Texture} texture - The texture.
  51452. * @param {string} textureProperty - The name of the texture uniform in the shader.
  51453. * @param {string} uvSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  51454. * @param {string} compareSnippet - A WGSL snippet that represents the reference value.
  51455. * @param {?string} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  51456. * @param {?string} offsetSnippet - A WGSL snippet that represents the offset that will be applied to the unnormalized texture coordinate before sampling the texture.
  51457. * @param {string} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  51458. * @return {string} The WGSL snippet.
  51459. */
  51460. generateTextureCompare( texture, textureProperty, uvSnippet, compareSnippet, depthSnippet, offsetSnippet, shaderStage = this.shaderStage ) {
  51461. if ( shaderStage === 'fragment' ) {
  51462. if ( texture.isDepthTexture === true && texture.isArrayTexture === true ) {
  51463. if ( offsetSnippet ) {
  51464. return `textureSampleCompare( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ depthSnippet }, ${ compareSnippet }, ${ offsetSnippet } )`;
  51465. }
  51466. return `textureSampleCompare( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ depthSnippet }, ${ compareSnippet } )`;
  51467. }
  51468. if ( offsetSnippet ) {
  51469. return `textureSampleCompare( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ compareSnippet }, ${ offsetSnippet } )`;
  51470. }
  51471. return `textureSampleCompare( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ compareSnippet } )`;
  51472. } else {
  51473. error( `WebGPURenderer: THREE.DepthTexture.compareFunction() does not support ${ shaderStage } shader.` );
  51474. }
  51475. }
  51476. /**
  51477. * Generates the WGSL snippet when sampling textures with explicit mip level.
  51478. *
  51479. * @param {Texture} texture - The texture.
  51480. * @param {string} textureProperty - The name of the texture uniform in the shader.
  51481. * @param {string} uvSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  51482. * @param {string} levelSnippet - A WGSL snippet that represents the mip level, with level 0 containing a full size version of the texture.
  51483. * @param {?string} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  51484. * @param {?string} offsetSnippet - A WGSL snippet that represents the offset that will be applied to the unnormalized texture coordinate before sampling the texture.
  51485. * @param {string} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  51486. * @return {string} The WGSL snippet.
  51487. */
  51488. generateTextureLevel( texture, textureProperty, uvSnippet, levelSnippet, depthSnippet, offsetSnippet ) {
  51489. if ( this.isUnfilterable( texture ) === false ) {
  51490. if ( offsetSnippet ) {
  51491. return `textureSampleLevel( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ levelSnippet }, ${ offsetSnippet } )`;
  51492. }
  51493. return `textureSampleLevel( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ levelSnippet } )`;
  51494. } else if ( this.isFilteredTexture( texture ) ) {
  51495. return this.generateFilteredTexture( texture, textureProperty, uvSnippet, offsetSnippet, levelSnippet );
  51496. } else {
  51497. return this.generateTextureLod( texture, textureProperty, uvSnippet, depthSnippet, offsetSnippet, levelSnippet );
  51498. }
  51499. }
  51500. /**
  51501. * Generates the WGSL snippet when sampling textures with a bias to the mip level.
  51502. *
  51503. * @param {Texture} texture - The texture.
  51504. * @param {string} textureProperty - The name of the texture uniform in the shader.
  51505. * @param {string} uvSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  51506. * @param {string} biasSnippet - A WGSL snippet that represents the bias to apply to the mip level before sampling.
  51507. * @param {?string} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  51508. * @param {?string} offsetSnippet - A WGSL snippet that represents the offset that will be applied to the unnormalized texture coordinate before sampling the texture.
  51509. * @param {string} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  51510. * @return {string} The WGSL snippet.
  51511. */
  51512. generateTextureBias( texture, textureProperty, uvSnippet, biasSnippet, depthSnippet, offsetSnippet, shaderStage = this.shaderStage ) {
  51513. if ( shaderStage === 'fragment' ) {
  51514. if ( offsetSnippet ) {
  51515. return `textureSampleBias( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ biasSnippet }, ${ offsetSnippet } )`;
  51516. }
  51517. return `textureSampleBias( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ biasSnippet } )`;
  51518. } else {
  51519. error( `WebGPURenderer: THREE.TextureNode.biasNode does not support ${ shaderStage } shader.` );
  51520. }
  51521. }
  51522. /**
  51523. * Returns a WGSL snippet that represents the property name of the given node.
  51524. *
  51525. * @param {Node} node - The node.
  51526. * @param {string} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  51527. * @return {string} The property name.
  51528. */
  51529. getPropertyName( node, shaderStage = this.shaderStage ) {
  51530. if ( node.isNodeVarying === true && node.needsInterpolation === true ) {
  51531. if ( shaderStage === 'vertex' ) {
  51532. return `varyings.${ node.name }`;
  51533. }
  51534. } else if ( node.isNodeUniform === true ) {
  51535. const name = node.name;
  51536. const type = node.type;
  51537. if ( type === 'texture' || type === 'cubeTexture' || type === 'storageTexture' || type === 'texture3D' ) {
  51538. return name;
  51539. } else if ( type === 'buffer' || type === 'storageBuffer' || type === 'indirectStorageBuffer' ) {
  51540. if ( this.isCustomStruct( node ) ) {
  51541. return name;
  51542. }
  51543. return name + '.value';
  51544. } else {
  51545. return node.groupNode.name + '.' + name;
  51546. }
  51547. }
  51548. return super.getPropertyName( node );
  51549. }
  51550. /**
  51551. * Returns the output struct name.
  51552. *
  51553. * @return {string} The name of the output struct.
  51554. */
  51555. getOutputStructName() {
  51556. return 'output';
  51557. }
  51558. /**
  51559. * Returns the native shader operator name for a given generic name.
  51560. *
  51561. * @param {string} op - The operator name to resolve.
  51562. * @return {?string} The resolved operator name.
  51563. */
  51564. getFunctionOperator( op ) {
  51565. const fnOp = wgslFnOpLib[ op ];
  51566. if ( fnOp !== undefined ) {
  51567. this._include( fnOp );
  51568. return fnOp;
  51569. }
  51570. return null;
  51571. }
  51572. /**
  51573. * Returns the node access for the given node and shader stage.
  51574. *
  51575. * @param {StorageTextureNode|StorageBufferNode} node - The storage node.
  51576. * @param {string} shaderStage - The shader stage.
  51577. * @return {string} The node access.
  51578. */
  51579. getNodeAccess( node, shaderStage ) {
  51580. if ( shaderStage !== 'compute' ) {
  51581. if ( node.isAtomic === true ) {
  51582. warn( 'WebGPURenderer: Atomic operations are only supported in compute shaders.' );
  51583. return NodeAccess.READ_WRITE;
  51584. }
  51585. return NodeAccess.READ_ONLY;
  51586. }
  51587. return node.access;
  51588. }
  51589. /**
  51590. * Returns A WGSL snippet representing the storage access.
  51591. *
  51592. * @param {StorageTextureNode|StorageBufferNode} node - The storage node.
  51593. * @param {string} shaderStage - The shader stage.
  51594. * @return {string} The WGSL snippet representing the storage access.
  51595. */
  51596. getStorageAccess( node, shaderStage ) {
  51597. return accessNames[ this.getNodeAccess( node, shaderStage ) ];
  51598. }
  51599. /**
  51600. * This method is one of the more important ones since it's responsible
  51601. * for generating a matching binding instance for the given uniform node.
  51602. *
  51603. * These bindings are later used in the renderer to create bind groups
  51604. * and layouts.
  51605. *
  51606. * @param {UniformNode} node - The uniform node.
  51607. * @param {string} type - The node data type.
  51608. * @param {string} shaderStage - The shader stage.
  51609. * @param {?string} [name=null] - An optional uniform name.
  51610. * @return {NodeUniform} The node uniform object.
  51611. */
  51612. getUniformFromNode( node, type, shaderStage, name = null ) {
  51613. const uniformNode = super.getUniformFromNode( node, type, shaderStage, name );
  51614. const nodeData = this.getDataFromNode( node, shaderStage, this.globalCache );
  51615. if ( nodeData.uniformGPU === undefined ) {
  51616. let uniformGPU;
  51617. const group = node.groupNode;
  51618. const groupName = group.name;
  51619. const bindings = this.getBindGroupArray( groupName, shaderStage );
  51620. if ( type === 'texture' || type === 'cubeTexture' || type === 'storageTexture' || type === 'texture3D' ) {
  51621. let texture = null;
  51622. const access = this.getNodeAccess( node, shaderStage );
  51623. if ( type === 'texture' || type === 'storageTexture' ) {
  51624. if ( node.value.is3DTexture === true ) {
  51625. texture = new NodeSampledTexture3D( uniformNode.name, uniformNode.node, group, access );
  51626. } else {
  51627. texture = new NodeSampledTexture( uniformNode.name, uniformNode.node, group, access );
  51628. }
  51629. } else if ( type === 'cubeTexture' ) {
  51630. texture = new NodeSampledCubeTexture( uniformNode.name, uniformNode.node, group, access );
  51631. } else if ( type === 'texture3D' ) {
  51632. texture = new NodeSampledTexture3D( uniformNode.name, uniformNode.node, group, access );
  51633. }
  51634. texture.store = node.isStorageTextureNode === true;
  51635. texture.mipLevel = texture.store ? node.mipLevel : 0;
  51636. texture.setVisibility( gpuShaderStageLib[ shaderStage ] );
  51637. if ( this.isUnfilterable( node.value ) === false && texture.store === false ) {
  51638. const sampler = new NodeSampler( `${ uniformNode.name }_sampler`, uniformNode.node, group );
  51639. sampler.setVisibility( gpuShaderStageLib[ shaderStage ] );
  51640. bindings.push( sampler, texture );
  51641. uniformGPU = [ sampler, texture ];
  51642. } else {
  51643. bindings.push( texture );
  51644. uniformGPU = [ texture ];
  51645. }
  51646. } else if ( type === 'buffer' || type === 'storageBuffer' || type === 'indirectStorageBuffer' ) {
  51647. const bufferClass = type === 'buffer' ? NodeUniformBuffer : NodeStorageBuffer;
  51648. const buffer = new bufferClass( node, group );
  51649. buffer.setVisibility( gpuShaderStageLib[ shaderStage ] );
  51650. bindings.push( buffer );
  51651. uniformGPU = buffer;
  51652. uniformNode.name = name ? name : 'NodeBuffer_' + uniformNode.id;
  51653. } else {
  51654. const uniformsStage = this.uniformGroups[ shaderStage ] || ( this.uniformGroups[ shaderStage ] = {} );
  51655. let uniformsGroup = uniformsStage[ groupName ];
  51656. if ( uniformsGroup === undefined ) {
  51657. uniformsGroup = new NodeUniformsGroup( groupName, group );
  51658. uniformsGroup.setVisibility( gpuShaderStageLib[ shaderStage ] );
  51659. uniformsStage[ groupName ] = uniformsGroup;
  51660. bindings.push( uniformsGroup );
  51661. }
  51662. uniformGPU = this.getNodeUniform( uniformNode, type );
  51663. uniformsGroup.addUniform( uniformGPU );
  51664. }
  51665. nodeData.uniformGPU = uniformGPU;
  51666. }
  51667. return uniformNode;
  51668. }
  51669. /**
  51670. * This method should be used whenever builtins are required in nodes.
  51671. * The internal builtins data structure will make sure builtins are
  51672. * defined in the WGSL source.
  51673. *
  51674. * @param {string} name - The builtin name.
  51675. * @param {string} property - The property name.
  51676. * @param {string} type - The node data type.
  51677. * @param {string} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  51678. * @return {string} The property name.
  51679. */
  51680. getBuiltin( name, property, type, shaderStage = this.shaderStage ) {
  51681. const map = this.builtins[ shaderStage ] || ( this.builtins[ shaderStage ] = new Map() );
  51682. if ( map.has( name ) === false ) {
  51683. map.set( name, {
  51684. name,
  51685. property,
  51686. type
  51687. } );
  51688. }
  51689. return property;
  51690. }
  51691. /**
  51692. * Returns `true` if the given builtin is defined in the given shader stage.
  51693. *
  51694. * @param {string} name - The builtin name.
  51695. * @param {string} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  51696. * @return {boolean} Whether the given builtin is defined in the given shader stage or not.
  51697. */
  51698. hasBuiltin( name, shaderStage = this.shaderStage ) {
  51699. return ( this.builtins[ shaderStage ] !== undefined && this.builtins[ shaderStage ].has( name ) );
  51700. }
  51701. /**
  51702. * Returns the vertex index builtin.
  51703. *
  51704. * @return {string} The vertex index.
  51705. */
  51706. getVertexIndex() {
  51707. if ( this.shaderStage === 'vertex' ) {
  51708. return this.getBuiltin( 'vertex_index', 'vertexIndex', 'u32', 'attribute' );
  51709. }
  51710. return 'vertexIndex';
  51711. }
  51712. /**
  51713. * Builds the given shader node.
  51714. *
  51715. * @param {ShaderNodeInternal} shaderNode - The shader node.
  51716. * @return {string} The WGSL function code.
  51717. */
  51718. buildFunctionCode( shaderNode ) {
  51719. const layout = shaderNode.layout;
  51720. const flowData = this.flowShaderNode( shaderNode );
  51721. const parameters = [];
  51722. for ( const input of layout.inputs ) {
  51723. parameters.push( input.name + ' : ' + this.getType( input.type ) );
  51724. }
  51725. //
  51726. let code = `fn ${ layout.name }( ${ parameters.join( ', ' ) } ) -> ${ this.getType( layout.type ) } {
  51727. ${ flowData.vars }
  51728. ${ flowData.code }
  51729. `;
  51730. if ( flowData.result ) {
  51731. code += `\treturn ${ flowData.result };\n`;
  51732. }
  51733. code += '\n}\n';
  51734. //
  51735. return code;
  51736. }
  51737. /**
  51738. * Contextually returns either the vertex stage instance index builtin
  51739. * or the linearized index of an compute invocation within a grid of workgroups.
  51740. *
  51741. * @return {string} The instance index.
  51742. */
  51743. getInstanceIndex() {
  51744. if ( this.shaderStage === 'vertex' ) {
  51745. return this.getBuiltin( 'instance_index', 'instanceIndex', 'u32', 'attribute' );
  51746. }
  51747. return 'instanceIndex';
  51748. }
  51749. /**
  51750. * Returns a builtin representing the index of a compute invocation within the scope of a workgroup load.
  51751. *
  51752. * @return {string} The invocation local index.
  51753. */
  51754. getInvocationLocalIndex() {
  51755. return this.getBuiltin( 'local_invocation_index', 'invocationLocalIndex', 'u32', 'attribute' );
  51756. }
  51757. /**
  51758. * Returns a builtin representing the size of a subgroup within the current shader.
  51759. *
  51760. * @return {string} The subgroup size.
  51761. */
  51762. getSubgroupSize() {
  51763. this.enableSubGroups();
  51764. return this.getBuiltin( 'subgroup_size', 'subgroupSize', 'u32', 'attribute' );
  51765. }
  51766. /**
  51767. * Returns a builtin representing the index of a compute invocation within the scope of a subgroup.
  51768. *
  51769. * @return {string} The invocation subgroup index.
  51770. */
  51771. getInvocationSubgroupIndex() {
  51772. this.enableSubGroups();
  51773. return this.getBuiltin( 'subgroup_invocation_id', 'invocationSubgroupIndex', 'u32', 'attribute' );
  51774. }
  51775. /**
  51776. * Returns a builtin representing the index of a compute invocation's subgroup within its workgroup.
  51777. *
  51778. * @return {string} The subgroup index.
  51779. */
  51780. getSubgroupIndex() {
  51781. this.enableSubGroups();
  51782. return this.getBuiltin( 'subgroup_id', 'subgroupIndex', 'u32', 'attribute' );
  51783. }
  51784. /**
  51785. * Overwritten as a NOP since this method is intended for the WebGL 2 backend.
  51786. *
  51787. * @return {null} Null.
  51788. */
  51789. getDrawIndex() {
  51790. return null;
  51791. }
  51792. /**
  51793. * Returns the front facing builtin.
  51794. *
  51795. * @return {string} The front facing builtin.
  51796. */
  51797. getFrontFacing() {
  51798. return this.getBuiltin( 'front_facing', 'isFront', 'bool' );
  51799. }
  51800. /**
  51801. * Returns the frag coord builtin.
  51802. *
  51803. * @return {string} The frag coord builtin.
  51804. */
  51805. getFragCoord() {
  51806. return this.getBuiltin( 'position', 'fragCoord', 'vec4<f32>' ) + '.xy';
  51807. }
  51808. /**
  51809. * Returns the frag depth builtin.
  51810. *
  51811. * @return {string} The frag depth builtin.
  51812. */
  51813. getFragDepth() {
  51814. return 'output.' + this.getBuiltin( 'frag_depth', 'depth', 'f32', 'output' );
  51815. }
  51816. /**
  51817. * Returns the clip distances builtin.
  51818. *
  51819. * @return {string} The clip distances builtin.
  51820. */
  51821. getClipDistance() {
  51822. return 'varyings.hw_clip_distances';
  51823. }
  51824. /**
  51825. * Whether to flip texture data along its vertical axis or not.
  51826. *
  51827. * @return {boolean} Returns always `false` in context of WGSL.
  51828. */
  51829. isFlipY() {
  51830. return false;
  51831. }
  51832. /**
  51833. * Enables the given directive for the given shader stage.
  51834. *
  51835. * @param {string} name - The directive name.
  51836. * @param {string} [shaderStage=this.shaderStage] - The shader stage to enable the directive for.
  51837. */
  51838. enableDirective( name, shaderStage = this.shaderStage ) {
  51839. const stage = this.directives[ shaderStage ] || ( this.directives[ shaderStage ] = new Set() );
  51840. stage.add( name );
  51841. }
  51842. /**
  51843. * Returns the directives of the given shader stage as a WGSL string.
  51844. *
  51845. * @param {string} shaderStage - The shader stage.
  51846. * @return {string} A WGSL snippet that enables the directives of the given stage.
  51847. */
  51848. getDirectives( shaderStage ) {
  51849. const snippets = [];
  51850. const directives = this.directives[ shaderStage ];
  51851. if ( directives !== undefined ) {
  51852. for ( const directive of directives ) {
  51853. snippets.push( `enable ${directive};` );
  51854. }
  51855. }
  51856. return snippets.join( '\n' );
  51857. }
  51858. /**
  51859. * Enables the 'subgroups' directive.
  51860. */
  51861. enableSubGroups() {
  51862. this.enableDirective( 'subgroups' );
  51863. }
  51864. /**
  51865. * Enables the 'subgroups-f16' directive.
  51866. */
  51867. enableSubgroupsF16() {
  51868. this.enableDirective( 'subgroups-f16' );
  51869. }
  51870. /**
  51871. * Enables the 'clip_distances' directive.
  51872. */
  51873. enableClipDistances() {
  51874. this.enableDirective( 'clip_distances' );
  51875. }
  51876. /**
  51877. * Enables the 'f16' directive.
  51878. */
  51879. enableShaderF16() {
  51880. this.enableDirective( 'f16' );
  51881. }
  51882. /**
  51883. * Enables the 'dual_source_blending' directive.
  51884. */
  51885. enableDualSourceBlending() {
  51886. this.enableDirective( 'dual_source_blending' );
  51887. }
  51888. /**
  51889. * Enables hardware clipping.
  51890. *
  51891. * @param {string} planeCount - The clipping plane count.
  51892. */
  51893. enableHardwareClipping( planeCount ) {
  51894. this.enableClipDistances();
  51895. this.getBuiltin( 'clip_distances', 'hw_clip_distances', `array<f32, ${ planeCount } >`, 'vertex' );
  51896. }
  51897. /**
  51898. * Returns the builtins of the given shader stage as a WGSL string.
  51899. *
  51900. * @param {string} shaderStage - The shader stage.
  51901. * @return {string} A WGSL snippet that represents the builtins of the given stage.
  51902. */
  51903. getBuiltins( shaderStage ) {
  51904. const snippets = [];
  51905. const builtins = this.builtins[ shaderStage ];
  51906. if ( builtins !== undefined ) {
  51907. for ( const { name, property, type } of builtins.values() ) {
  51908. snippets.push( `@builtin( ${name} ) ${property} : ${type}` );
  51909. }
  51910. }
  51911. return snippets.join( ',\n\t' );
  51912. }
  51913. /**
  51914. * This method should be used when a new scoped buffer is used in context of
  51915. * compute shaders. It adds the array to the internal data structure which is
  51916. * later used to generate the respective WGSL.
  51917. *
  51918. * @param {string} name - The array name.
  51919. * @param {string} scope - The scope.
  51920. * @param {string} bufferType - The buffer type.
  51921. * @param {string} bufferCount - The buffer count.
  51922. * @return {string} The array name.
  51923. */
  51924. getScopedArray( name, scope, bufferType, bufferCount ) {
  51925. if ( this.scopedArrays.has( name ) === false ) {
  51926. this.scopedArrays.set( name, {
  51927. name,
  51928. scope,
  51929. bufferType,
  51930. bufferCount
  51931. } );
  51932. }
  51933. return name;
  51934. }
  51935. /**
  51936. * Returns the scoped arrays of the given shader stage as a WGSL string.
  51937. *
  51938. * @param {string} shaderStage - The shader stage.
  51939. * @return {string|undefined} The WGSL snippet that defines the scoped arrays.
  51940. * Returns `undefined` when used in the vertex or fragment stage.
  51941. */
  51942. getScopedArrays( shaderStage ) {
  51943. if ( shaderStage !== 'compute' ) {
  51944. return;
  51945. }
  51946. const snippets = [];
  51947. for ( const { name, scope, bufferType, bufferCount } of this.scopedArrays.values() ) {
  51948. const type = this.getType( bufferType );
  51949. snippets.push( `var<${scope}> ${name}: array< ${type}, ${bufferCount} >;` );
  51950. }
  51951. return snippets.join( '\n' );
  51952. }
  51953. /**
  51954. * Returns the shader attributes of the given shader stage as a WGSL string.
  51955. *
  51956. * @param {string} shaderStage - The shader stage.
  51957. * @return {string} The WGSL snippet that defines the shader attributes.
  51958. */
  51959. getAttributes( shaderStage ) {
  51960. const snippets = [];
  51961. if ( shaderStage === 'compute' ) {
  51962. this.getBuiltin( 'global_invocation_id', 'globalId', 'vec3<u32>', 'attribute' );
  51963. this.getBuiltin( 'workgroup_id', 'workgroupId', 'vec3<u32>', 'attribute' );
  51964. this.getBuiltin( 'local_invocation_id', 'localId', 'vec3<u32>', 'attribute' );
  51965. this.getBuiltin( 'num_workgroups', 'numWorkgroups', 'vec3<u32>', 'attribute' );
  51966. if ( this.renderer.hasFeature( 'subgroups' ) ) {
  51967. this.enableDirective( 'subgroups', shaderStage );
  51968. this.getBuiltin( 'subgroup_size', 'subgroupSize', 'u32', 'attribute' );
  51969. }
  51970. }
  51971. if ( shaderStage === 'vertex' || shaderStage === 'compute' ) {
  51972. const builtins = this.getBuiltins( 'attribute' );
  51973. if ( builtins ) snippets.push( builtins );
  51974. const attributes = this.getAttributesArray();
  51975. for ( let index = 0, length = attributes.length; index < length; index ++ ) {
  51976. const attribute = attributes[ index ];
  51977. const name = attribute.name;
  51978. const type = this.getType( attribute.type );
  51979. snippets.push( `@location( ${index} ) ${ name } : ${ type }` );
  51980. }
  51981. }
  51982. return snippets.join( ',\n\t' );
  51983. }
  51984. /**
  51985. * Returns the members of the given struct type node as a WGSL string.
  51986. *
  51987. * @param {StructTypeNode} struct - The struct type node.
  51988. * @return {string} The WGSL snippet that defines the struct members.
  51989. */
  51990. getStructMembers( struct ) {
  51991. const snippets = [];
  51992. for ( const member of struct.members ) {
  51993. const prefix = struct.output ? '@location( ' + member.index + ' ) ' : '';
  51994. let type = this.getType( member.type );
  51995. if ( member.atomic ) {
  51996. type = 'atomic< ' + type + ' >';
  51997. }
  51998. snippets.push( `\t${ prefix + member.name } : ${ type }` );
  51999. }
  52000. if ( struct.output ) {
  52001. snippets.push( `\t${ this.getBuiltins( 'output' ) }` );
  52002. }
  52003. return snippets.join( ',\n' );
  52004. }
  52005. /**
  52006. * Returns the structs of the given shader stage as a WGSL string.
  52007. *
  52008. * @param {string} shaderStage - The shader stage.
  52009. * @return {string} The WGSL snippet that defines the structs.
  52010. */
  52011. getStructs( shaderStage ) {
  52012. let result = '';
  52013. const structs = this.structs[ shaderStage ];
  52014. if ( structs.length > 0 ) {
  52015. const snippets = [];
  52016. for ( const struct of structs ) {
  52017. let snippet = `struct ${ struct.name } {\n`;
  52018. snippet += this.getStructMembers( struct );
  52019. snippet += '\n};';
  52020. snippets.push( snippet );
  52021. }
  52022. result = '\n' + snippets.join( '\n\n' ) + '\n';
  52023. }
  52024. return result;
  52025. }
  52026. /**
  52027. * Returns a WGSL string representing a variable.
  52028. *
  52029. * @param {string} type - The variable's type.
  52030. * @param {string} name - The variable's name.
  52031. * @param {?number} [count=null] - The array length.
  52032. * @return {string} The WGSL snippet that defines a variable.
  52033. */
  52034. getVar( type, name, count = null ) {
  52035. let snippet = `var ${ name } : `;
  52036. if ( count !== null ) {
  52037. snippet += this.generateArrayDeclaration( type, count );
  52038. } else {
  52039. snippet += this.getType( type );
  52040. }
  52041. return snippet;
  52042. }
  52043. /**
  52044. * Returns the variables of the given shader stage as a WGSL string.
  52045. *
  52046. * @param {string} shaderStage - The shader stage.
  52047. * @return {string} The WGSL snippet that defines the variables.
  52048. */
  52049. getVars( shaderStage ) {
  52050. const snippets = [];
  52051. const vars = this.vars[ shaderStage ];
  52052. if ( vars !== undefined ) {
  52053. for ( const variable of vars ) {
  52054. snippets.push( `\t${ this.getVar( variable.type, variable.name, variable.count ) };` );
  52055. }
  52056. }
  52057. return `\n${ snippets.join( '\n' ) }\n`;
  52058. }
  52059. /**
  52060. * Returns the varyings of the given shader stage as a WGSL string.
  52061. *
  52062. * @param {string} shaderStage - The shader stage.
  52063. * @return {string} The WGSL snippet that defines the varyings.
  52064. */
  52065. getVaryings( shaderStage ) {
  52066. const snippets = [];
  52067. if ( shaderStage === 'vertex' ) {
  52068. this.getBuiltin( 'position', 'Vertex', 'vec4<f32>', 'vertex' );
  52069. }
  52070. if ( shaderStage === 'vertex' || shaderStage === 'fragment' ) {
  52071. const varyings = this.varyings;
  52072. const vars = this.vars[ shaderStage ];
  52073. for ( let index = 0; index < varyings.length; index ++ ) {
  52074. const varying = varyings[ index ];
  52075. if ( varying.needsInterpolation ) {
  52076. let attributesSnippet = `@location( ${index} )`;
  52077. if ( varying.interpolationType ) {
  52078. const samplingSnippet = varying.interpolationSampling !== null ? `, ${ varying.interpolationSampling } )` : ' )';
  52079. attributesSnippet += ` @interpolate( ${ varying.interpolationType }${ samplingSnippet }`;
  52080. // Otherwise, optimize interpolation when sensible
  52081. } else if ( /^(int|uint|ivec|uvec)/.test( varying.type ) ) {
  52082. attributesSnippet += ` @interpolate( ${ this.renderer.backend.compatibilityMode ? 'flat, either' : 'flat' } )`;
  52083. }
  52084. snippets.push( `${ attributesSnippet } ${ varying.name } : ${ this.getType( varying.type ) }` );
  52085. } else if ( shaderStage === 'vertex' && vars.includes( varying ) === false ) {
  52086. vars.push( varying );
  52087. }
  52088. }
  52089. }
  52090. const builtins = this.getBuiltins( shaderStage );
  52091. if ( builtins ) snippets.push( builtins );
  52092. const code = snippets.join( ',\n\t' );
  52093. return shaderStage === 'vertex' ? this._getWGSLStruct( 'VaryingsStruct', '\t' + code ) : code;
  52094. }
  52095. isCustomStruct( nodeUniform ) {
  52096. const attribute = nodeUniform.value;
  52097. const bufferNode = nodeUniform.node;
  52098. const isAttributeStructType = ( attribute.isBufferAttribute || attribute.isInstancedBufferAttribute ) && bufferNode.structTypeNode !== null;
  52099. const isStructArray =
  52100. ( bufferNode.value && bufferNode.value.array ) &&
  52101. ( typeof bufferNode.value.itemSize === 'number' && bufferNode.value.array.length > bufferNode.value.itemSize );
  52102. return isAttributeStructType && ! isStructArray;
  52103. }
  52104. /**
  52105. * Returns the uniforms of the given shader stage as a WGSL string.
  52106. *
  52107. * @param {string} shaderStage - The shader stage.
  52108. * @return {string} The WGSL snippet that defines the uniforms.
  52109. */
  52110. getUniforms( shaderStage ) {
  52111. const uniforms = this.uniforms[ shaderStage ];
  52112. const bindingSnippets = [];
  52113. const bufferSnippets = [];
  52114. const structSnippets = [];
  52115. const uniformGroups = {};
  52116. for ( const uniform of uniforms ) {
  52117. const groupName = uniform.groupNode.name;
  52118. const uniformIndexes = this.bindingsIndexes[ groupName ];
  52119. if ( uniform.type === 'texture' || uniform.type === 'cubeTexture' || uniform.type === 'storageTexture' || uniform.type === 'texture3D' ) {
  52120. const texture = uniform.node.value;
  52121. if ( this.isUnfilterable( texture ) === false && uniform.node.isStorageTextureNode !== true ) {
  52122. if ( this.isSampleCompare( texture ) ) {
  52123. bindingSnippets.push( `@binding( ${ uniformIndexes.binding ++ } ) @group( ${ uniformIndexes.group } ) var ${ uniform.name }_sampler : sampler_comparison;` );
  52124. } else {
  52125. bindingSnippets.push( `@binding( ${ uniformIndexes.binding ++ } ) @group( ${ uniformIndexes.group } ) var ${ uniform.name }_sampler : sampler;` );
  52126. }
  52127. }
  52128. let textureType;
  52129. let multisampled = '';
  52130. const { primarySamples } = this.renderer.backend.utils.getTextureSampleData( texture );
  52131. if ( primarySamples > 1 ) {
  52132. multisampled = '_multisampled';
  52133. }
  52134. if ( texture.isCubeTexture === true ) {
  52135. textureType = 'texture_cube<f32>';
  52136. } else if ( texture.isDepthTexture === true ) {
  52137. if ( this.renderer.backend.compatibilityMode && texture.compareFunction === null ) {
  52138. textureType = `texture${ multisampled }_2d<f32>`;
  52139. } else {
  52140. textureType = `texture_depth${ multisampled }_2d${ texture.isArrayTexture === true ? '_array' : '' }`;
  52141. }
  52142. } else if ( uniform.node.isStorageTextureNode === true ) {
  52143. const format = getFormat( texture );
  52144. const access = this.getStorageAccess( uniform.node, shaderStage );
  52145. const is3D = uniform.node.value.is3DTexture;
  52146. const isArrayTexture = uniform.node.value.isArrayTexture;
  52147. const dimension = is3D ? '3d' : `2d${ isArrayTexture ? '_array' : '' }`;
  52148. textureType = `texture_storage_${ dimension }<${ format }, ${ access }>`;
  52149. } else if ( texture.isArrayTexture === true || texture.isDataArrayTexture === true || texture.isCompressedArrayTexture === true ) {
  52150. textureType = 'texture_2d_array<f32>';
  52151. } else if ( texture.is3DTexture === true || texture.isData3DTexture === true ) {
  52152. textureType = 'texture_3d<f32>';
  52153. } else {
  52154. const componentPrefix = this.getComponentTypeFromTexture( texture ).charAt( 0 );
  52155. textureType = `texture${ multisampled }_2d<${ componentPrefix }32>`;
  52156. }
  52157. bindingSnippets.push( `@binding( ${ uniformIndexes.binding ++ } ) @group( ${ uniformIndexes.group } ) var ${ uniform.name } : ${ textureType };` );
  52158. } else if ( uniform.type === 'buffer' || uniform.type === 'storageBuffer' || uniform.type === 'indirectStorageBuffer' ) {
  52159. const bufferNode = uniform.node;
  52160. const bufferType = this.getType( bufferNode.getNodeType( this ) );
  52161. const bufferCount = bufferNode.bufferCount;
  52162. const bufferCountSnippet = bufferCount > 0 && uniform.type === 'buffer' ? ', ' + bufferCount : '';
  52163. const bufferAccessMode = bufferNode.isStorageBufferNode ? `storage, ${ this.getStorageAccess( bufferNode, shaderStage ) }` : 'uniform';
  52164. if ( this.isCustomStruct( uniform ) ) {
  52165. bufferSnippets.push( `@binding( ${ uniformIndexes.binding ++ } ) @group( ${ uniformIndexes.group } ) var<${ bufferAccessMode }> ${ uniform.name } : ${ bufferType };` );
  52166. } else {
  52167. const bufferTypeSnippet = bufferNode.isAtomic ? `atomic<${ bufferType }>` : `${ bufferType }`;
  52168. const bufferSnippet = `\tvalue : array< ${ bufferTypeSnippet }${ bufferCountSnippet } >`;
  52169. bufferSnippets.push( this._getWGSLStructBinding( uniform.name, bufferSnippet, bufferAccessMode, uniformIndexes.binding ++, uniformIndexes.group ) );
  52170. }
  52171. } else {
  52172. const vectorType = this.getType( this.getVectorType( uniform.type ) );
  52173. const groupName = uniform.groupNode.name;
  52174. const group = uniformGroups[ groupName ] || ( uniformGroups[ groupName ] = {
  52175. index: uniformIndexes.binding ++,
  52176. id: uniformIndexes.group,
  52177. snippets: []
  52178. } );
  52179. group.snippets.push( `\t${ uniform.name } : ${ vectorType }` );
  52180. }
  52181. }
  52182. for ( const name in uniformGroups ) {
  52183. const group = uniformGroups[ name ];
  52184. structSnippets.push( this._getWGSLStructBinding( name, group.snippets.join( ',\n' ), 'uniform', group.index, group.id ) );
  52185. }
  52186. let code = bindingSnippets.join( '\n' );
  52187. code += bufferSnippets.join( '\n' );
  52188. code += structSnippets.join( '\n' );
  52189. return code;
  52190. }
  52191. /**
  52192. * Controls the code build of the shader stages.
  52193. */
  52194. buildCode() {
  52195. const shadersData = this.material !== null ? { fragment: {}, vertex: {} } : { compute: {} };
  52196. this.sortBindingGroups();
  52197. for ( const shaderStage in shadersData ) {
  52198. this.shaderStage = shaderStage;
  52199. const stageData = shadersData[ shaderStage ];
  52200. stageData.uniforms = this.getUniforms( shaderStage );
  52201. stageData.attributes = this.getAttributes( shaderStage );
  52202. stageData.varyings = this.getVaryings( shaderStage );
  52203. stageData.structs = this.getStructs( shaderStage );
  52204. stageData.vars = this.getVars( shaderStage );
  52205. stageData.codes = this.getCodes( shaderStage );
  52206. stageData.directives = this.getDirectives( shaderStage );
  52207. stageData.scopedArrays = this.getScopedArrays( shaderStage );
  52208. //
  52209. let flow = '// code\n\n';
  52210. flow += this.flowCode[ shaderStage ];
  52211. const flowNodes = this.flowNodes[ shaderStage ];
  52212. const mainNode = flowNodes[ flowNodes.length - 1 ];
  52213. const outputNode = mainNode.outputNode;
  52214. const isOutputStruct = ( outputNode !== undefined && outputNode.isOutputStructNode === true );
  52215. for ( const node of flowNodes ) {
  52216. const flowSlotData = this.getFlowData( node/*, shaderStage*/ );
  52217. const slotName = node.name;
  52218. if ( slotName ) {
  52219. if ( flow.length > 0 ) flow += '\n';
  52220. flow += `\t// flow -> ${ slotName }\n`;
  52221. }
  52222. flow += `${ flowSlotData.code }\n\t`;
  52223. if ( node === mainNode && shaderStage !== 'compute' ) {
  52224. flow += '// result\n\n\t';
  52225. if ( shaderStage === 'vertex' ) {
  52226. flow += `varyings.Vertex = ${ flowSlotData.result };`;
  52227. } else if ( shaderStage === 'fragment' ) {
  52228. if ( isOutputStruct ) {
  52229. stageData.returnType = outputNode.getNodeType( this );
  52230. stageData.structs += 'var<private> output : ' + stageData.returnType + ';';
  52231. flow += `return ${ flowSlotData.result };`;
  52232. } else {
  52233. let structSnippet = '\t@location(0) color: vec4<f32>';
  52234. const builtins = this.getBuiltins( 'output' );
  52235. if ( builtins ) structSnippet += ',\n\t' + builtins;
  52236. stageData.returnType = 'OutputStruct';
  52237. stageData.structs += this._getWGSLStruct( 'OutputStruct', structSnippet );
  52238. stageData.structs += '\nvar<private> output : OutputStruct;';
  52239. flow += `output.color = ${ flowSlotData.result };\n\n\treturn output;`;
  52240. }
  52241. }
  52242. }
  52243. }
  52244. stageData.flow = flow;
  52245. }
  52246. this.shaderStage = null;
  52247. if ( this.material !== null ) {
  52248. this.vertexShader = this._getWGSLVertexCode( shadersData.vertex );
  52249. this.fragmentShader = this._getWGSLFragmentCode( shadersData.fragment );
  52250. } else {
  52251. // Early strictly validated in computeNode
  52252. const workgroupSize = this.object.workgroupSize;
  52253. this.computeShader = this._getWGSLComputeCode( shadersData.compute, workgroupSize );
  52254. }
  52255. }
  52256. /**
  52257. * Returns the native shader method name for a given generic name.
  52258. *
  52259. * @param {string} method - The method name to resolve.
  52260. * @param {?string} [output=null] - An optional output.
  52261. * @return {string} The resolved WGSL method name.
  52262. */
  52263. getMethod( method, output = null ) {
  52264. let wgslMethod;
  52265. if ( output !== null ) {
  52266. wgslMethod = this._getWGSLMethod( method + '_' + output );
  52267. }
  52268. if ( wgslMethod === undefined ) {
  52269. wgslMethod = this._getWGSLMethod( method );
  52270. }
  52271. return wgslMethod || method;
  52272. }
  52273. /**
  52274. * Returns the bitcast method name for a given input and outputType.
  52275. *
  52276. * @param {string} type - The output type to bitcast to.
  52277. * @return {string} The resolved WGSL bitcast invocation.
  52278. */
  52279. getBitcastMethod( type ) {
  52280. const dataType = this.getType( type );
  52281. return `bitcast<${ dataType }>`;
  52282. }
  52283. /**
  52284. * Returns the native snippet for a ternary operation.
  52285. *
  52286. * @param {string} condSnippet - The condition determining which expression gets resolved.
  52287. * @param {string} ifSnippet - The expression to resolve to if the condition is true.
  52288. * @param {string} elseSnippet - The expression to resolve to if the condition is false.
  52289. * @return {string} The resolved method name.
  52290. */
  52291. getTernary( condSnippet, ifSnippet, elseSnippet ) {
  52292. return `select( ${elseSnippet}, ${ifSnippet}, ${condSnippet} )`;
  52293. }
  52294. /**
  52295. * Returns the WGSL type of the given node data type.
  52296. *
  52297. * @param {string} type - The node data type.
  52298. * @return {string} The WGSL type.
  52299. */
  52300. getType( type ) {
  52301. return wgslTypeLib[ type ] || type;
  52302. }
  52303. /**
  52304. * Whether the requested feature is available or not.
  52305. *
  52306. * @param {string} name - The requested feature.
  52307. * @return {boolean} Whether the requested feature is supported or not.
  52308. */
  52309. isAvailable( name ) {
  52310. let result = supports[ name ];
  52311. if ( result === undefined ) {
  52312. if ( name === 'float32Filterable' ) {
  52313. result = this.renderer.hasFeature( 'float32-filterable' );
  52314. } else if ( name === 'clipDistance' ) {
  52315. result = this.renderer.hasFeature( 'clip-distances' );
  52316. }
  52317. supports[ name ] = result;
  52318. }
  52319. return result;
  52320. }
  52321. /**
  52322. * Returns the native shader method name for a given generic name.
  52323. *
  52324. * @private
  52325. * @param {string} method - The method name to resolve.
  52326. * @return {string} The resolved WGSL method name.
  52327. */
  52328. _getWGSLMethod( method ) {
  52329. if ( wgslPolyfill[ method ] !== undefined ) {
  52330. this._include( method );
  52331. }
  52332. return wgslMethods[ method ];
  52333. }
  52334. /**
  52335. * Includes the given method name into the current
  52336. * function node.
  52337. *
  52338. * @private
  52339. * @param {string} name - The method name to include.
  52340. * @return {CodeNode} The respective code node.
  52341. */
  52342. _include( name ) {
  52343. const codeNode = wgslPolyfill[ name ];
  52344. codeNode.build( this );
  52345. this.addInclude( codeNode );
  52346. return codeNode;
  52347. }
  52348. /**
  52349. * Returns a WGSL vertex shader based on the given shader data.
  52350. *
  52351. * @private
  52352. * @param {Object} shaderData - The shader data.
  52353. * @return {string} The vertex shader.
  52354. */
  52355. _getWGSLVertexCode( shaderData ) {
  52356. return `${ this.getSignature() }
  52357. // directives
  52358. ${shaderData.directives}
  52359. // structs
  52360. ${shaderData.structs}
  52361. // uniforms
  52362. ${shaderData.uniforms}
  52363. // varyings
  52364. ${shaderData.varyings}
  52365. var<private> varyings : VaryingsStruct;
  52366. // codes
  52367. ${shaderData.codes}
  52368. @vertex
  52369. fn main( ${shaderData.attributes} ) -> VaryingsStruct {
  52370. // vars
  52371. ${shaderData.vars}
  52372. // flow
  52373. ${shaderData.flow}
  52374. return varyings;
  52375. }
  52376. `;
  52377. }
  52378. /**
  52379. * Returns a WGSL fragment shader based on the given shader data.
  52380. *
  52381. * @private
  52382. * @param {Object} shaderData - The shader data.
  52383. * @return {string} The vertex shader.
  52384. */
  52385. _getWGSLFragmentCode( shaderData ) {
  52386. return `${ this.getSignature() }
  52387. // global
  52388. ${ diagnostics }
  52389. // structs
  52390. ${shaderData.structs}
  52391. // uniforms
  52392. ${shaderData.uniforms}
  52393. // codes
  52394. ${shaderData.codes}
  52395. @fragment
  52396. fn main( ${shaderData.varyings} ) -> ${shaderData.returnType} {
  52397. // vars
  52398. ${shaderData.vars}
  52399. // flow
  52400. ${shaderData.flow}
  52401. }
  52402. `;
  52403. }
  52404. /**
  52405. * Returns a WGSL compute shader based on the given shader data.
  52406. *
  52407. * @private
  52408. * @param {Object} shaderData - The shader data.
  52409. * @param {string} workgroupSize - The workgroup size.
  52410. * @return {string} The vertex shader.
  52411. */
  52412. _getWGSLComputeCode( shaderData, workgroupSize ) {
  52413. const [ workgroupSizeX, workgroupSizeY, workgroupSizeZ ] = workgroupSize;
  52414. return `${ this.getSignature() }
  52415. // directives
  52416. ${ shaderData.directives }
  52417. // system
  52418. var<private> instanceIndex : u32;
  52419. // locals
  52420. ${ shaderData.scopedArrays }
  52421. // structs
  52422. ${ shaderData.structs }
  52423. // uniforms
  52424. ${ shaderData.uniforms }
  52425. // codes
  52426. ${ shaderData.codes }
  52427. @compute @workgroup_size( ${ workgroupSizeX }, ${ workgroupSizeY }, ${ workgroupSizeZ } )
  52428. fn main( ${ shaderData.attributes } ) {
  52429. // system
  52430. instanceIndex = globalId.x
  52431. + globalId.y * ( ${ workgroupSizeX } * numWorkgroups.x )
  52432. + globalId.z * ( ${ workgroupSizeX } * numWorkgroups.x ) * ( ${ workgroupSizeY } * numWorkgroups.y );
  52433. // vars
  52434. ${ shaderData.vars }
  52435. // flow
  52436. ${ shaderData.flow }
  52437. }
  52438. `;
  52439. }
  52440. /**
  52441. * Returns a WGSL struct based on the given name and variables.
  52442. *
  52443. * @private
  52444. * @param {string} name - The struct name.
  52445. * @param {string} vars - The struct variables.
  52446. * @return {string} The WGSL snippet representing a struct.
  52447. */
  52448. _getWGSLStruct( name, vars ) {
  52449. return `
  52450. struct ${name} {
  52451. ${vars}
  52452. };`;
  52453. }
  52454. /**
  52455. * Returns a WGSL struct binding.
  52456. *
  52457. * @private
  52458. * @param {string} name - The struct name.
  52459. * @param {string} vars - The struct variables.
  52460. * @param {string} access - The access.
  52461. * @param {number} [binding=0] - The binding index.
  52462. * @param {number} [group=0] - The group index.
  52463. * @return {string} The WGSL snippet representing a struct binding.
  52464. */
  52465. _getWGSLStructBinding( name, vars, access, binding = 0, group = 0 ) {
  52466. const structName = name + 'Struct';
  52467. const structSnippet = this._getWGSLStruct( structName, vars );
  52468. return `${structSnippet}
  52469. @binding( ${ binding } ) @group( ${ group } )
  52470. var<${access}> ${ name } : ${ structName };`;
  52471. }
  52472. }
  52473. /**
  52474. * A WebGPU backend utility module with common helpers.
  52475. *
  52476. * @private
  52477. */
  52478. class WebGPUUtils {
  52479. /**
  52480. * Constructs a new utility object.
  52481. *
  52482. * @param {WebGPUBackend} backend - The WebGPU backend.
  52483. */
  52484. constructor( backend ) {
  52485. /**
  52486. * A reference to the WebGPU backend.
  52487. *
  52488. * @type {WebGPUBackend}
  52489. */
  52490. this.backend = backend;
  52491. }
  52492. /**
  52493. * Returns the depth/stencil GPU format for the given render context.
  52494. *
  52495. * @param {RenderContext} renderContext - The render context.
  52496. * @return {string} The depth/stencil GPU texture format.
  52497. */
  52498. getCurrentDepthStencilFormat( renderContext ) {
  52499. let format;
  52500. if ( renderContext.depthTexture !== null ) {
  52501. format = this.getTextureFormatGPU( renderContext.depthTexture );
  52502. } else if ( renderContext.depth && renderContext.stencil ) {
  52503. format = GPUTextureFormat.Depth24PlusStencil8;
  52504. } else if ( renderContext.depth ) {
  52505. format = GPUTextureFormat.Depth24Plus;
  52506. }
  52507. return format;
  52508. }
  52509. /**
  52510. * Returns the GPU format for the given texture.
  52511. *
  52512. * @param {Texture} texture - The texture.
  52513. * @return {string} The GPU texture format.
  52514. */
  52515. getTextureFormatGPU( texture ) {
  52516. return this.backend.get( texture ).format;
  52517. }
  52518. /**
  52519. * Returns an object that defines the multi-sampling state of the given texture.
  52520. *
  52521. * @param {Texture} texture - The texture.
  52522. * @return {Object} The multi-sampling state.
  52523. */
  52524. getTextureSampleData( texture ) {
  52525. let samples;
  52526. if ( texture.isFramebufferTexture ) {
  52527. samples = 1;
  52528. } else if ( texture.isDepthTexture && ! texture.renderTarget ) {
  52529. const renderer = this.backend.renderer;
  52530. const renderTarget = renderer.getRenderTarget();
  52531. samples = renderTarget ? renderTarget.samples : renderer.currentSamples;
  52532. } else if ( texture.renderTarget ) {
  52533. samples = texture.renderTarget.samples;
  52534. }
  52535. samples = samples || 1;
  52536. const isMSAA = samples > 1 && texture.renderTarget !== null && ( texture.isDepthTexture !== true && texture.isFramebufferTexture !== true );
  52537. const primarySamples = isMSAA ? 1 : samples;
  52538. return { samples, primarySamples, isMSAA };
  52539. }
  52540. /**
  52541. * Returns the default color attachment's GPU format of the current render context.
  52542. *
  52543. * @param {RenderContext} renderContext - The render context.
  52544. * @return {string} The GPU texture format of the default color attachment.
  52545. */
  52546. getCurrentColorFormat( renderContext ) {
  52547. let format;
  52548. if ( renderContext.textures !== null ) {
  52549. format = this.getTextureFormatGPU( renderContext.textures[ 0 ] );
  52550. } else {
  52551. format = this.getPreferredCanvasFormat(); // default context format
  52552. }
  52553. return format;
  52554. }
  52555. /**
  52556. * Returns the GPU formats of all color attachments of the current render context.
  52557. *
  52558. * @param {RenderContext} renderContext - The render context.
  52559. * @return {Array<string>} The GPU texture formats of all color attachments.
  52560. */
  52561. getCurrentColorFormats( renderContext ) {
  52562. if ( renderContext.textures !== null ) {
  52563. return renderContext.textures.map( t => this.getTextureFormatGPU( t ) );
  52564. } else {
  52565. return [ this.getPreferredCanvasFormat() ]; // default context format
  52566. }
  52567. }
  52568. /**
  52569. * Returns the output color space of the current render context.
  52570. *
  52571. * @param {RenderContext} renderContext - The render context.
  52572. * @return {string} The output color space.
  52573. */
  52574. getCurrentColorSpace( renderContext ) {
  52575. if ( renderContext.textures !== null ) {
  52576. return renderContext.textures[ 0 ].colorSpace;
  52577. }
  52578. return this.backend.renderer.outputColorSpace;
  52579. }
  52580. /**
  52581. * Returns GPU primitive topology for the given object and material.
  52582. *
  52583. * @param {Object3D} object - The 3D object.
  52584. * @param {Material} material - The material.
  52585. * @return {string} The GPU primitive topology.
  52586. */
  52587. getPrimitiveTopology( object, material ) {
  52588. if ( object.isPoints ) return GPUPrimitiveTopology.PointList;
  52589. else if ( object.isLineSegments || ( object.isMesh && material.wireframe === true ) ) return GPUPrimitiveTopology.LineList;
  52590. else if ( object.isLine ) return GPUPrimitiveTopology.LineStrip;
  52591. else if ( object.isMesh ) return GPUPrimitiveTopology.TriangleList;
  52592. }
  52593. /**
  52594. * Returns a modified sample count from the given sample count value.
  52595. *
  52596. * That is required since WebGPU only supports either 1 or 4.
  52597. *
  52598. * @param {number} sampleCount - The input sample count.
  52599. * @return {number} The (potentially updated) output sample count.
  52600. */
  52601. getSampleCount( sampleCount ) {
  52602. return sampleCount >= 4 ? 4 : 1;
  52603. }
  52604. /**
  52605. * Returns the sample count of the given render context.
  52606. *
  52607. * @param {RenderContext} renderContext - The render context.
  52608. * @return {number} The sample count.
  52609. */
  52610. getSampleCountRenderContext( renderContext ) {
  52611. if ( renderContext.textures !== null ) {
  52612. return this.getSampleCount( renderContext.sampleCount );
  52613. }
  52614. return this.getSampleCount( this.backend.renderer.currentSamples );
  52615. }
  52616. /**
  52617. * Returns the preferred canvas format.
  52618. *
  52619. * There is a separate method for this so it's possible to
  52620. * honor edge cases for specific devices.
  52621. *
  52622. * @return {string} The GPU texture format of the canvas.
  52623. */
  52624. getPreferredCanvasFormat() {
  52625. const outputType = this.backend.parameters.outputType;
  52626. if ( outputType === undefined ) {
  52627. return navigator.gpu.getPreferredCanvasFormat();
  52628. } else if ( outputType === UnsignedByteType ) {
  52629. return GPUTextureFormat.BGRA8Unorm;
  52630. } else if ( outputType === HalfFloatType ) {
  52631. return GPUTextureFormat.RGBA16Float;
  52632. } else {
  52633. throw new Error( 'Unsupported outputType' );
  52634. }
  52635. }
  52636. }
  52637. const typedArraysToVertexFormatPrefix = new Map( [
  52638. [ Int8Array, [ 'sint8', 'snorm8' ]],
  52639. [ Uint8Array, [ 'uint8', 'unorm8' ]],
  52640. [ Int16Array, [ 'sint16', 'snorm16' ]],
  52641. [ Uint16Array, [ 'uint16', 'unorm16' ]],
  52642. [ Int32Array, [ 'sint32', 'snorm32' ]],
  52643. [ Uint32Array, [ 'uint32', 'unorm32' ]],
  52644. [ Float32Array, [ 'float32', ]],
  52645. ] );
  52646. if ( typeof Float16Array !== 'undefined' ) {
  52647. typedArraysToVertexFormatPrefix.set( Float16Array, [ 'float16' ] );
  52648. }
  52649. const typedAttributeToVertexFormatPrefix = new Map( [
  52650. [ Float16BufferAttribute, [ 'float16', ]],
  52651. ] );
  52652. const typeArraysToVertexFormatPrefixForItemSize1 = new Map( [
  52653. [ Int32Array, 'sint32' ],
  52654. [ Int16Array, 'sint32' ], // patch for INT16
  52655. [ Uint32Array, 'uint32' ],
  52656. [ Uint16Array, 'uint32' ], // patch for UINT16
  52657. [ Float32Array, 'float32' ]
  52658. ] );
  52659. /**
  52660. * A WebGPU backend utility module for managing shader attributes.
  52661. *
  52662. * @private
  52663. */
  52664. class WebGPUAttributeUtils {
  52665. /**
  52666. * Constructs a new utility object.
  52667. *
  52668. * @param {WebGPUBackend} backend - The WebGPU backend.
  52669. */
  52670. constructor( backend ) {
  52671. /**
  52672. * A reference to the WebGPU backend.
  52673. *
  52674. * @type {WebGPUBackend}
  52675. */
  52676. this.backend = backend;
  52677. }
  52678. /**
  52679. * Creates the GPU buffer for the given buffer attribute.
  52680. *
  52681. * @param {BufferAttribute} attribute - The buffer attribute.
  52682. * @param {GPUBufferUsage} usage - A flag that indicates how the buffer may be used after its creation.
  52683. */
  52684. createAttribute( attribute, usage ) {
  52685. const bufferAttribute = this._getBufferAttribute( attribute );
  52686. const backend = this.backend;
  52687. const bufferData = backend.get( bufferAttribute );
  52688. let buffer = bufferData.buffer;
  52689. if ( buffer === undefined ) {
  52690. const device = backend.device;
  52691. let array = bufferAttribute.array;
  52692. // patch for INT16 and UINT16
  52693. if ( attribute.normalized === false ) {
  52694. if ( array.constructor === Int16Array || array.constructor === Int8Array ) {
  52695. array = new Int32Array( array );
  52696. } else if ( array.constructor === Uint16Array || array.constructor === Uint8Array ) {
  52697. array = new Uint32Array( array );
  52698. if ( usage & GPUBufferUsage.INDEX ) {
  52699. for ( let i = 0; i < array.length; i ++ ) {
  52700. if ( array[ i ] === 0xffff ) array[ i ] = 0xffffffff; // use correct primitive restart index
  52701. }
  52702. }
  52703. }
  52704. }
  52705. bufferAttribute.array = array;
  52706. if ( ( bufferAttribute.isStorageBufferAttribute || bufferAttribute.isStorageInstancedBufferAttribute ) && bufferAttribute.itemSize === 3 ) {
  52707. array = new array.constructor( bufferAttribute.count * 4 );
  52708. for ( let i = 0; i < bufferAttribute.count; i ++ ) {
  52709. array.set( bufferAttribute.array.subarray( i * 3, i * 3 + 3 ), i * 4 );
  52710. }
  52711. // Update BufferAttribute
  52712. bufferAttribute.itemSize = 4;
  52713. bufferAttribute.array = array;
  52714. bufferData._force3to4BytesAlignment = true;
  52715. }
  52716. // ensure 4 byte alignment
  52717. const byteLength = array.byteLength;
  52718. const size = byteLength + ( ( 4 - ( byteLength % 4 ) ) % 4 );
  52719. buffer = device.createBuffer( {
  52720. label: bufferAttribute.name,
  52721. size: size,
  52722. usage: usage,
  52723. mappedAtCreation: true
  52724. } );
  52725. new array.constructor( buffer.getMappedRange() ).set( array );
  52726. buffer.unmap();
  52727. bufferData.buffer = buffer;
  52728. }
  52729. }
  52730. /**
  52731. * Updates the GPU buffer of the given buffer attribute.
  52732. *
  52733. * @param {BufferAttribute} attribute - The buffer attribute.
  52734. */
  52735. updateAttribute( attribute ) {
  52736. const bufferAttribute = this._getBufferAttribute( attribute );
  52737. const backend = this.backend;
  52738. const device = backend.device;
  52739. const bufferData = backend.get( bufferAttribute );
  52740. const buffer = backend.get( bufferAttribute ).buffer;
  52741. let array = bufferAttribute.array;
  52742. // if storage buffer ensure 4 byte alignment
  52743. if ( bufferData._force3to4BytesAlignment === true ) {
  52744. array = new array.constructor( bufferAttribute.count * 4 );
  52745. for ( let i = 0; i < bufferAttribute.count; i ++ ) {
  52746. array.set( bufferAttribute.array.subarray( i * 3, i * 3 + 3 ), i * 4 );
  52747. }
  52748. bufferAttribute.array = array;
  52749. }
  52750. const isTypedArray = this._isTypedArray( array );
  52751. const updateRanges = bufferAttribute.updateRanges;
  52752. if ( updateRanges.length === 0 ) {
  52753. // Not using update ranges
  52754. device.queue.writeBuffer(
  52755. buffer,
  52756. 0,
  52757. array,
  52758. 0
  52759. );
  52760. } else {
  52761. const byteOffsetFactor = isTypedArray ? 1 : array.BYTES_PER_ELEMENT;
  52762. for ( let i = 0, l = updateRanges.length; i < l; i ++ ) {
  52763. const range = updateRanges[ i ];
  52764. let dataOffset, size;
  52765. if ( bufferData._force3to4BytesAlignment === true ) {
  52766. const vertexStart = Math.floor( range.start / 3 );
  52767. const vertexCount = Math.ceil( range.count / 3 );
  52768. dataOffset = vertexStart * 4 * byteOffsetFactor;
  52769. size = vertexCount * 4 * byteOffsetFactor;
  52770. } else {
  52771. dataOffset = range.start * byteOffsetFactor;
  52772. size = range.count * byteOffsetFactor;
  52773. }
  52774. const bufferOffset = dataOffset * ( isTypedArray ? array.BYTES_PER_ELEMENT : 1 ); // bufferOffset is always in bytes
  52775. device.queue.writeBuffer(
  52776. buffer,
  52777. bufferOffset,
  52778. array,
  52779. dataOffset,
  52780. size
  52781. );
  52782. }
  52783. bufferAttribute.clearUpdateRanges();
  52784. }
  52785. }
  52786. /**
  52787. * This method creates the vertex buffer layout data which are
  52788. * require when creating a render pipeline for the given render object.
  52789. *
  52790. * @param {RenderObject} renderObject - The render object.
  52791. * @return {Array<Object>} An array holding objects which describe the vertex buffer layout.
  52792. */
  52793. createShaderVertexBuffers( renderObject ) {
  52794. const attributes = renderObject.getAttributes();
  52795. const vertexBuffers = new Map();
  52796. for ( let slot = 0; slot < attributes.length; slot ++ ) {
  52797. const geometryAttribute = attributes[ slot ];
  52798. const bytesPerElement = geometryAttribute.array.BYTES_PER_ELEMENT;
  52799. const bufferAttribute = this._getBufferAttribute( geometryAttribute );
  52800. let vertexBufferLayout = vertexBuffers.get( bufferAttribute );
  52801. if ( vertexBufferLayout === undefined ) {
  52802. let arrayStride, stepMode;
  52803. if ( geometryAttribute.isInterleavedBufferAttribute === true ) {
  52804. arrayStride = geometryAttribute.data.stride * bytesPerElement;
  52805. stepMode = geometryAttribute.data.isInstancedInterleavedBuffer ? GPUInputStepMode.Instance : GPUInputStepMode.Vertex;
  52806. } else {
  52807. arrayStride = geometryAttribute.itemSize * bytesPerElement;
  52808. stepMode = geometryAttribute.isInstancedBufferAttribute ? GPUInputStepMode.Instance : GPUInputStepMode.Vertex;
  52809. }
  52810. // patch for INT16 and UINT16
  52811. if ( geometryAttribute.normalized === false && ( geometryAttribute.array.constructor === Int16Array || geometryAttribute.array.constructor === Uint16Array ) ) {
  52812. arrayStride = 4;
  52813. }
  52814. vertexBufferLayout = {
  52815. arrayStride,
  52816. attributes: [],
  52817. stepMode
  52818. };
  52819. vertexBuffers.set( bufferAttribute, vertexBufferLayout );
  52820. }
  52821. const format = this._getVertexFormat( geometryAttribute );
  52822. const offset = ( geometryAttribute.isInterleavedBufferAttribute === true ) ? geometryAttribute.offset * bytesPerElement : 0;
  52823. vertexBufferLayout.attributes.push( {
  52824. shaderLocation: slot,
  52825. offset,
  52826. format
  52827. } );
  52828. }
  52829. return Array.from( vertexBuffers.values() );
  52830. }
  52831. /**
  52832. * Destroys the GPU buffer of the given buffer attribute.
  52833. *
  52834. * @param {BufferAttribute} attribute - The buffer attribute.
  52835. */
  52836. destroyAttribute( attribute ) {
  52837. const backend = this.backend;
  52838. const data = backend.get( this._getBufferAttribute( attribute ) );
  52839. data.buffer.destroy();
  52840. backend.delete( attribute );
  52841. }
  52842. /**
  52843. * This method performs a readback operation by moving buffer data from
  52844. * a storage buffer attribute from the GPU to the CPU.
  52845. *
  52846. * @async
  52847. * @param {StorageBufferAttribute} attribute - The storage buffer attribute.
  52848. * @return {Promise<ArrayBuffer>} A promise that resolves with the buffer data when the data are ready.
  52849. */
  52850. async getArrayBufferAsync( attribute ) {
  52851. const backend = this.backend;
  52852. const device = backend.device;
  52853. const data = backend.get( this._getBufferAttribute( attribute ) );
  52854. const bufferGPU = data.buffer;
  52855. const size = bufferGPU.size;
  52856. const readBufferGPU = device.createBuffer( {
  52857. label: `${ attribute.name }_readback`,
  52858. size,
  52859. usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ
  52860. } );
  52861. const cmdEncoder = device.createCommandEncoder( {
  52862. label: `readback_encoder_${ attribute.name }`
  52863. } );
  52864. cmdEncoder.copyBufferToBuffer(
  52865. bufferGPU,
  52866. 0,
  52867. readBufferGPU,
  52868. 0,
  52869. size
  52870. );
  52871. const gpuCommands = cmdEncoder.finish();
  52872. device.queue.submit( [ gpuCommands ] );
  52873. await readBufferGPU.mapAsync( GPUMapMode.READ );
  52874. const arrayBuffer = readBufferGPU.getMappedRange();
  52875. const dstBuffer = new attribute.array.constructor( arrayBuffer.slice( 0 ) );
  52876. readBufferGPU.unmap();
  52877. return dstBuffer.buffer;
  52878. }
  52879. /**
  52880. * Returns the vertex format of the given buffer attribute.
  52881. *
  52882. * @private
  52883. * @param {BufferAttribute} geometryAttribute - The buffer attribute.
  52884. * @return {string|undefined} The vertex format (e.g. 'float32x3').
  52885. */
  52886. _getVertexFormat( geometryAttribute ) {
  52887. const { itemSize, normalized } = geometryAttribute;
  52888. const ArrayType = geometryAttribute.array.constructor;
  52889. const AttributeType = geometryAttribute.constructor;
  52890. let format;
  52891. if ( itemSize === 1 ) {
  52892. format = typeArraysToVertexFormatPrefixForItemSize1.get( ArrayType );
  52893. } else {
  52894. const prefixOptions = typedAttributeToVertexFormatPrefix.get( AttributeType ) || typedArraysToVertexFormatPrefix.get( ArrayType );
  52895. const prefix = prefixOptions[ normalized ? 1 : 0 ];
  52896. if ( prefix ) {
  52897. const bytesPerUnit = ArrayType.BYTES_PER_ELEMENT * itemSize;
  52898. const paddedBytesPerUnit = Math.floor( ( bytesPerUnit + 3 ) / 4 ) * 4;
  52899. const paddedItemSize = paddedBytesPerUnit / ArrayType.BYTES_PER_ELEMENT;
  52900. if ( paddedItemSize % 1 ) {
  52901. throw new Error( 'THREE.WebGPUAttributeUtils: Bad vertex format item size.' );
  52902. }
  52903. format = `${prefix}x${paddedItemSize}`;
  52904. }
  52905. }
  52906. if ( ! format ) {
  52907. error( 'WebGPUAttributeUtils: Vertex format not supported yet.' );
  52908. }
  52909. return format;
  52910. }
  52911. /**
  52912. * Returns `true` if the given array is a typed array.
  52913. *
  52914. * @private
  52915. * @param {any} array - The array.
  52916. * @return {boolean} Whether the given array is a typed array or not.
  52917. */
  52918. _isTypedArray( array ) {
  52919. return ArrayBuffer.isView( array ) && ! ( array instanceof DataView );
  52920. }
  52921. /**
  52922. * Utility method for handling interleaved buffer attributes correctly.
  52923. * To process them, their `InterleavedBuffer` is returned.
  52924. *
  52925. * @private
  52926. * @param {BufferAttribute} attribute - The attribute.
  52927. * @return {BufferAttribute|InterleavedBuffer}
  52928. */
  52929. _getBufferAttribute( attribute ) {
  52930. if ( attribute.isInterleavedBufferAttribute ) attribute = attribute.data;
  52931. return attribute;
  52932. }
  52933. }
  52934. /**
  52935. * A WebGPU backend utility module for managing bindings.
  52936. *
  52937. * When reading the documentation it's helpful to keep in mind that
  52938. * all class definitions starting with 'GPU*' are modules from the
  52939. * WebGPU API. So for example `BindGroup` is a class from the engine
  52940. * whereas `GPUBindGroup` is a class from WebGPU.
  52941. *
  52942. * @private
  52943. */
  52944. class WebGPUBindingUtils {
  52945. /**
  52946. * Constructs a new utility object.
  52947. *
  52948. * @param {WebGPUBackend} backend - The WebGPU backend.
  52949. */
  52950. constructor( backend ) {
  52951. /**
  52952. * A reference to the WebGPU backend.
  52953. *
  52954. * @type {WebGPUBackend}
  52955. */
  52956. this.backend = backend;
  52957. /**
  52958. * A cache for managing bind group layouts.
  52959. *
  52960. * @type {WeakMap<Array<Binding>,GPUBindGroupLayout>}
  52961. */
  52962. this.bindGroupLayoutCache = new WeakMap();
  52963. }
  52964. /**
  52965. * Creates a GPU bind group layout for the given bind group.
  52966. *
  52967. * @param {BindGroup} bindGroup - The bind group.
  52968. * @return {GPUBindGroupLayout} The GPU bind group layout.
  52969. */
  52970. createBindingsLayout( bindGroup ) {
  52971. const backend = this.backend;
  52972. const device = backend.device;
  52973. const entries = [];
  52974. let index = 0;
  52975. for ( const binding of bindGroup.bindings ) {
  52976. const bindingGPU = {
  52977. binding: index ++,
  52978. visibility: binding.visibility
  52979. };
  52980. if ( binding.isUniformBuffer || binding.isStorageBuffer ) {
  52981. const buffer = {}; // GPUBufferBindingLayout
  52982. if ( binding.isStorageBuffer ) {
  52983. if ( binding.visibility & 4 ) {
  52984. // compute
  52985. if ( binding.access === NodeAccess.READ_WRITE || binding.access === NodeAccess.WRITE_ONLY ) {
  52986. buffer.type = GPUBufferBindingType.Storage;
  52987. } else {
  52988. buffer.type = GPUBufferBindingType.ReadOnlyStorage;
  52989. }
  52990. } else {
  52991. buffer.type = GPUBufferBindingType.ReadOnlyStorage;
  52992. }
  52993. }
  52994. bindingGPU.buffer = buffer;
  52995. } else if ( binding.isSampledTexture && binding.store ) {
  52996. const storageTexture = {}; // GPUStorageTextureBindingLayout
  52997. storageTexture.format = this.backend.get( binding.texture ).texture.format;
  52998. const access = binding.access;
  52999. if ( access === NodeAccess.READ_WRITE ) {
  53000. storageTexture.access = GPUStorageTextureAccess.ReadWrite;
  53001. } else if ( access === NodeAccess.WRITE_ONLY ) {
  53002. storageTexture.access = GPUStorageTextureAccess.WriteOnly;
  53003. } else {
  53004. storageTexture.access = GPUStorageTextureAccess.ReadOnly;
  53005. }
  53006. if ( binding.texture.isArrayTexture ) {
  53007. storageTexture.viewDimension = GPUTextureViewDimension.TwoDArray;
  53008. } else if ( binding.texture.is3DTexture ) {
  53009. storageTexture.viewDimension = GPUTextureViewDimension.ThreeD;
  53010. }
  53011. bindingGPU.storageTexture = storageTexture;
  53012. } else if ( binding.isSampledTexture ) {
  53013. const texture = {}; // GPUTextureBindingLayout
  53014. const { primarySamples } = backend.utils.getTextureSampleData( binding.texture );
  53015. if ( primarySamples > 1 ) {
  53016. texture.multisampled = true;
  53017. if ( ! binding.texture.isDepthTexture ) {
  53018. texture.sampleType = GPUTextureSampleType.UnfilterableFloat;
  53019. }
  53020. }
  53021. if ( binding.texture.isDepthTexture ) {
  53022. if ( backend.compatibilityMode && binding.texture.compareFunction === null ) {
  53023. texture.sampleType = GPUTextureSampleType.UnfilterableFloat;
  53024. } else {
  53025. texture.sampleType = GPUTextureSampleType.Depth;
  53026. }
  53027. } else if ( binding.texture.isDataTexture || binding.texture.isDataArrayTexture || binding.texture.isData3DTexture ) {
  53028. const type = binding.texture.type;
  53029. if ( type === IntType ) {
  53030. texture.sampleType = GPUTextureSampleType.SInt;
  53031. } else if ( type === UnsignedIntType ) {
  53032. texture.sampleType = GPUTextureSampleType.UInt;
  53033. } else if ( type === FloatType ) {
  53034. if ( this.backend.hasFeature( 'float32-filterable' ) ) {
  53035. texture.sampleType = GPUTextureSampleType.Float;
  53036. } else {
  53037. texture.sampleType = GPUTextureSampleType.UnfilterableFloat;
  53038. }
  53039. }
  53040. }
  53041. if ( binding.isSampledCubeTexture ) {
  53042. texture.viewDimension = GPUTextureViewDimension.Cube;
  53043. } else if ( binding.texture.isArrayTexture || binding.texture.isDataArrayTexture || binding.texture.isCompressedArrayTexture ) {
  53044. texture.viewDimension = GPUTextureViewDimension.TwoDArray;
  53045. } else if ( binding.isSampledTexture3D ) {
  53046. texture.viewDimension = GPUTextureViewDimension.ThreeD;
  53047. }
  53048. bindingGPU.texture = texture;
  53049. } else if ( binding.isSampler ) {
  53050. const sampler = {}; // GPUSamplerBindingLayout
  53051. if ( binding.texture.isDepthTexture ) {
  53052. if ( binding.texture.compareFunction !== null ) {
  53053. sampler.type = GPUSamplerBindingType.Comparison;
  53054. } else if ( backend.compatibilityMode ) {
  53055. sampler.type = GPUSamplerBindingType.NonFiltering;
  53056. }
  53057. }
  53058. bindingGPU.sampler = sampler;
  53059. } else {
  53060. error( `WebGPUBindingUtils: Unsupported binding "${ binding }".` );
  53061. }
  53062. entries.push( bindingGPU );
  53063. }
  53064. return device.createBindGroupLayout( { entries } );
  53065. }
  53066. /**
  53067. * Creates bindings from the given bind group definition.
  53068. *
  53069. * @param {BindGroup} bindGroup - The bind group.
  53070. * @param {Array<BindGroup>} bindings - Array of bind groups.
  53071. * @param {number} cacheIndex - The cache index.
  53072. * @param {number} version - The version.
  53073. */
  53074. createBindings( bindGroup, bindings, cacheIndex, version = 0 ) {
  53075. const { backend, bindGroupLayoutCache } = this;
  53076. const bindingsData = backend.get( bindGroup );
  53077. // setup (static) binding layout and (dynamic) binding group
  53078. let bindLayoutGPU = bindGroupLayoutCache.get( bindGroup.bindingsReference );
  53079. if ( bindLayoutGPU === undefined ) {
  53080. bindLayoutGPU = this.createBindingsLayout( bindGroup );
  53081. bindGroupLayoutCache.set( bindGroup.bindingsReference, bindLayoutGPU );
  53082. }
  53083. let bindGroupGPU;
  53084. if ( cacheIndex > 0 ) {
  53085. if ( bindingsData.groups === undefined ) {
  53086. bindingsData.groups = [];
  53087. bindingsData.versions = [];
  53088. }
  53089. if ( bindingsData.versions[ cacheIndex ] === version ) {
  53090. bindGroupGPU = bindingsData.groups[ cacheIndex ];
  53091. }
  53092. }
  53093. if ( bindGroupGPU === undefined ) {
  53094. bindGroupGPU = this.createBindGroup( bindGroup, bindLayoutGPU );
  53095. if ( cacheIndex > 0 ) {
  53096. bindingsData.groups[ cacheIndex ] = bindGroupGPU;
  53097. bindingsData.versions[ cacheIndex ] = version;
  53098. }
  53099. }
  53100. bindingsData.group = bindGroupGPU;
  53101. bindingsData.layout = bindLayoutGPU;
  53102. }
  53103. /**
  53104. * Updates a buffer binding.
  53105. *
  53106. * @param {Buffer} binding - The buffer binding to update.
  53107. */
  53108. updateBinding( binding ) {
  53109. const backend = this.backend;
  53110. const device = backend.device;
  53111. const buffer = binding.buffer;
  53112. const bufferGPU = backend.get( binding ).buffer;
  53113. device.queue.writeBuffer( bufferGPU, 0, buffer, 0 );
  53114. }
  53115. /**
  53116. * Creates a GPU bind group for the camera index.
  53117. *
  53118. * @param {Uint32Array} data - The index data.
  53119. * @param {GPUBindGroupLayout} layout - The GPU bind group layout.
  53120. * @return {GPUBindGroup} The GPU bind group.
  53121. */
  53122. createBindGroupIndex( data, layout ) {
  53123. const backend = this.backend;
  53124. const device = backend.device;
  53125. const usage = GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST;
  53126. const index = data[ 0 ];
  53127. const buffer = device.createBuffer( {
  53128. label: 'bindingCameraIndex_' + index,
  53129. size: 16, // uint(4) * 4
  53130. usage: usage
  53131. } );
  53132. device.queue.writeBuffer( buffer, 0, data, 0 );
  53133. const entries = [ { binding: 0, resource: { buffer } } ];
  53134. return device.createBindGroup( {
  53135. label: 'bindGroupCameraIndex_' + index,
  53136. layout,
  53137. entries
  53138. } );
  53139. }
  53140. /**
  53141. * Creates a GPU bind group for the given bind group and GPU layout.
  53142. *
  53143. * @param {BindGroup} bindGroup - The bind group.
  53144. * @param {GPUBindGroupLayout} layoutGPU - The GPU bind group layout.
  53145. * @return {GPUBindGroup} The GPU bind group.
  53146. */
  53147. createBindGroup( bindGroup, layoutGPU ) {
  53148. const backend = this.backend;
  53149. const device = backend.device;
  53150. let bindingPoint = 0;
  53151. const entriesGPU = [];
  53152. for ( const binding of bindGroup.bindings ) {
  53153. if ( binding.isUniformBuffer ) {
  53154. const bindingData = backend.get( binding );
  53155. if ( bindingData.buffer === undefined ) {
  53156. const byteLength = binding.byteLength;
  53157. const usage = GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST;
  53158. const bufferGPU = device.createBuffer( {
  53159. label: 'bindingBuffer_' + binding.name,
  53160. size: byteLength,
  53161. usage: usage
  53162. } );
  53163. bindingData.buffer = bufferGPU;
  53164. }
  53165. entriesGPU.push( { binding: bindingPoint, resource: { buffer: bindingData.buffer } } );
  53166. } else if ( binding.isStorageBuffer ) {
  53167. const bindingData = backend.get( binding );
  53168. if ( bindingData.buffer === undefined ) {
  53169. const attribute = binding.attribute;
  53170. //const usage = GPUBufferUsage.STORAGE | GPUBufferUsage.VERTEX | /*GPUBufferUsage.COPY_SRC |*/ GPUBufferUsage.COPY_DST;
  53171. //backend.attributeUtils.createAttribute( attribute, usage ); // @TODO: Move it to universal renderer
  53172. bindingData.buffer = backend.get( attribute ).buffer;
  53173. }
  53174. entriesGPU.push( { binding: bindingPoint, resource: { buffer: bindingData.buffer } } );
  53175. } else if ( binding.isSampledTexture ) {
  53176. const textureData = backend.get( binding.texture );
  53177. let resourceGPU;
  53178. if ( textureData.externalTexture !== undefined ) {
  53179. resourceGPU = device.importExternalTexture( { source: textureData.externalTexture } );
  53180. } else {
  53181. const mipLevelCount = binding.store ? 1 : textureData.texture.mipLevelCount;
  53182. const baseMipLevel = binding.store ? binding.mipLevel : 0;
  53183. let propertyName = `view-${ textureData.texture.width }-${ textureData.texture.height }`;
  53184. if ( textureData.texture.depthOrArrayLayers > 1 ) {
  53185. propertyName += `-${ textureData.texture.depthOrArrayLayers }`;
  53186. }
  53187. propertyName += `-${ mipLevelCount }-${ baseMipLevel }`;
  53188. resourceGPU = textureData[ propertyName ];
  53189. if ( resourceGPU === undefined ) {
  53190. const aspectGPU = GPUTextureAspect.All;
  53191. let dimensionViewGPU;
  53192. if ( binding.isSampledCubeTexture ) {
  53193. dimensionViewGPU = GPUTextureViewDimension.Cube;
  53194. } else if ( binding.isSampledTexture3D ) {
  53195. dimensionViewGPU = GPUTextureViewDimension.ThreeD;
  53196. } else if ( binding.texture.isArrayTexture || binding.texture.isDataArrayTexture || binding.texture.isCompressedArrayTexture ) {
  53197. dimensionViewGPU = GPUTextureViewDimension.TwoDArray;
  53198. } else {
  53199. dimensionViewGPU = GPUTextureViewDimension.TwoD;
  53200. }
  53201. resourceGPU = textureData[ propertyName ] = textureData.texture.createView( { aspect: aspectGPU, dimension: dimensionViewGPU, mipLevelCount, baseMipLevel } );
  53202. }
  53203. }
  53204. entriesGPU.push( { binding: bindingPoint, resource: resourceGPU } );
  53205. } else if ( binding.isSampler ) {
  53206. const textureGPU = backend.get( binding.texture );
  53207. entriesGPU.push( { binding: bindingPoint, resource: textureGPU.sampler } );
  53208. }
  53209. bindingPoint ++;
  53210. }
  53211. return device.createBindGroup( {
  53212. label: 'bindGroup_' + bindGroup.name,
  53213. layout: layoutGPU,
  53214. entries: entriesGPU
  53215. } );
  53216. }
  53217. }
  53218. /**
  53219. * A WebGPU backend utility module for managing pipelines.
  53220. *
  53221. * @private
  53222. */
  53223. class WebGPUPipelineUtils {
  53224. /**
  53225. * Constructs a new utility object.
  53226. *
  53227. * @param {WebGPUBackend} backend - The WebGPU backend.
  53228. */
  53229. constructor( backend ) {
  53230. /**
  53231. * A reference to the WebGPU backend.
  53232. *
  53233. * @type {WebGPUBackend}
  53234. */
  53235. this.backend = backend;
  53236. /**
  53237. * A Weak Map that tracks the active pipeline for render or compute passes.
  53238. *
  53239. * @private
  53240. * @type {WeakMap<(GPURenderPassEncoder|GPUComputePassEncoder),(GPURenderPipeline|GPUComputePipeline)>}
  53241. */
  53242. this._activePipelines = new WeakMap();
  53243. }
  53244. /**
  53245. * Sets the given pipeline for the given pass. The method makes sure to only set the
  53246. * pipeline when necessary.
  53247. *
  53248. * @param {(GPURenderPassEncoder|GPUComputePassEncoder)} pass - The pass encoder.
  53249. * @param {(GPURenderPipeline|GPUComputePipeline)} pipeline - The pipeline.
  53250. */
  53251. setPipeline( pass, pipeline ) {
  53252. const currentPipeline = this._activePipelines.get( pass );
  53253. if ( currentPipeline !== pipeline ) {
  53254. pass.setPipeline( pipeline );
  53255. this._activePipelines.set( pass, pipeline );
  53256. }
  53257. }
  53258. /**
  53259. * Returns the sample count derived from the given render context.
  53260. *
  53261. * @private
  53262. * @param {RenderContext} renderContext - The render context.
  53263. * @return {number} The sample count.
  53264. */
  53265. _getSampleCount( renderContext ) {
  53266. return this.backend.utils.getSampleCountRenderContext( renderContext );
  53267. }
  53268. /**
  53269. * Creates a render pipeline for the given render object.
  53270. *
  53271. * @param {RenderObject} renderObject - The render object.
  53272. * @param {Array<Promise>} promises - An array of compilation promises which are used in `compileAsync()`.
  53273. */
  53274. createRenderPipeline( renderObject, promises ) {
  53275. const { object, material, geometry, pipeline } = renderObject;
  53276. const { vertexProgram, fragmentProgram } = pipeline;
  53277. const backend = this.backend;
  53278. const device = backend.device;
  53279. const utils = backend.utils;
  53280. const pipelineData = backend.get( pipeline );
  53281. // bind group layouts
  53282. const bindGroupLayouts = [];
  53283. for ( const bindGroup of renderObject.getBindings() ) {
  53284. const bindingsData = backend.get( bindGroup );
  53285. bindGroupLayouts.push( bindingsData.layout );
  53286. }
  53287. // vertex buffers
  53288. const vertexBuffers = backend.attributeUtils.createShaderVertexBuffers( renderObject );
  53289. // blending
  53290. let blending;
  53291. if ( material.blending !== NoBlending && ( material.blending !== NormalBlending || material.transparent !== false ) ) {
  53292. blending = this._getBlending( material );
  53293. }
  53294. // stencil
  53295. let stencilFront = {};
  53296. if ( material.stencilWrite === true ) {
  53297. stencilFront = {
  53298. compare: this._getStencilCompare( material ),
  53299. failOp: this._getStencilOperation( material.stencilFail ),
  53300. depthFailOp: this._getStencilOperation( material.stencilZFail ),
  53301. passOp: this._getStencilOperation( material.stencilZPass )
  53302. };
  53303. }
  53304. const colorWriteMask = this._getColorWriteMask( material );
  53305. const targets = [];
  53306. if ( renderObject.context.textures !== null ) {
  53307. const textures = renderObject.context.textures;
  53308. for ( let i = 0; i < textures.length; i ++ ) {
  53309. const colorFormat = utils.getTextureFormatGPU( textures[ i ] );
  53310. targets.push( {
  53311. format: colorFormat,
  53312. blend: blending,
  53313. writeMask: colorWriteMask
  53314. } );
  53315. }
  53316. } else {
  53317. const colorFormat = utils.getCurrentColorFormat( renderObject.context );
  53318. targets.push( {
  53319. format: colorFormat,
  53320. blend: blending,
  53321. writeMask: colorWriteMask
  53322. } );
  53323. }
  53324. const vertexModule = backend.get( vertexProgram ).module;
  53325. const fragmentModule = backend.get( fragmentProgram ).module;
  53326. const primitiveState = this._getPrimitiveState( object, geometry, material );
  53327. const depthCompare = this._getDepthCompare( material );
  53328. const depthStencilFormat = utils.getCurrentDepthStencilFormat( renderObject.context );
  53329. const sampleCount = this._getSampleCount( renderObject.context );
  53330. const pipelineDescriptor = {
  53331. label: `renderPipeline_${ material.name || material.type }_${ material.id }`,
  53332. vertex: Object.assign( {}, vertexModule, { buffers: vertexBuffers } ),
  53333. fragment: Object.assign( {}, fragmentModule, { targets } ),
  53334. primitive: primitiveState,
  53335. multisample: {
  53336. count: sampleCount,
  53337. alphaToCoverageEnabled: material.alphaToCoverage && sampleCount > 1
  53338. },
  53339. layout: device.createPipelineLayout( {
  53340. bindGroupLayouts
  53341. } )
  53342. };
  53343. const depthStencil = {};
  53344. const renderDepth = renderObject.context.depth;
  53345. const renderStencil = renderObject.context.stencil;
  53346. if ( renderDepth === true || renderStencil === true ) {
  53347. if ( renderDepth === true ) {
  53348. depthStencil.format = depthStencilFormat;
  53349. depthStencil.depthWriteEnabled = material.depthWrite;
  53350. depthStencil.depthCompare = depthCompare;
  53351. }
  53352. if ( renderStencil === true ) {
  53353. depthStencil.stencilFront = stencilFront;
  53354. depthStencil.stencilBack = {}; // three.js does not provide an API to configure the back function (gl.stencilFuncSeparate() was never used)
  53355. depthStencil.stencilReadMask = material.stencilFuncMask;
  53356. depthStencil.stencilWriteMask = material.stencilWriteMask;
  53357. }
  53358. if ( material.polygonOffset === true ) {
  53359. depthStencil.depthBias = material.polygonOffsetUnits;
  53360. depthStencil.depthBiasSlopeScale = material.polygonOffsetFactor;
  53361. depthStencil.depthBiasClamp = 0; // three.js does not provide an API to configure this value
  53362. }
  53363. pipelineDescriptor.depthStencil = depthStencil;
  53364. }
  53365. // create pipeline
  53366. device.pushErrorScope( 'validation' );
  53367. if ( promises === null ) {
  53368. pipelineData.pipeline = device.createRenderPipeline( pipelineDescriptor );
  53369. device.popErrorScope().then( ( err ) => {
  53370. if ( err !== null ) {
  53371. pipelineData.error = true;
  53372. error( err.message );
  53373. }
  53374. } );
  53375. } else {
  53376. const p = new Promise( async ( resolve /*, reject*/ ) => {
  53377. try {
  53378. pipelineData.pipeline = await device.createRenderPipelineAsync( pipelineDescriptor );
  53379. } catch ( err ) { }
  53380. const errorScope = await device.popErrorScope();
  53381. if ( errorScope !== null ) {
  53382. pipelineData.error = true;
  53383. error( errorScope.message );
  53384. }
  53385. resolve();
  53386. } );
  53387. promises.push( p );
  53388. }
  53389. }
  53390. /**
  53391. * Creates GPU render bundle encoder for the given render context.
  53392. *
  53393. * @param {RenderContext} renderContext - The render context.
  53394. * @param {?string} [label='renderBundleEncoder'] - The label.
  53395. * @return {GPURenderBundleEncoder} The GPU render bundle encoder.
  53396. */
  53397. createBundleEncoder( renderContext, label = 'renderBundleEncoder' ) {
  53398. const backend = this.backend;
  53399. const { utils, device } = backend;
  53400. const depthStencilFormat = utils.getCurrentDepthStencilFormat( renderContext );
  53401. const colorFormats = utils.getCurrentColorFormats( renderContext );
  53402. const sampleCount = this._getSampleCount( renderContext );
  53403. const descriptor = {
  53404. label,
  53405. colorFormats,
  53406. depthStencilFormat,
  53407. sampleCount
  53408. };
  53409. return device.createRenderBundleEncoder( descriptor );
  53410. }
  53411. /**
  53412. * Creates a compute pipeline for the given compute node.
  53413. *
  53414. * @param {ComputePipeline} pipeline - The compute pipeline.
  53415. * @param {Array<BindGroup>} bindings - The bindings.
  53416. */
  53417. createComputePipeline( pipeline, bindings ) {
  53418. const backend = this.backend;
  53419. const device = backend.device;
  53420. const computeProgram = backend.get( pipeline.computeProgram ).module;
  53421. const pipelineGPU = backend.get( pipeline );
  53422. // bind group layouts
  53423. const bindGroupLayouts = [];
  53424. for ( const bindingsGroup of bindings ) {
  53425. const bindingsData = backend.get( bindingsGroup );
  53426. bindGroupLayouts.push( bindingsData.layout );
  53427. }
  53428. pipelineGPU.pipeline = device.createComputePipeline( {
  53429. compute: computeProgram,
  53430. layout: device.createPipelineLayout( {
  53431. bindGroupLayouts
  53432. } )
  53433. } );
  53434. }
  53435. /**
  53436. * Returns the blending state as a descriptor object required
  53437. * for the pipeline creation.
  53438. *
  53439. * @private
  53440. * @param {Material} material - The material.
  53441. * @return {Object} The blending state.
  53442. */
  53443. _getBlending( material ) {
  53444. let color, alpha;
  53445. const blending = material.blending;
  53446. const blendSrc = material.blendSrc;
  53447. const blendDst = material.blendDst;
  53448. const blendEquation = material.blendEquation;
  53449. if ( blending === CustomBlending ) {
  53450. const blendSrcAlpha = material.blendSrcAlpha !== null ? material.blendSrcAlpha : blendSrc;
  53451. const blendDstAlpha = material.blendDstAlpha !== null ? material.blendDstAlpha : blendDst;
  53452. const blendEquationAlpha = material.blendEquationAlpha !== null ? material.blendEquationAlpha : blendEquation;
  53453. color = {
  53454. srcFactor: this._getBlendFactor( blendSrc ),
  53455. dstFactor: this._getBlendFactor( blendDst ),
  53456. operation: this._getBlendOperation( blendEquation )
  53457. };
  53458. alpha = {
  53459. srcFactor: this._getBlendFactor( blendSrcAlpha ),
  53460. dstFactor: this._getBlendFactor( blendDstAlpha ),
  53461. operation: this._getBlendOperation( blendEquationAlpha )
  53462. };
  53463. } else {
  53464. const premultipliedAlpha = material.premultipliedAlpha;
  53465. const setBlend = ( srcRGB, dstRGB, srcAlpha, dstAlpha ) => {
  53466. color = {
  53467. srcFactor: srcRGB,
  53468. dstFactor: dstRGB,
  53469. operation: GPUBlendOperation.Add
  53470. };
  53471. alpha = {
  53472. srcFactor: srcAlpha,
  53473. dstFactor: dstAlpha,
  53474. operation: GPUBlendOperation.Add
  53475. };
  53476. };
  53477. if ( premultipliedAlpha ) {
  53478. switch ( blending ) {
  53479. case NormalBlending:
  53480. setBlend( GPUBlendFactor.One, GPUBlendFactor.OneMinusSrcAlpha, GPUBlendFactor.One, GPUBlendFactor.OneMinusSrcAlpha );
  53481. break;
  53482. case AdditiveBlending:
  53483. setBlend( GPUBlendFactor.One, GPUBlendFactor.One, GPUBlendFactor.One, GPUBlendFactor.One );
  53484. break;
  53485. case SubtractiveBlending:
  53486. setBlend( GPUBlendFactor.Zero, GPUBlendFactor.OneMinusSrc, GPUBlendFactor.Zero, GPUBlendFactor.One );
  53487. break;
  53488. case MultiplyBlending:
  53489. setBlend( GPUBlendFactor.Dst, GPUBlendFactor.OneMinusSrcAlpha, GPUBlendFactor.Zero, GPUBlendFactor.One );
  53490. break;
  53491. }
  53492. } else {
  53493. switch ( blending ) {
  53494. case NormalBlending:
  53495. setBlend( GPUBlendFactor.SrcAlpha, GPUBlendFactor.OneMinusSrcAlpha, GPUBlendFactor.One, GPUBlendFactor.OneMinusSrcAlpha );
  53496. break;
  53497. case AdditiveBlending:
  53498. setBlend( GPUBlendFactor.SrcAlpha, GPUBlendFactor.One, GPUBlendFactor.One, GPUBlendFactor.One );
  53499. break;
  53500. case SubtractiveBlending:
  53501. error( 'WebGPURenderer: SubtractiveBlending requires material.premultipliedAlpha = true' );
  53502. break;
  53503. case MultiplyBlending:
  53504. error( 'WebGPURenderer: MultiplyBlending requires material.premultipliedAlpha = true' );
  53505. break;
  53506. }
  53507. }
  53508. }
  53509. if ( color !== undefined && alpha !== undefined ) {
  53510. return { color, alpha };
  53511. } else {
  53512. error( 'WebGPURenderer: Invalid blending: ', blending );
  53513. }
  53514. }
  53515. /**
  53516. * Returns the GPU blend factor which is required for the pipeline creation.
  53517. *
  53518. * @private
  53519. * @param {number} blend - The blend factor as a three.js constant.
  53520. * @return {string} The GPU blend factor.
  53521. */
  53522. _getBlendFactor( blend ) {
  53523. let blendFactor;
  53524. switch ( blend ) {
  53525. case ZeroFactor:
  53526. blendFactor = GPUBlendFactor.Zero;
  53527. break;
  53528. case OneFactor:
  53529. blendFactor = GPUBlendFactor.One;
  53530. break;
  53531. case SrcColorFactor:
  53532. blendFactor = GPUBlendFactor.Src;
  53533. break;
  53534. case OneMinusSrcColorFactor:
  53535. blendFactor = GPUBlendFactor.OneMinusSrc;
  53536. break;
  53537. case SrcAlphaFactor:
  53538. blendFactor = GPUBlendFactor.SrcAlpha;
  53539. break;
  53540. case OneMinusSrcAlphaFactor:
  53541. blendFactor = GPUBlendFactor.OneMinusSrcAlpha;
  53542. break;
  53543. case DstColorFactor:
  53544. blendFactor = GPUBlendFactor.Dst;
  53545. break;
  53546. case OneMinusDstColorFactor:
  53547. blendFactor = GPUBlendFactor.OneMinusDst;
  53548. break;
  53549. case DstAlphaFactor:
  53550. blendFactor = GPUBlendFactor.DstAlpha;
  53551. break;
  53552. case OneMinusDstAlphaFactor:
  53553. blendFactor = GPUBlendFactor.OneMinusDstAlpha;
  53554. break;
  53555. case SrcAlphaSaturateFactor:
  53556. blendFactor = GPUBlendFactor.SrcAlphaSaturated;
  53557. break;
  53558. case BlendColorFactor:
  53559. blendFactor = GPUBlendFactor.Constant;
  53560. break;
  53561. case OneMinusBlendColorFactor:
  53562. blendFactor = GPUBlendFactor.OneMinusConstant;
  53563. break;
  53564. default:
  53565. error( 'WebGPURenderer: Blend factor not supported.', blend );
  53566. }
  53567. return blendFactor;
  53568. }
  53569. /**
  53570. * Returns the GPU stencil compare function which is required for the pipeline creation.
  53571. *
  53572. * @private
  53573. * @param {Material} material - The material.
  53574. * @return {string} The GPU stencil compare function.
  53575. */
  53576. _getStencilCompare( material ) {
  53577. let stencilCompare;
  53578. const stencilFunc = material.stencilFunc;
  53579. switch ( stencilFunc ) {
  53580. case NeverStencilFunc:
  53581. stencilCompare = GPUCompareFunction.Never;
  53582. break;
  53583. case AlwaysStencilFunc:
  53584. stencilCompare = GPUCompareFunction.Always;
  53585. break;
  53586. case LessStencilFunc:
  53587. stencilCompare = GPUCompareFunction.Less;
  53588. break;
  53589. case LessEqualStencilFunc:
  53590. stencilCompare = GPUCompareFunction.LessEqual;
  53591. break;
  53592. case EqualStencilFunc:
  53593. stencilCompare = GPUCompareFunction.Equal;
  53594. break;
  53595. case GreaterEqualStencilFunc:
  53596. stencilCompare = GPUCompareFunction.GreaterEqual;
  53597. break;
  53598. case GreaterStencilFunc:
  53599. stencilCompare = GPUCompareFunction.Greater;
  53600. break;
  53601. case NotEqualStencilFunc:
  53602. stencilCompare = GPUCompareFunction.NotEqual;
  53603. break;
  53604. default:
  53605. error( 'WebGPURenderer: Invalid stencil function.', stencilFunc );
  53606. }
  53607. return stencilCompare;
  53608. }
  53609. /**
  53610. * Returns the GPU stencil operation which is required for the pipeline creation.
  53611. *
  53612. * @private
  53613. * @param {number} op - A three.js constant defining the stencil operation.
  53614. * @return {string} The GPU stencil operation.
  53615. */
  53616. _getStencilOperation( op ) {
  53617. let stencilOperation;
  53618. switch ( op ) {
  53619. case KeepStencilOp:
  53620. stencilOperation = GPUStencilOperation.Keep;
  53621. break;
  53622. case ZeroStencilOp:
  53623. stencilOperation = GPUStencilOperation.Zero;
  53624. break;
  53625. case ReplaceStencilOp:
  53626. stencilOperation = GPUStencilOperation.Replace;
  53627. break;
  53628. case InvertStencilOp:
  53629. stencilOperation = GPUStencilOperation.Invert;
  53630. break;
  53631. case IncrementStencilOp:
  53632. stencilOperation = GPUStencilOperation.IncrementClamp;
  53633. break;
  53634. case DecrementStencilOp:
  53635. stencilOperation = GPUStencilOperation.DecrementClamp;
  53636. break;
  53637. case IncrementWrapStencilOp:
  53638. stencilOperation = GPUStencilOperation.IncrementWrap;
  53639. break;
  53640. case DecrementWrapStencilOp:
  53641. stencilOperation = GPUStencilOperation.DecrementWrap;
  53642. break;
  53643. default:
  53644. error( 'WebGPURenderer: Invalid stencil operation.', stencilOperation );
  53645. }
  53646. return stencilOperation;
  53647. }
  53648. /**
  53649. * Returns the GPU blend operation which is required for the pipeline creation.
  53650. *
  53651. * @private
  53652. * @param {number} blendEquation - A three.js constant defining the blend equation.
  53653. * @return {string} The GPU blend operation.
  53654. */
  53655. _getBlendOperation( blendEquation ) {
  53656. let blendOperation;
  53657. switch ( blendEquation ) {
  53658. case AddEquation:
  53659. blendOperation = GPUBlendOperation.Add;
  53660. break;
  53661. case SubtractEquation:
  53662. blendOperation = GPUBlendOperation.Subtract;
  53663. break;
  53664. case ReverseSubtractEquation:
  53665. blendOperation = GPUBlendOperation.ReverseSubtract;
  53666. break;
  53667. case MinEquation:
  53668. blendOperation = GPUBlendOperation.Min;
  53669. break;
  53670. case MaxEquation:
  53671. blendOperation = GPUBlendOperation.Max;
  53672. break;
  53673. default:
  53674. error( 'WebGPUPipelineUtils: Blend equation not supported.', blendEquation );
  53675. }
  53676. return blendOperation;
  53677. }
  53678. /**
  53679. * Returns the primitive state as a descriptor object required
  53680. * for the pipeline creation.
  53681. *
  53682. * @private
  53683. * @param {Object3D} object - The 3D object.
  53684. * @param {BufferGeometry} geometry - The geometry.
  53685. * @param {Material} material - The material.
  53686. * @return {Object} The primitive state.
  53687. */
  53688. _getPrimitiveState( object, geometry, material ) {
  53689. const descriptor = {};
  53690. const utils = this.backend.utils;
  53691. //
  53692. descriptor.topology = utils.getPrimitiveTopology( object, material );
  53693. if ( geometry.index !== null && object.isLine === true && object.isLineSegments !== true ) {
  53694. descriptor.stripIndexFormat = ( geometry.index.array instanceof Uint16Array ) ? GPUIndexFormat.Uint16 : GPUIndexFormat.Uint32;
  53695. }
  53696. //
  53697. let flipSided = ( material.side === BackSide );
  53698. if ( object.isMesh && object.matrixWorld.determinant() < 0 ) flipSided = ! flipSided;
  53699. descriptor.frontFace = ( flipSided === true ) ? GPUFrontFace.CW : GPUFrontFace.CCW;
  53700. //
  53701. descriptor.cullMode = ( material.side === DoubleSide ) ? GPUCullMode.None : GPUCullMode.Back;
  53702. return descriptor;
  53703. }
  53704. /**
  53705. * Returns the GPU color write mask which is required for the pipeline creation.
  53706. *
  53707. * @private
  53708. * @param {Material} material - The material.
  53709. * @return {number} The GPU color write mask.
  53710. */
  53711. _getColorWriteMask( material ) {
  53712. return ( material.colorWrite === true ) ? GPUColorWriteFlags.All : GPUColorWriteFlags.None;
  53713. }
  53714. /**
  53715. * Returns the GPU depth compare function which is required for the pipeline creation.
  53716. *
  53717. * @private
  53718. * @param {Material} material - The material.
  53719. * @return {string} The GPU depth compare function.
  53720. */
  53721. _getDepthCompare( material ) {
  53722. let depthCompare;
  53723. if ( material.depthTest === false ) {
  53724. depthCompare = GPUCompareFunction.Always;
  53725. } else {
  53726. const depthFunc = material.depthFunc;
  53727. switch ( depthFunc ) {
  53728. case NeverDepth:
  53729. depthCompare = GPUCompareFunction.Never;
  53730. break;
  53731. case AlwaysDepth:
  53732. depthCompare = GPUCompareFunction.Always;
  53733. break;
  53734. case LessDepth:
  53735. depthCompare = GPUCompareFunction.Less;
  53736. break;
  53737. case LessEqualDepth:
  53738. depthCompare = GPUCompareFunction.LessEqual;
  53739. break;
  53740. case EqualDepth:
  53741. depthCompare = GPUCompareFunction.Equal;
  53742. break;
  53743. case GreaterEqualDepth:
  53744. depthCompare = GPUCompareFunction.GreaterEqual;
  53745. break;
  53746. case GreaterDepth:
  53747. depthCompare = GPUCompareFunction.Greater;
  53748. break;
  53749. case NotEqualDepth:
  53750. depthCompare = GPUCompareFunction.NotEqual;
  53751. break;
  53752. default:
  53753. error( 'WebGPUPipelineUtils: Invalid depth function.', depthFunc );
  53754. }
  53755. }
  53756. return depthCompare;
  53757. }
  53758. }
  53759. /**
  53760. * Manages a pool of WebGPU timestamp queries for performance measurement.
  53761. * Extends the base TimestampQueryPool to provide WebGPU-specific implementation.
  53762. *
  53763. * @augments TimestampQueryPool
  53764. */
  53765. class WebGPUTimestampQueryPool extends TimestampQueryPool {
  53766. /**
  53767. * Creates a new WebGPU timestamp query pool.
  53768. *
  53769. * @param {GPUDevice} device - The WebGPU device to create queries on.
  53770. * @param {string} type - The type identifier for this query pool.
  53771. * @param {number} [maxQueries=2048] - Maximum number of queries this pool can hold.
  53772. */
  53773. constructor( device, type, maxQueries = 2048 ) {
  53774. super( maxQueries );
  53775. this.device = device;
  53776. this.type = type;
  53777. this.querySet = this.device.createQuerySet( {
  53778. type: 'timestamp',
  53779. count: this.maxQueries,
  53780. label: `queryset_global_timestamp_${type}`
  53781. } );
  53782. const bufferSize = this.maxQueries * 8;
  53783. this.resolveBuffer = this.device.createBuffer( {
  53784. label: `buffer_timestamp_resolve_${type}`,
  53785. size: bufferSize,
  53786. usage: GPUBufferUsage.QUERY_RESOLVE | GPUBufferUsage.COPY_SRC
  53787. } );
  53788. this.resultBuffer = this.device.createBuffer( {
  53789. label: `buffer_timestamp_result_${type}`,
  53790. size: bufferSize,
  53791. usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ
  53792. } );
  53793. }
  53794. /**
  53795. * Allocates a pair of queries for a given render context.
  53796. *
  53797. * @param {string} uid - A unique identifier for the render context.
  53798. * @returns {?number} The base offset for the allocated queries, or null if allocation failed.
  53799. */
  53800. allocateQueriesForContext( uid ) {
  53801. if ( ! this.trackTimestamp || this.isDisposed ) return null;
  53802. if ( this.currentQueryIndex + 2 > this.maxQueries ) {
  53803. warnOnce( `WebGPUTimestampQueryPool [${ this.type }]: Maximum number of queries exceeded, when using trackTimestamp it is necessary to resolves the queries via renderer.resolveTimestampsAsync( THREE.TimestampQuery.${ this.type.toUpperCase() } ).` );
  53804. return null;
  53805. }
  53806. const baseOffset = this.currentQueryIndex;
  53807. this.currentQueryIndex += 2;
  53808. this.queryOffsets.set( uid, baseOffset );
  53809. return baseOffset;
  53810. }
  53811. /**
  53812. * Asynchronously resolves all pending queries and returns the total duration.
  53813. * If there's already a pending resolve operation, returns that promise instead.
  53814. *
  53815. * @async
  53816. * @returns {Promise<number>} The total duration in milliseconds, or the last valid value if resolution fails.
  53817. */
  53818. async resolveQueriesAsync() {
  53819. if ( ! this.trackTimestamp || this.currentQueryIndex === 0 || this.isDisposed ) {
  53820. return this.lastValue;
  53821. }
  53822. if ( this.pendingResolve ) {
  53823. return this.pendingResolve;
  53824. }
  53825. this.pendingResolve = this._resolveQueries();
  53826. try {
  53827. const result = await this.pendingResolve;
  53828. return result;
  53829. } finally {
  53830. this.pendingResolve = null;
  53831. }
  53832. }
  53833. /**
  53834. * Internal method to resolve queries and calculate total duration.
  53835. *
  53836. * @async
  53837. * @private
  53838. * @returns {Promise<number>} The total duration in milliseconds.
  53839. */
  53840. async _resolveQueries() {
  53841. if ( this.isDisposed ) {
  53842. return this.lastValue;
  53843. }
  53844. try {
  53845. if ( this.resultBuffer.mapState !== 'unmapped' ) {
  53846. return this.lastValue;
  53847. }
  53848. const currentOffsets = new Map( this.queryOffsets );
  53849. const queryCount = this.currentQueryIndex;
  53850. const bytesUsed = queryCount * 8;
  53851. // Reset state before GPU work
  53852. this.currentQueryIndex = 0;
  53853. this.queryOffsets.clear();
  53854. const commandEncoder = this.device.createCommandEncoder();
  53855. commandEncoder.resolveQuerySet(
  53856. this.querySet,
  53857. 0,
  53858. queryCount,
  53859. this.resolveBuffer,
  53860. 0
  53861. );
  53862. commandEncoder.copyBufferToBuffer(
  53863. this.resolveBuffer,
  53864. 0,
  53865. this.resultBuffer,
  53866. 0,
  53867. bytesUsed
  53868. );
  53869. const commandBuffer = commandEncoder.finish();
  53870. this.device.queue.submit( [ commandBuffer ] );
  53871. if ( this.resultBuffer.mapState !== 'unmapped' ) {
  53872. return this.lastValue;
  53873. }
  53874. // Create and track the mapping operation
  53875. await this.resultBuffer.mapAsync( GPUMapMode.READ, 0, bytesUsed );
  53876. if ( this.isDisposed ) {
  53877. if ( this.resultBuffer.mapState === 'mapped' ) {
  53878. this.resultBuffer.unmap();
  53879. }
  53880. return this.lastValue;
  53881. }
  53882. //
  53883. const times = new BigUint64Array( this.resultBuffer.getMappedRange( 0, bytesUsed ) );
  53884. const framesDuration = {};
  53885. const frames = [];
  53886. for ( const [ uid, baseOffset ] of currentOffsets ) {
  53887. const match = uid.match( /^(.*):f(\d+)$/ );
  53888. const frame = parseInt( match[ 2 ] );
  53889. if ( frames.includes( frame ) === false ) {
  53890. frames.push( frame );
  53891. }
  53892. if ( framesDuration[ frame ] === undefined ) framesDuration[ frame ] = 0;
  53893. const startTime = times[ baseOffset ];
  53894. const endTime = times[ baseOffset + 1 ];
  53895. const duration = Number( endTime - startTime ) / 1e6;
  53896. this.timestamps.set( uid, duration );
  53897. framesDuration[ frame ] += duration;
  53898. }
  53899. // Return the total duration of the last frame
  53900. const totalDuration = framesDuration[ frames[ frames.length - 1 ] ];
  53901. this.resultBuffer.unmap();
  53902. this.lastValue = totalDuration;
  53903. this.frames = frames;
  53904. return totalDuration;
  53905. } catch ( error ) {
  53906. error( 'Error resolving queries:', error );
  53907. if ( this.resultBuffer.mapState === 'mapped' ) {
  53908. this.resultBuffer.unmap();
  53909. }
  53910. return this.lastValue;
  53911. }
  53912. }
  53913. /**
  53914. * Dispose of the query pool.
  53915. *
  53916. * @async
  53917. * @returns {Promise} A Promise that resolves when the dispose has been executed.
  53918. */
  53919. async dispose() {
  53920. if ( this.isDisposed ) {
  53921. return;
  53922. }
  53923. this.isDisposed = true;
  53924. // Wait for pending resolve operation
  53925. if ( this.pendingResolve ) {
  53926. try {
  53927. await this.pendingResolve;
  53928. } catch ( error ) {
  53929. error( 'Error waiting for pending resolve:', error );
  53930. }
  53931. }
  53932. // Ensure buffer is unmapped before destroying
  53933. if ( this.resultBuffer && this.resultBuffer.mapState === 'mapped' ) {
  53934. try {
  53935. this.resultBuffer.unmap();
  53936. } catch ( error ) {
  53937. error( 'Error unmapping buffer:', error );
  53938. }
  53939. }
  53940. // Destroy resources
  53941. if ( this.querySet ) {
  53942. this.querySet.destroy();
  53943. this.querySet = null;
  53944. }
  53945. if ( this.resolveBuffer ) {
  53946. this.resolveBuffer.destroy();
  53947. this.resolveBuffer = null;
  53948. }
  53949. if ( this.resultBuffer ) {
  53950. this.resultBuffer.destroy();
  53951. this.resultBuffer = null;
  53952. }
  53953. this.queryOffsets.clear();
  53954. this.pendingResolve = null;
  53955. }
  53956. }
  53957. /*// debugger tools
  53958. import 'https://greggman.github.io/webgpu-avoid-redundant-state-setting/webgpu-check-redundant-state-setting.js';
  53959. //*/
  53960. /**
  53961. * A backend implementation targeting WebGPU.
  53962. *
  53963. * @private
  53964. * @augments Backend
  53965. */
  53966. class WebGPUBackend extends Backend {
  53967. /**
  53968. * WebGPUBackend options.
  53969. *
  53970. * @typedef {Object} WebGPUBackend~Options
  53971. * @property {boolean} [logarithmicDepthBuffer=false] - Whether logarithmic depth buffer is enabled or not.
  53972. * @property {boolean} [alpha=true] - Whether the default framebuffer (which represents the final contents of the canvas) should be transparent or opaque.
  53973. * @property {boolean} [compatibilityMode=false] - Whether the backend should be in compatibility mode or not.
  53974. * @property {boolean} [depth=true] - Whether the default framebuffer should have a depth buffer or not.
  53975. * @property {boolean} [stencil=false] - Whether the default framebuffer should have a stencil buffer or not.
  53976. * @property {boolean} [antialias=false] - Whether MSAA as the default anti-aliasing should be enabled or not.
  53977. * @property {number} [samples=0] - When `antialias` is `true`, `4` samples are used by default. Set this parameter to any other integer value than 0 to overwrite the default.
  53978. * @property {boolean} [forceWebGL=false] - If set to `true`, the renderer uses a WebGL 2 backend no matter if WebGPU is supported or not.
  53979. * @property {boolean} [trackTimestamp=false] - Whether to track timestamps with a Timestamp Query API or not.
  53980. * @property {string} [powerPreference=undefined] - The power preference.
  53981. * @property {Object} [requiredLimits=undefined] - Specifies the limits that are required by the device request. The request will fail if the adapter cannot provide these limits.
  53982. * @property {GPUDevice} [device=undefined] - If there is an existing GPU device on app level, it can be passed to the renderer as a parameter.
  53983. * @property {number} [outputType=undefined] - Texture type for output to canvas. By default, device's preferred format is used; other formats may incur overhead.
  53984. */
  53985. /**
  53986. * Constructs a new WebGPU backend.
  53987. *
  53988. * @param {WebGPUBackend~Options} [parameters] - The configuration parameter.
  53989. */
  53990. constructor( parameters = {} ) {
  53991. super( parameters );
  53992. /**
  53993. * This flag can be used for type testing.
  53994. *
  53995. * @type {boolean}
  53996. * @readonly
  53997. * @default true
  53998. */
  53999. this.isWebGPUBackend = true;
  54000. // some parameters require default values other than "undefined"
  54001. this.parameters.alpha = ( parameters.alpha === undefined ) ? true : parameters.alpha;
  54002. this.parameters.compatibilityMode = ( parameters.compatibilityMode === undefined ) ? false : parameters.compatibilityMode;
  54003. this.parameters.requiredLimits = ( parameters.requiredLimits === undefined ) ? {} : parameters.requiredLimits;
  54004. /**
  54005. * Indicates whether the backend is in compatibility mode or not.
  54006. * @type {boolean}
  54007. * @default false
  54008. */
  54009. this.compatibilityMode = this.parameters.compatibilityMode;
  54010. /**
  54011. * A reference to the device.
  54012. *
  54013. * @type {?GPUDevice}
  54014. * @default null
  54015. */
  54016. this.device = null;
  54017. /**
  54018. * A reference to the default render pass descriptor.
  54019. *
  54020. * @type {?Object}
  54021. * @default null
  54022. */
  54023. this.defaultRenderPassdescriptor = null;
  54024. /**
  54025. * A reference to a backend module holding common utility functions.
  54026. *
  54027. * @type {WebGPUUtils}
  54028. */
  54029. this.utils = new WebGPUUtils( this );
  54030. /**
  54031. * A reference to a backend module holding shader attribute-related
  54032. * utility functions.
  54033. *
  54034. * @type {WebGPUAttributeUtils}
  54035. */
  54036. this.attributeUtils = new WebGPUAttributeUtils( this );
  54037. /**
  54038. * A reference to a backend module holding shader binding-related
  54039. * utility functions.
  54040. *
  54041. * @type {WebGPUBindingUtils}
  54042. */
  54043. this.bindingUtils = new WebGPUBindingUtils( this );
  54044. /**
  54045. * A reference to a backend module holding shader pipeline-related
  54046. * utility functions.
  54047. *
  54048. * @type {WebGPUPipelineUtils}
  54049. */
  54050. this.pipelineUtils = new WebGPUPipelineUtils( this );
  54051. /**
  54052. * A reference to a backend module holding shader texture-related
  54053. * utility functions.
  54054. *
  54055. * @type {WebGPUTextureUtils}
  54056. */
  54057. this.textureUtils = new WebGPUTextureUtils( this );
  54058. /**
  54059. * A map that manages the resolve buffers for occlusion queries.
  54060. *
  54061. * @type {Map<number,GPUBuffer>}
  54062. */
  54063. this.occludedResolveCache = new Map();
  54064. }
  54065. /**
  54066. * Initializes the backend so it is ready for usage.
  54067. *
  54068. * @async
  54069. * @param {Renderer} renderer - The renderer.
  54070. * @return {Promise} A Promise that resolves when the backend has been initialized.
  54071. */
  54072. async init( renderer ) {
  54073. await super.init( renderer );
  54074. //
  54075. const parameters = this.parameters;
  54076. // create the device if it is not passed with parameters
  54077. let device;
  54078. if ( parameters.device === undefined ) {
  54079. const adapterOptions = {
  54080. powerPreference: parameters.powerPreference,
  54081. featureLevel: parameters.compatibilityMode ? 'compatibility' : undefined
  54082. };
  54083. const adapter = ( typeof navigator !== 'undefined' ) ? await navigator.gpu.requestAdapter( adapterOptions ) : null;
  54084. if ( adapter === null ) {
  54085. throw new Error( 'WebGPUBackend: Unable to create WebGPU adapter.' );
  54086. }
  54087. // feature support
  54088. const features = Object.values( GPUFeatureName );
  54089. const supportedFeatures = [];
  54090. for ( const name of features ) {
  54091. if ( adapter.features.has( name ) ) {
  54092. supportedFeatures.push( name );
  54093. }
  54094. }
  54095. const deviceDescriptor = {
  54096. requiredFeatures: supportedFeatures,
  54097. requiredLimits: parameters.requiredLimits
  54098. };
  54099. device = await adapter.requestDevice( deviceDescriptor );
  54100. } else {
  54101. device = parameters.device;
  54102. }
  54103. device.lost.then( ( info ) => {
  54104. const deviceLossInfo = {
  54105. api: 'WebGPU',
  54106. message: info.message || 'Unknown reason',
  54107. reason: info.reason || null,
  54108. originalEvent: info
  54109. };
  54110. renderer.onDeviceLost( deviceLossInfo );
  54111. } );
  54112. this.device = device;
  54113. this.trackTimestamp = this.trackTimestamp && this.hasFeature( GPUFeatureName.TimestampQuery );
  54114. this.updateSize();
  54115. }
  54116. /**
  54117. * A reference to the context.
  54118. *
  54119. * @type {?GPUCanvasContext}
  54120. * @default null
  54121. */
  54122. get context() {
  54123. const canvasTarget = this.renderer.getCanvasTarget();
  54124. const canvasData = this.get( canvasTarget );
  54125. let context = canvasData.context;
  54126. if ( context === undefined ) {
  54127. const parameters = this.parameters;
  54128. if ( canvasTarget.isDefaultCanvasTarget === true && parameters.context !== undefined ) {
  54129. context = parameters.context;
  54130. } else {
  54131. context = canvasTarget.domElement.getContext( 'webgpu' );
  54132. }
  54133. // OffscreenCanvas does not have setAttribute, see #22811
  54134. if ( 'setAttribute' in canvasTarget.domElement ) canvasTarget.domElement.setAttribute( 'data-engine', `three.js r${ REVISION } webgpu` );
  54135. const alphaMode = parameters.alpha ? 'premultiplied' : 'opaque';
  54136. const toneMappingMode = parameters.outputType === HalfFloatType ? 'extended' : 'standard';
  54137. context.configure( {
  54138. device: this.device,
  54139. format: this.utils.getPreferredCanvasFormat(),
  54140. usage: GPUTextureUsage.RENDER_ATTACHMENT | GPUTextureUsage.COPY_SRC,
  54141. alphaMode: alphaMode,
  54142. toneMapping: {
  54143. mode: toneMappingMode
  54144. }
  54145. } );
  54146. canvasData.context = context;
  54147. }
  54148. return context;
  54149. }
  54150. /**
  54151. * The coordinate system of the backend.
  54152. *
  54153. * @type {number}
  54154. * @readonly
  54155. */
  54156. get coordinateSystem() {
  54157. return WebGPUCoordinateSystem;
  54158. }
  54159. /**
  54160. * This method performs a readback operation by moving buffer data from
  54161. * a storage buffer attribute from the GPU to the CPU.
  54162. *
  54163. * @async
  54164. * @param {StorageBufferAttribute} attribute - The storage buffer attribute.
  54165. * @return {Promise<ArrayBuffer>} A promise that resolves with the buffer data when the data are ready.
  54166. */
  54167. async getArrayBufferAsync( attribute ) {
  54168. return await this.attributeUtils.getArrayBufferAsync( attribute );
  54169. }
  54170. /**
  54171. * Returns the backend's rendering context.
  54172. *
  54173. * @return {GPUCanvasContext} The rendering context.
  54174. */
  54175. getContext() {
  54176. return this.context;
  54177. }
  54178. /**
  54179. * Returns the default render pass descriptor.
  54180. *
  54181. * In WebGPU, the default framebuffer must be configured
  54182. * like custom framebuffers so the backend needs a render
  54183. * pass descriptor even when rendering directly to screen.
  54184. *
  54185. * @private
  54186. * @return {Object} The render pass descriptor.
  54187. */
  54188. _getDefaultRenderPassDescriptor() {
  54189. const renderer = this.renderer;
  54190. const canvasTarget = renderer.getCanvasTarget();
  54191. const canvasData = this.get( canvasTarget );
  54192. const samples = renderer.currentSamples;
  54193. let descriptor = canvasData.descriptor;
  54194. if ( descriptor === undefined || canvasData.samples !== samples ) {
  54195. descriptor = {
  54196. colorAttachments: [ {
  54197. view: null
  54198. } ]
  54199. };
  54200. if ( renderer.depth === true || renderer.stencil === true ) {
  54201. descriptor.depthStencilAttachment = {
  54202. view: this.textureUtils.getDepthBuffer( renderer.depth, renderer.stencil ).createView()
  54203. };
  54204. }
  54205. const colorAttachment = descriptor.colorAttachments[ 0 ];
  54206. if ( samples > 0 ) {
  54207. colorAttachment.view = this.textureUtils.getColorBuffer().createView();
  54208. } else {
  54209. colorAttachment.resolveTarget = undefined;
  54210. }
  54211. canvasData.descriptor = descriptor;
  54212. canvasData.samples = samples;
  54213. }
  54214. const colorAttachment = descriptor.colorAttachments[ 0 ];
  54215. if ( samples > 0 ) {
  54216. colorAttachment.resolveTarget = this.context.getCurrentTexture().createView();
  54217. } else {
  54218. colorAttachment.view = this.context.getCurrentTexture().createView();
  54219. }
  54220. return descriptor;
  54221. }
  54222. /**
  54223. * Internal to determine if the current render target is a render target array with depth 2D array texture.
  54224. *
  54225. * @param {RenderContext} renderContext - The render context.
  54226. * @return {boolean} Whether the render target is a render target array with depth 2D array texture.
  54227. *
  54228. * @private
  54229. */
  54230. _isRenderCameraDepthArray( renderContext ) {
  54231. return renderContext.depthTexture && renderContext.depthTexture.image.depth > 1 && renderContext.camera.isArrayCamera;
  54232. }
  54233. /**
  54234. * Returns the render pass descriptor for the given render context.
  54235. *
  54236. * @private
  54237. * @param {RenderContext} renderContext - The render context.
  54238. * @param {Object} colorAttachmentsConfig - Configuration object for the color attachments.
  54239. * @return {Object} The render pass descriptor.
  54240. */
  54241. _getRenderPassDescriptor( renderContext, colorAttachmentsConfig = {} ) {
  54242. const renderTarget = renderContext.renderTarget;
  54243. const renderTargetData = this.get( renderTarget );
  54244. let descriptors = renderTargetData.descriptors;
  54245. if ( descriptors === undefined ||
  54246. renderTargetData.width !== renderTarget.width ||
  54247. renderTargetData.height !== renderTarget.height ||
  54248. renderTargetData.samples !== renderTarget.samples
  54249. ) {
  54250. descriptors = {};
  54251. renderTargetData.descriptors = descriptors;
  54252. }
  54253. const cacheKey = renderContext.getCacheKey();
  54254. let descriptorBase = descriptors[ cacheKey ];
  54255. if ( descriptorBase === undefined ) {
  54256. const textures = renderContext.textures;
  54257. const textureViews = [];
  54258. let sliceIndex;
  54259. const isRenderCameraDepthArray = this._isRenderCameraDepthArray( renderContext );
  54260. for ( let i = 0; i < textures.length; i ++ ) {
  54261. const textureData = this.get( textures[ i ] );
  54262. const viewDescriptor = {
  54263. label: `colorAttachment_${ i }`,
  54264. baseMipLevel: renderContext.activeMipmapLevel,
  54265. mipLevelCount: 1,
  54266. baseArrayLayer: renderContext.activeCubeFace,
  54267. arrayLayerCount: 1,
  54268. dimension: GPUTextureViewDimension.TwoD
  54269. };
  54270. if ( renderTarget.isRenderTarget3D ) {
  54271. sliceIndex = renderContext.activeCubeFace;
  54272. viewDescriptor.baseArrayLayer = 0;
  54273. viewDescriptor.dimension = GPUTextureViewDimension.ThreeD;
  54274. viewDescriptor.depthOrArrayLayers = textures[ i ].image.depth;
  54275. } else if ( renderTarget.isRenderTarget && textures[ i ].image.depth > 1 ) {
  54276. if ( isRenderCameraDepthArray === true ) {
  54277. const cameras = renderContext.camera.cameras;
  54278. for ( let layer = 0; layer < cameras.length; layer ++ ) {
  54279. const layerViewDescriptor = {
  54280. ...viewDescriptor,
  54281. baseArrayLayer: layer,
  54282. arrayLayerCount: 1,
  54283. dimension: GPUTextureViewDimension.TwoD
  54284. };
  54285. const textureView = textureData.texture.createView( layerViewDescriptor );
  54286. textureViews.push( {
  54287. view: textureView,
  54288. resolveTarget: undefined,
  54289. depthSlice: undefined
  54290. } );
  54291. }
  54292. } else {
  54293. viewDescriptor.dimension = GPUTextureViewDimension.TwoDArray;
  54294. viewDescriptor.depthOrArrayLayers = textures[ i ].image.depth;
  54295. }
  54296. }
  54297. if ( isRenderCameraDepthArray !== true ) {
  54298. const textureView = textureData.texture.createView( viewDescriptor );
  54299. let view, resolveTarget;
  54300. if ( textureData.msaaTexture !== undefined ) {
  54301. view = textureData.msaaTexture.createView();
  54302. resolveTarget = textureView;
  54303. } else {
  54304. view = textureView;
  54305. resolveTarget = undefined;
  54306. }
  54307. textureViews.push( {
  54308. view,
  54309. resolveTarget,
  54310. depthSlice: sliceIndex
  54311. } );
  54312. }
  54313. }
  54314. descriptorBase = { textureViews };
  54315. if ( renderContext.depth ) {
  54316. const depthTextureData = this.get( renderContext.depthTexture );
  54317. const options = {};
  54318. if ( renderContext.depthTexture.isArrayTexture ) {
  54319. options.dimension = GPUTextureViewDimension.TwoD;
  54320. options.arrayLayerCount = 1;
  54321. options.baseArrayLayer = renderContext.activeCubeFace;
  54322. }
  54323. descriptorBase.depthStencilView = depthTextureData.texture.createView( options );
  54324. }
  54325. descriptors[ cacheKey ] = descriptorBase;
  54326. renderTargetData.width = renderTarget.width;
  54327. renderTargetData.height = renderTarget.height;
  54328. renderTargetData.samples = renderTarget.samples;
  54329. renderTargetData.activeMipmapLevel = renderContext.activeMipmapLevel;
  54330. renderTargetData.activeCubeFace = renderContext.activeCubeFace;
  54331. }
  54332. const descriptor = {
  54333. colorAttachments: []
  54334. };
  54335. // Apply dynamic properties to cached views
  54336. for ( let i = 0; i < descriptorBase.textureViews.length; i ++ ) {
  54337. const viewInfo = descriptorBase.textureViews[ i ];
  54338. let clearValue = { r: 0, g: 0, b: 0, a: 1 };
  54339. if ( i === 0 && colorAttachmentsConfig.clearValue ) {
  54340. clearValue = colorAttachmentsConfig.clearValue;
  54341. }
  54342. descriptor.colorAttachments.push( {
  54343. view: viewInfo.view,
  54344. depthSlice: viewInfo.depthSlice,
  54345. resolveTarget: viewInfo.resolveTarget,
  54346. loadOp: colorAttachmentsConfig.loadOp || GPULoadOp.Load,
  54347. storeOp: colorAttachmentsConfig.storeOp || GPUStoreOp.Store,
  54348. clearValue: clearValue
  54349. } );
  54350. }
  54351. if ( descriptorBase.depthStencilView ) {
  54352. descriptor.depthStencilAttachment = {
  54353. view: descriptorBase.depthStencilView
  54354. };
  54355. }
  54356. return descriptor;
  54357. }
  54358. /**
  54359. * This method is executed at the beginning of a render call and prepares
  54360. * the WebGPU state for upcoming render calls
  54361. *
  54362. * @param {RenderContext} renderContext - The render context.
  54363. */
  54364. beginRender( renderContext ) {
  54365. const renderContextData = this.get( renderContext );
  54366. //
  54367. const device = this.device;
  54368. const occlusionQueryCount = renderContext.occlusionQueryCount;
  54369. let occlusionQuerySet;
  54370. if ( occlusionQueryCount > 0 ) {
  54371. if ( renderContextData.currentOcclusionQuerySet ) renderContextData.currentOcclusionQuerySet.destroy();
  54372. if ( renderContextData.currentOcclusionQueryBuffer ) renderContextData.currentOcclusionQueryBuffer.destroy();
  54373. // Get a reference to the array of objects with queries. The renderContextData property
  54374. // can be changed by another render pass before the buffer.mapAsyc() completes.
  54375. renderContextData.currentOcclusionQuerySet = renderContextData.occlusionQuerySet;
  54376. renderContextData.currentOcclusionQueryBuffer = renderContextData.occlusionQueryBuffer;
  54377. renderContextData.currentOcclusionQueryObjects = renderContextData.occlusionQueryObjects;
  54378. //
  54379. occlusionQuerySet = device.createQuerySet( { type: 'occlusion', count: occlusionQueryCount, label: `occlusionQuerySet_${ renderContext.id }` } );
  54380. renderContextData.occlusionQuerySet = occlusionQuerySet;
  54381. renderContextData.occlusionQueryIndex = 0;
  54382. renderContextData.occlusionQueryObjects = new Array( occlusionQueryCount );
  54383. renderContextData.lastOcclusionObject = null;
  54384. }
  54385. let descriptor;
  54386. if ( renderContext.textures === null ) {
  54387. descriptor = this._getDefaultRenderPassDescriptor();
  54388. } else {
  54389. descriptor = this._getRenderPassDescriptor( renderContext, { loadOp: GPULoadOp.Load } );
  54390. }
  54391. this.initTimestampQuery( TimestampQuery.RENDER, this.getTimestampUID( renderContext ), descriptor );
  54392. descriptor.occlusionQuerySet = occlusionQuerySet;
  54393. const depthStencilAttachment = descriptor.depthStencilAttachment;
  54394. if ( renderContext.textures !== null ) {
  54395. const colorAttachments = descriptor.colorAttachments;
  54396. for ( let i = 0; i < colorAttachments.length; i ++ ) {
  54397. const colorAttachment = colorAttachments[ i ];
  54398. if ( renderContext.clearColor ) {
  54399. colorAttachment.clearValue = i === 0 ? renderContext.clearColorValue : { r: 0, g: 0, b: 0, a: 1 };
  54400. colorAttachment.loadOp = GPULoadOp.Clear;
  54401. } else {
  54402. colorAttachment.loadOp = GPULoadOp.Load;
  54403. }
  54404. colorAttachment.storeOp = GPUStoreOp.Store;
  54405. }
  54406. } else {
  54407. const colorAttachment = descriptor.colorAttachments[ 0 ];
  54408. if ( renderContext.clearColor ) {
  54409. colorAttachment.clearValue = renderContext.clearColorValue;
  54410. colorAttachment.loadOp = GPULoadOp.Clear;
  54411. } else {
  54412. colorAttachment.loadOp = GPULoadOp.Load;
  54413. }
  54414. colorAttachment.storeOp = GPUStoreOp.Store;
  54415. }
  54416. //
  54417. if ( renderContext.depth ) {
  54418. if ( renderContext.clearDepth ) {
  54419. depthStencilAttachment.depthClearValue = renderContext.clearDepthValue;
  54420. depthStencilAttachment.depthLoadOp = GPULoadOp.Clear;
  54421. } else {
  54422. depthStencilAttachment.depthLoadOp = GPULoadOp.Load;
  54423. }
  54424. depthStencilAttachment.depthStoreOp = GPUStoreOp.Store;
  54425. }
  54426. if ( renderContext.stencil ) {
  54427. if ( renderContext.clearStencil ) {
  54428. depthStencilAttachment.stencilClearValue = renderContext.clearStencilValue;
  54429. depthStencilAttachment.stencilLoadOp = GPULoadOp.Clear;
  54430. } else {
  54431. depthStencilAttachment.stencilLoadOp = GPULoadOp.Load;
  54432. }
  54433. depthStencilAttachment.stencilStoreOp = GPUStoreOp.Store;
  54434. }
  54435. //
  54436. const encoder = device.createCommandEncoder( { label: 'renderContext_' + renderContext.id } );
  54437. // shadow arrays - prepare bundle encoders for each camera in an array camera
  54438. if ( this._isRenderCameraDepthArray( renderContext ) === true ) {
  54439. const cameras = renderContext.camera.cameras;
  54440. if ( ! renderContextData.layerDescriptors || renderContextData.layerDescriptors.length !== cameras.length ) {
  54441. this._createDepthLayerDescriptors( renderContext, renderContextData, descriptor, cameras );
  54442. } else {
  54443. this._updateDepthLayerDescriptors( renderContext, renderContextData, cameras );
  54444. }
  54445. // Create bundle encoders for each layer
  54446. renderContextData.bundleEncoders = [];
  54447. renderContextData.bundleSets = [];
  54448. // Create separate bundle encoders for each camera in the array
  54449. for ( let i = 0; i < cameras.length; i ++ ) {
  54450. const bundleEncoder = this.pipelineUtils.createBundleEncoder(
  54451. renderContext,
  54452. 'renderBundleArrayCamera_' + i
  54453. );
  54454. // Initialize state tracking for this bundle
  54455. const bundleSets = {
  54456. attributes: {},
  54457. bindingGroups: [],
  54458. pipeline: null,
  54459. index: null
  54460. };
  54461. renderContextData.bundleEncoders.push( bundleEncoder );
  54462. renderContextData.bundleSets.push( bundleSets );
  54463. }
  54464. // We'll complete the bundles in finishRender
  54465. renderContextData.currentPass = null;
  54466. } else {
  54467. const currentPass = encoder.beginRenderPass( descriptor );
  54468. renderContextData.currentPass = currentPass;
  54469. if ( renderContext.viewport ) {
  54470. this.updateViewport( renderContext );
  54471. }
  54472. if ( renderContext.scissor ) {
  54473. this.updateScissor( renderContext );
  54474. }
  54475. }
  54476. //
  54477. renderContextData.descriptor = descriptor;
  54478. renderContextData.encoder = encoder;
  54479. renderContextData.currentSets = { attributes: {}, bindingGroups: [], pipeline: null, index: null };
  54480. renderContextData.renderBundles = [];
  54481. }
  54482. /**
  54483. * This method creates layer descriptors for each camera in an array camera
  54484. * to prepare for rendering to a depth array texture.
  54485. *
  54486. * @param {RenderContext} renderContext - The render context.
  54487. * @param {Object} renderContextData - The render context data.
  54488. * @param {Object} descriptor - The render pass descriptor.
  54489. * @param {ArrayCamera} cameras - The array camera.
  54490. *
  54491. * @private
  54492. */
  54493. _createDepthLayerDescriptors( renderContext, renderContextData, descriptor, cameras ) {
  54494. const depthStencilAttachment = descriptor.depthStencilAttachment;
  54495. renderContextData.layerDescriptors = [];
  54496. const depthTextureData = this.get( renderContext.depthTexture );
  54497. if ( ! depthTextureData.viewCache ) {
  54498. depthTextureData.viewCache = [];
  54499. }
  54500. for ( let i = 0; i < cameras.length; i ++ ) {
  54501. const layerDescriptor = {
  54502. ...descriptor,
  54503. colorAttachments: [ {
  54504. ...descriptor.colorAttachments[ 0 ],
  54505. view: descriptor.colorAttachments[ i ].view
  54506. } ]
  54507. };
  54508. if ( descriptor.depthStencilAttachment ) {
  54509. const layerIndex = i;
  54510. if ( ! depthTextureData.viewCache[ layerIndex ] ) {
  54511. depthTextureData.viewCache[ layerIndex ] = depthTextureData.texture.createView( {
  54512. dimension: GPUTextureViewDimension.TwoD,
  54513. baseArrayLayer: i,
  54514. arrayLayerCount: 1
  54515. } );
  54516. }
  54517. layerDescriptor.depthStencilAttachment = {
  54518. view: depthTextureData.viewCache[ layerIndex ],
  54519. depthLoadOp: depthStencilAttachment.depthLoadOp || GPULoadOp.Clear,
  54520. depthStoreOp: depthStencilAttachment.depthStoreOp || GPUStoreOp.Store,
  54521. depthClearValue: depthStencilAttachment.depthClearValue || 1.0
  54522. };
  54523. if ( renderContext.stencil ) {
  54524. layerDescriptor.depthStencilAttachment.stencilLoadOp = depthStencilAttachment.stencilLoadOp;
  54525. layerDescriptor.depthStencilAttachment.stencilStoreOp = depthStencilAttachment.stencilStoreOp;
  54526. layerDescriptor.depthStencilAttachment.stencilClearValue = depthStencilAttachment.stencilClearValue;
  54527. }
  54528. } else {
  54529. layerDescriptor.depthStencilAttachment = { ...depthStencilAttachment };
  54530. }
  54531. renderContextData.layerDescriptors.push( layerDescriptor );
  54532. }
  54533. }
  54534. /**
  54535. * This method updates the layer descriptors for each camera in an array camera
  54536. * to prepare for rendering to a depth array texture.
  54537. *
  54538. * @param {RenderContext} renderContext - The render context.
  54539. * @param {Object} renderContextData - The render context data.
  54540. * @param {ArrayCamera} cameras - The array camera.
  54541. *
  54542. */
  54543. _updateDepthLayerDescriptors( renderContext, renderContextData, cameras ) {
  54544. for ( let i = 0; i < cameras.length; i ++ ) {
  54545. const layerDescriptor = renderContextData.layerDescriptors[ i ];
  54546. if ( layerDescriptor.depthStencilAttachment ) {
  54547. const depthAttachment = layerDescriptor.depthStencilAttachment;
  54548. if ( renderContext.depth ) {
  54549. if ( renderContext.clearDepth ) {
  54550. depthAttachment.depthClearValue = renderContext.clearDepthValue;
  54551. depthAttachment.depthLoadOp = GPULoadOp.Clear;
  54552. } else {
  54553. depthAttachment.depthLoadOp = GPULoadOp.Load;
  54554. }
  54555. }
  54556. if ( renderContext.stencil ) {
  54557. if ( renderContext.clearStencil ) {
  54558. depthAttachment.stencilClearValue = renderContext.clearStencilValue;
  54559. depthAttachment.stencilLoadOp = GPULoadOp.Clear;
  54560. } else {
  54561. depthAttachment.stencilLoadOp = GPULoadOp.Load;
  54562. }
  54563. }
  54564. }
  54565. }
  54566. }
  54567. /**
  54568. * This method is executed at the end of a render call and finalizes work
  54569. * after draw calls.
  54570. *
  54571. * @param {RenderContext} renderContext - The render context.
  54572. */
  54573. finishRender( renderContext ) {
  54574. const renderContextData = this.get( renderContext );
  54575. const occlusionQueryCount = renderContext.occlusionQueryCount;
  54576. if ( renderContextData.renderBundles.length > 0 ) {
  54577. renderContextData.currentPass.executeBundles( renderContextData.renderBundles );
  54578. }
  54579. if ( occlusionQueryCount > renderContextData.occlusionQueryIndex ) {
  54580. renderContextData.currentPass.endOcclusionQuery();
  54581. }
  54582. // shadow arrays - Execute bundles for each layer
  54583. const encoder = renderContextData.encoder;
  54584. if ( this._isRenderCameraDepthArray( renderContext ) === true ) {
  54585. const bundles = [];
  54586. for ( let i = 0; i < renderContextData.bundleEncoders.length; i ++ ) {
  54587. const bundleEncoder = renderContextData.bundleEncoders[ i ];
  54588. bundles.push( bundleEncoder.finish() );
  54589. }
  54590. for ( let i = 0; i < renderContextData.layerDescriptors.length; i ++ ) {
  54591. if ( i < bundles.length ) {
  54592. const layerDescriptor = renderContextData.layerDescriptors[ i ];
  54593. const renderPass = encoder.beginRenderPass( layerDescriptor );
  54594. if ( renderContext.viewport ) {
  54595. const { x, y, width, height, minDepth, maxDepth } = renderContext.viewportValue;
  54596. renderPass.setViewport( x, y, width, height, minDepth, maxDepth );
  54597. }
  54598. if ( renderContext.scissor ) {
  54599. const { x, y, width, height } = renderContext.scissorValue;
  54600. renderPass.setScissorRect( x, y, width, height );
  54601. }
  54602. renderPass.executeBundles( [ bundles[ i ] ] );
  54603. renderPass.end();
  54604. }
  54605. }
  54606. } else if ( renderContextData.currentPass ) {
  54607. renderContextData.currentPass.end();
  54608. }
  54609. if ( occlusionQueryCount > 0 ) {
  54610. const bufferSize = occlusionQueryCount * 8; // 8 byte entries for query results
  54611. //
  54612. let queryResolveBuffer = this.occludedResolveCache.get( bufferSize );
  54613. if ( queryResolveBuffer === undefined ) {
  54614. queryResolveBuffer = this.device.createBuffer(
  54615. {
  54616. size: bufferSize,
  54617. usage: GPUBufferUsage.QUERY_RESOLVE | GPUBufferUsage.COPY_SRC
  54618. }
  54619. );
  54620. this.occludedResolveCache.set( bufferSize, queryResolveBuffer );
  54621. }
  54622. //
  54623. const readBuffer = this.device.createBuffer(
  54624. {
  54625. size: bufferSize,
  54626. usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ
  54627. }
  54628. );
  54629. // two buffers required here - WebGPU doesn't allow usage of QUERY_RESOLVE & MAP_READ to be combined
  54630. renderContextData.encoder.resolveQuerySet( renderContextData.occlusionQuerySet, 0, occlusionQueryCount, queryResolveBuffer, 0 );
  54631. renderContextData.encoder.copyBufferToBuffer( queryResolveBuffer, 0, readBuffer, 0, bufferSize );
  54632. renderContextData.occlusionQueryBuffer = readBuffer;
  54633. //
  54634. this.resolveOccludedAsync( renderContext );
  54635. }
  54636. this.device.queue.submit( [ renderContextData.encoder.finish() ] );
  54637. //
  54638. if ( renderContext.textures !== null ) {
  54639. const textures = renderContext.textures;
  54640. for ( let i = 0; i < textures.length; i ++ ) {
  54641. const texture = textures[ i ];
  54642. if ( texture.generateMipmaps === true ) {
  54643. this.textureUtils.generateMipmaps( texture );
  54644. }
  54645. }
  54646. }
  54647. }
  54648. /**
  54649. * Returns `true` if the given 3D object is fully occluded by other
  54650. * 3D objects in the scene.
  54651. *
  54652. * @param {RenderContext} renderContext - The render context.
  54653. * @param {Object3D} object - The 3D object to test.
  54654. * @return {boolean} Whether the 3D object is fully occluded or not.
  54655. */
  54656. isOccluded( renderContext, object ) {
  54657. const renderContextData = this.get( renderContext );
  54658. return renderContextData.occluded && renderContextData.occluded.has( object );
  54659. }
  54660. /**
  54661. * This method processes the result of occlusion queries and writes it
  54662. * into render context data.
  54663. *
  54664. * @async
  54665. * @param {RenderContext} renderContext - The render context.
  54666. * @return {Promise} A Promise that resolves when the occlusion query results have been processed.
  54667. */
  54668. async resolveOccludedAsync( renderContext ) {
  54669. const renderContextData = this.get( renderContext );
  54670. // handle occlusion query results
  54671. const { currentOcclusionQueryBuffer, currentOcclusionQueryObjects } = renderContextData;
  54672. if ( currentOcclusionQueryBuffer && currentOcclusionQueryObjects ) {
  54673. const occluded = new WeakSet();
  54674. renderContextData.currentOcclusionQueryObjects = null;
  54675. renderContextData.currentOcclusionQueryBuffer = null;
  54676. await currentOcclusionQueryBuffer.mapAsync( GPUMapMode.READ );
  54677. const buffer = currentOcclusionQueryBuffer.getMappedRange();
  54678. const results = new BigUint64Array( buffer );
  54679. for ( let i = 0; i < currentOcclusionQueryObjects.length; i ++ ) {
  54680. if ( results[ i ] === BigInt( 0 ) ) {
  54681. occluded.add( currentOcclusionQueryObjects[ i ] );
  54682. }
  54683. }
  54684. currentOcclusionQueryBuffer.destroy();
  54685. renderContextData.occluded = occluded;
  54686. }
  54687. }
  54688. /**
  54689. * Updates the viewport with the values from the given render context.
  54690. *
  54691. * @param {RenderContext} renderContext - The render context.
  54692. */
  54693. updateViewport( renderContext ) {
  54694. const { currentPass } = this.get( renderContext );
  54695. const { x, y, width, height, minDepth, maxDepth } = renderContext.viewportValue;
  54696. currentPass.setViewport( x, y, width, height, minDepth, maxDepth );
  54697. }
  54698. /**
  54699. * Updates the scissor with the values from the given render context.
  54700. *
  54701. * @param {RenderContext} renderContext - The render context.
  54702. */
  54703. updateScissor( renderContext ) {
  54704. const { currentPass } = this.get( renderContext );
  54705. const { x, y, width, height } = renderContext.scissorValue;
  54706. currentPass.setScissorRect( x, y, width, height );
  54707. }
  54708. /**
  54709. * Returns the clear color and alpha into a single
  54710. * color object.
  54711. *
  54712. * @return {Color4} The clear color.
  54713. */
  54714. getClearColor() {
  54715. const clearColor = super.getClearColor();
  54716. // only premultiply alpha when alphaMode is "premultiplied"
  54717. if ( this.renderer.alpha === true ) {
  54718. clearColor.r *= clearColor.a;
  54719. clearColor.g *= clearColor.a;
  54720. clearColor.b *= clearColor.a;
  54721. }
  54722. return clearColor;
  54723. }
  54724. /**
  54725. * Performs a clear operation.
  54726. *
  54727. * @param {boolean} color - Whether the color buffer should be cleared or not.
  54728. * @param {boolean} depth - Whether the depth buffer should be cleared or not.
  54729. * @param {boolean} stencil - Whether the stencil buffer should be cleared or not.
  54730. * @param {?RenderContext} [renderTargetContext=null] - The render context of the current set render target.
  54731. */
  54732. clear( color, depth, stencil, renderTargetContext = null ) {
  54733. const device = this.device;
  54734. const renderer = this.renderer;
  54735. let colorAttachments = [];
  54736. let depthStencilAttachment;
  54737. let clearValue;
  54738. let supportsDepth;
  54739. let supportsStencil;
  54740. if ( color ) {
  54741. const clearColor = this.getClearColor();
  54742. clearValue = { r: clearColor.r, g: clearColor.g, b: clearColor.b, a: clearColor.a };
  54743. }
  54744. if ( renderTargetContext === null ) {
  54745. supportsDepth = renderer.depth;
  54746. supportsStencil = renderer.stencil;
  54747. const descriptor = this._getDefaultRenderPassDescriptor();
  54748. if ( color ) {
  54749. colorAttachments = descriptor.colorAttachments;
  54750. const colorAttachment = colorAttachments[ 0 ];
  54751. colorAttachment.clearValue = clearValue;
  54752. colorAttachment.loadOp = GPULoadOp.Clear;
  54753. colorAttachment.storeOp = GPUStoreOp.Store;
  54754. }
  54755. if ( supportsDepth || supportsStencil ) {
  54756. depthStencilAttachment = descriptor.depthStencilAttachment;
  54757. }
  54758. } else {
  54759. supportsDepth = renderTargetContext.depth;
  54760. supportsStencil = renderTargetContext.stencil;
  54761. const clearConfig = {
  54762. loadOp: color ? GPULoadOp.Clear : GPULoadOp.Load,
  54763. clearValue: color ? clearValue : undefined
  54764. };
  54765. if ( supportsDepth ) {
  54766. clearConfig.depthLoadOp = depth ? GPULoadOp.Clear : GPULoadOp.Load;
  54767. clearConfig.depthClearValue = depth ? renderer.getClearDepth() : undefined;
  54768. clearConfig.depthStoreOp = GPUStoreOp.Store;
  54769. }
  54770. if ( supportsStencil ) {
  54771. clearConfig.stencilLoadOp = stencil ? GPULoadOp.Clear : GPULoadOp.Load;
  54772. clearConfig.stencilClearValue = stencil ? renderer.getClearStencil() : undefined;
  54773. clearConfig.stencilStoreOp = GPUStoreOp.Store;
  54774. }
  54775. const descriptor = this._getRenderPassDescriptor( renderTargetContext, clearConfig );
  54776. colorAttachments = descriptor.colorAttachments;
  54777. depthStencilAttachment = descriptor.depthStencilAttachment;
  54778. }
  54779. if ( supportsDepth && depthStencilAttachment ) {
  54780. if ( depth ) {
  54781. depthStencilAttachment.depthLoadOp = GPULoadOp.Clear;
  54782. depthStencilAttachment.depthClearValue = renderer.getClearDepth();
  54783. depthStencilAttachment.depthStoreOp = GPUStoreOp.Store;
  54784. } else {
  54785. depthStencilAttachment.depthLoadOp = GPULoadOp.Load;
  54786. depthStencilAttachment.depthStoreOp = GPUStoreOp.Store;
  54787. }
  54788. }
  54789. //
  54790. if ( supportsStencil && depthStencilAttachment ) {
  54791. if ( stencil ) {
  54792. depthStencilAttachment.stencilLoadOp = GPULoadOp.Clear;
  54793. depthStencilAttachment.stencilClearValue = renderer.getClearStencil();
  54794. depthStencilAttachment.stencilStoreOp = GPUStoreOp.Store;
  54795. } else {
  54796. depthStencilAttachment.stencilLoadOp = GPULoadOp.Load;
  54797. depthStencilAttachment.stencilStoreOp = GPUStoreOp.Store;
  54798. }
  54799. }
  54800. //
  54801. const encoder = device.createCommandEncoder( { label: 'clear' } );
  54802. const currentPass = encoder.beginRenderPass( {
  54803. colorAttachments,
  54804. depthStencilAttachment
  54805. } );
  54806. currentPass.end();
  54807. device.queue.submit( [ encoder.finish() ] );
  54808. }
  54809. // compute
  54810. /**
  54811. * This method is executed at the beginning of a compute call and
  54812. * prepares the state for upcoming compute tasks.
  54813. *
  54814. * @param {Node|Array<Node>} computeGroup - The compute node(s).
  54815. */
  54816. beginCompute( computeGroup ) {
  54817. const groupGPU = this.get( computeGroup );
  54818. //
  54819. const descriptor = {
  54820. label: 'computeGroup_' + computeGroup.id
  54821. };
  54822. this.initTimestampQuery( TimestampQuery.COMPUTE, this.getTimestampUID( computeGroup ), descriptor );
  54823. groupGPU.cmdEncoderGPU = this.device.createCommandEncoder( { label: 'computeGroup_' + computeGroup.id } );
  54824. groupGPU.passEncoderGPU = groupGPU.cmdEncoderGPU.beginComputePass( descriptor );
  54825. }
  54826. /**
  54827. * Executes a compute command for the given compute node.
  54828. *
  54829. * @param {Node|Array<Node>} computeGroup - The group of compute nodes of a compute call. Can be a single compute node.
  54830. * @param {Node} computeNode - The compute node.
  54831. * @param {Array<BindGroup>} bindings - The bindings.
  54832. * @param {ComputePipeline} pipeline - The compute pipeline.
  54833. * @param {number|Array<number>|IndirectStorageBufferAttribute} [dispatchSize=null]
  54834. * - A single number representing count, or
  54835. * - An array [x, y, z] representing dispatch size, or
  54836. * - A IndirectStorageBufferAttribute for indirect dispatch size.
  54837. */
  54838. compute( computeGroup, computeNode, bindings, pipeline, dispatchSize = null ) {
  54839. const computeNodeData = this.get( computeNode );
  54840. const { passEncoderGPU } = this.get( computeGroup );
  54841. // pipeline
  54842. const pipelineGPU = this.get( pipeline ).pipeline;
  54843. this.pipelineUtils.setPipeline( passEncoderGPU, pipelineGPU );
  54844. // bind groups
  54845. for ( let i = 0, l = bindings.length; i < l; i ++ ) {
  54846. const bindGroup = bindings[ i ];
  54847. const bindingsData = this.get( bindGroup );
  54848. passEncoderGPU.setBindGroup( i, bindingsData.group );
  54849. }
  54850. if ( dispatchSize === null ) {
  54851. dispatchSize = computeNode.count;
  54852. }
  54853. // When the dispatchSize is set with a StorageBuffer from the GPU.
  54854. if ( dispatchSize && typeof dispatchSize === 'object' && dispatchSize.isIndirectStorageBufferAttribute ) {
  54855. const dispatchBuffer = this.get( dispatchSize ).buffer;
  54856. passEncoderGPU.dispatchWorkgroupsIndirect( dispatchBuffer, 0 );
  54857. return;
  54858. }
  54859. if ( typeof dispatchSize === 'number' ) {
  54860. // If a single number is given, we calculate the dispatch size based on the workgroup size
  54861. const count = dispatchSize;
  54862. if ( computeNodeData.dispatchSize === undefined || computeNodeData.count !== count ) {
  54863. // cache dispatch size to avoid recalculating it every time
  54864. computeNodeData.dispatchSize = [ 0, 1, 1 ];
  54865. computeNodeData.count = count;
  54866. const workgroupSize = computeNode.workgroupSize;
  54867. let size = workgroupSize[ 0 ];
  54868. for ( let i = 1; i < workgroupSize.length; i ++ )
  54869. size *= workgroupSize[ i ];
  54870. const dispatchCount = Math.ceil( count / size );
  54871. //
  54872. const maxComputeWorkgroupsPerDimension = this.device.limits.maxComputeWorkgroupsPerDimension;
  54873. dispatchSize = [ dispatchCount, 1, 1 ];
  54874. if ( dispatchCount > maxComputeWorkgroupsPerDimension ) {
  54875. dispatchSize[ 0 ] = Math.min( dispatchCount, maxComputeWorkgroupsPerDimension );
  54876. dispatchSize[ 1 ] = Math.ceil( dispatchCount / maxComputeWorkgroupsPerDimension );
  54877. }
  54878. computeNodeData.dispatchSize = dispatchSize;
  54879. }
  54880. dispatchSize = computeNodeData.dispatchSize;
  54881. }
  54882. //
  54883. passEncoderGPU.dispatchWorkgroups(
  54884. dispatchSize[ 0 ],
  54885. dispatchSize[ 1 ] || 1,
  54886. dispatchSize[ 2 ] || 1
  54887. );
  54888. }
  54889. /**
  54890. * This method is executed at the end of a compute call and
  54891. * finalizes work after compute tasks.
  54892. *
  54893. * @param {Node|Array<Node>} computeGroup - The compute node(s).
  54894. */
  54895. finishCompute( computeGroup ) {
  54896. const groupData = this.get( computeGroup );
  54897. groupData.passEncoderGPU.end();
  54898. this.device.queue.submit( [ groupData.cmdEncoderGPU.finish() ] );
  54899. }
  54900. // render object
  54901. /**
  54902. * Executes a draw command for the given render object.
  54903. *
  54904. * @param {RenderObject} renderObject - The render object to draw.
  54905. * @param {Info} info - Holds a series of statistical information about the GPU memory and the rendering process.
  54906. */
  54907. draw( renderObject, info ) {
  54908. const { object, material, context, pipeline } = renderObject;
  54909. const bindings = renderObject.getBindings();
  54910. const renderContextData = this.get( context );
  54911. const pipelineData = this.get( pipeline );
  54912. const pipelineGPU = pipelineData.pipeline;
  54913. if ( pipelineData.error === true ) return;
  54914. const index = renderObject.getIndex();
  54915. const hasIndex = ( index !== null );
  54916. const drawParams = renderObject.getDrawParameters();
  54917. if ( drawParams === null ) return;
  54918. // pipeline
  54919. const setPipelineAndBindings = ( passEncoderGPU, currentSets ) => {
  54920. // pipeline
  54921. this.pipelineUtils.setPipeline( passEncoderGPU, pipelineGPU );
  54922. currentSets.pipeline = pipelineGPU;
  54923. // bind groups
  54924. const currentBindingGroups = currentSets.bindingGroups;
  54925. for ( let i = 0, l = bindings.length; i < l; i ++ ) {
  54926. const bindGroup = bindings[ i ];
  54927. const bindingsData = this.get( bindGroup );
  54928. if ( currentBindingGroups[ bindGroup.index ] !== bindGroup.id ) {
  54929. passEncoderGPU.setBindGroup( bindGroup.index, bindingsData.group );
  54930. currentBindingGroups[ bindGroup.index ] = bindGroup.id;
  54931. }
  54932. }
  54933. // attributes
  54934. // index
  54935. if ( hasIndex === true ) {
  54936. if ( currentSets.index !== index ) {
  54937. const buffer = this.get( index ).buffer;
  54938. const indexFormat = ( index.array instanceof Uint16Array ) ? GPUIndexFormat.Uint16 : GPUIndexFormat.Uint32;
  54939. passEncoderGPU.setIndexBuffer( buffer, indexFormat );
  54940. currentSets.index = index;
  54941. }
  54942. }
  54943. // vertex buffers
  54944. const vertexBuffers = renderObject.getVertexBuffers();
  54945. for ( let i = 0, l = vertexBuffers.length; i < l; i ++ ) {
  54946. const vertexBuffer = vertexBuffers[ i ];
  54947. if ( currentSets.attributes[ i ] !== vertexBuffer ) {
  54948. const buffer = this.get( vertexBuffer ).buffer;
  54949. passEncoderGPU.setVertexBuffer( i, buffer );
  54950. currentSets.attributes[ i ] = vertexBuffer;
  54951. }
  54952. }
  54953. // stencil
  54954. if ( context.stencil === true && material.stencilWrite === true && renderContextData.currentStencilRef !== material.stencilRef ) {
  54955. passEncoderGPU.setStencilReference( material.stencilRef );
  54956. renderContextData.currentStencilRef = material.stencilRef;
  54957. }
  54958. };
  54959. // Define draw function
  54960. const draw = ( passEncoderGPU, currentSets ) => {
  54961. setPipelineAndBindings( passEncoderGPU, currentSets );
  54962. if ( object.isBatchedMesh === true ) {
  54963. const starts = object._multiDrawStarts;
  54964. const counts = object._multiDrawCounts;
  54965. const drawCount = object._multiDrawCount;
  54966. const drawInstances = object._multiDrawInstances;
  54967. if ( drawInstances !== null ) {
  54968. // @deprecated, r174
  54969. warnOnce( 'WebGPUBackend: renderMultiDrawInstances has been deprecated and will be removed in r184. Append to renderMultiDraw arguments and use indirection.' );
  54970. }
  54971. for ( let i = 0; i < drawCount; i ++ ) {
  54972. const count = drawInstances ? drawInstances[ i ] : 1;
  54973. const firstInstance = count > 1 ? 0 : i;
  54974. if ( hasIndex === true ) {
  54975. passEncoderGPU.drawIndexed( counts[ i ], count, starts[ i ] / index.array.BYTES_PER_ELEMENT, 0, firstInstance );
  54976. } else {
  54977. passEncoderGPU.draw( counts[ i ], count, starts[ i ], firstInstance );
  54978. }
  54979. info.update( object, counts[ i ], count );
  54980. }
  54981. } else if ( hasIndex === true ) {
  54982. const { vertexCount: indexCount, instanceCount, firstVertex: firstIndex } = drawParams;
  54983. const indirect = renderObject.getIndirect();
  54984. if ( indirect !== null ) {
  54985. const buffer = this.get( indirect ).buffer;
  54986. passEncoderGPU.drawIndexedIndirect( buffer, 0 );
  54987. } else {
  54988. passEncoderGPU.drawIndexed( indexCount, instanceCount, firstIndex, 0, 0 );
  54989. }
  54990. info.update( object, indexCount, instanceCount );
  54991. } else {
  54992. const { vertexCount, instanceCount, firstVertex } = drawParams;
  54993. const indirect = renderObject.getIndirect();
  54994. if ( indirect !== null ) {
  54995. const buffer = this.get( indirect ).buffer;
  54996. passEncoderGPU.drawIndirect( buffer, 0 );
  54997. } else {
  54998. passEncoderGPU.draw( vertexCount, instanceCount, firstVertex, 0 );
  54999. }
  55000. info.update( object, vertexCount, instanceCount );
  55001. }
  55002. };
  55003. if ( renderObject.camera.isArrayCamera && renderObject.camera.cameras.length > 0 ) {
  55004. const cameraData = this.get( renderObject.camera );
  55005. const cameras = renderObject.camera.cameras;
  55006. const cameraIndex = renderObject.getBindingGroup( 'cameraIndex' );
  55007. if ( cameraData.indexesGPU === undefined || cameraData.indexesGPU.length !== cameras.length ) {
  55008. const bindingsData = this.get( cameraIndex );
  55009. const indexesGPU = [];
  55010. const data = new Uint32Array( [ 0, 0, 0, 0 ] );
  55011. for ( let i = 0, len = cameras.length; i < len; i ++ ) {
  55012. data[ 0 ] = i;
  55013. const bindGroupIndex = this.bindingUtils.createBindGroupIndex( data, bindingsData.layout );
  55014. indexesGPU.push( bindGroupIndex );
  55015. }
  55016. cameraData.indexesGPU = indexesGPU; // TODO: Create a global library for this
  55017. }
  55018. const pixelRatio = this.renderer.getPixelRatio();
  55019. for ( let i = 0, len = cameras.length; i < len; i ++ ) {
  55020. const subCamera = cameras[ i ];
  55021. if ( object.layers.test( subCamera.layers ) ) {
  55022. const vp = subCamera.viewport;
  55023. let pass = renderContextData.currentPass;
  55024. let sets = renderContextData.currentSets;
  55025. if ( renderContextData.bundleEncoders ) {
  55026. const bundleEncoder = renderContextData.bundleEncoders[ i ];
  55027. const bundleSets = renderContextData.bundleSets[ i ];
  55028. pass = bundleEncoder;
  55029. sets = bundleSets;
  55030. }
  55031. if ( vp ) {
  55032. pass.setViewport(
  55033. Math.floor( vp.x * pixelRatio ),
  55034. Math.floor( vp.y * pixelRatio ),
  55035. Math.floor( vp.width * pixelRatio ),
  55036. Math.floor( vp.height * pixelRatio ),
  55037. context.viewportValue.minDepth,
  55038. context.viewportValue.maxDepth
  55039. );
  55040. }
  55041. // Set camera index binding for this layer
  55042. if ( cameraIndex && cameraData.indexesGPU ) {
  55043. pass.setBindGroup( cameraIndex.index, cameraData.indexesGPU[ i ] );
  55044. sets.bindingGroups[ cameraIndex.index ] = cameraIndex.id;
  55045. }
  55046. draw( pass, sets );
  55047. }
  55048. }
  55049. } else {
  55050. // Regular single camera rendering
  55051. if ( renderContextData.currentPass ) {
  55052. // Handle occlusion queries
  55053. if ( renderContextData.occlusionQuerySet !== undefined ) {
  55054. const lastObject = renderContextData.lastOcclusionObject;
  55055. if ( lastObject !== object ) {
  55056. if ( lastObject !== null && lastObject.occlusionTest === true ) {
  55057. renderContextData.currentPass.endOcclusionQuery();
  55058. renderContextData.occlusionQueryIndex ++;
  55059. }
  55060. if ( object.occlusionTest === true ) {
  55061. renderContextData.currentPass.beginOcclusionQuery( renderContextData.occlusionQueryIndex );
  55062. renderContextData.occlusionQueryObjects[ renderContextData.occlusionQueryIndex ] = object;
  55063. }
  55064. renderContextData.lastOcclusionObject = object;
  55065. }
  55066. }
  55067. draw( renderContextData.currentPass, renderContextData.currentSets );
  55068. }
  55069. }
  55070. }
  55071. // cache key
  55072. /**
  55073. * Returns `true` if the render pipeline requires an update.
  55074. *
  55075. * @param {RenderObject} renderObject - The render object.
  55076. * @return {boolean} Whether the render pipeline requires an update or not.
  55077. */
  55078. needsRenderUpdate( renderObject ) {
  55079. const data = this.get( renderObject );
  55080. const { object, material } = renderObject;
  55081. const utils = this.utils;
  55082. const sampleCount = utils.getSampleCountRenderContext( renderObject.context );
  55083. const colorSpace = utils.getCurrentColorSpace( renderObject.context );
  55084. const colorFormat = utils.getCurrentColorFormat( renderObject.context );
  55085. const depthStencilFormat = utils.getCurrentDepthStencilFormat( renderObject.context );
  55086. const primitiveTopology = utils.getPrimitiveTopology( object, material );
  55087. let needsUpdate = false;
  55088. if ( data.material !== material || data.materialVersion !== material.version ||
  55089. data.transparent !== material.transparent || data.blending !== material.blending || data.premultipliedAlpha !== material.premultipliedAlpha ||
  55090. data.blendSrc !== material.blendSrc || data.blendDst !== material.blendDst || data.blendEquation !== material.blendEquation ||
  55091. data.blendSrcAlpha !== material.blendSrcAlpha || data.blendDstAlpha !== material.blendDstAlpha || data.blendEquationAlpha !== material.blendEquationAlpha ||
  55092. data.colorWrite !== material.colorWrite || data.depthWrite !== material.depthWrite || data.depthTest !== material.depthTest || data.depthFunc !== material.depthFunc ||
  55093. data.stencilWrite !== material.stencilWrite || data.stencilFunc !== material.stencilFunc ||
  55094. data.stencilFail !== material.stencilFail || data.stencilZFail !== material.stencilZFail || data.stencilZPass !== material.stencilZPass ||
  55095. data.stencilFuncMask !== material.stencilFuncMask || data.stencilWriteMask !== material.stencilWriteMask ||
  55096. data.side !== material.side || data.alphaToCoverage !== material.alphaToCoverage ||
  55097. data.sampleCount !== sampleCount || data.colorSpace !== colorSpace ||
  55098. data.colorFormat !== colorFormat || data.depthStencilFormat !== depthStencilFormat ||
  55099. data.primitiveTopology !== primitiveTopology ||
  55100. data.clippingContextCacheKey !== renderObject.clippingContextCacheKey
  55101. ) {
  55102. data.material = material; data.materialVersion = material.version;
  55103. data.transparent = material.transparent; data.blending = material.blending; data.premultipliedAlpha = material.premultipliedAlpha;
  55104. data.blendSrc = material.blendSrc; data.blendDst = material.blendDst; data.blendEquation = material.blendEquation;
  55105. data.blendSrcAlpha = material.blendSrcAlpha; data.blendDstAlpha = material.blendDstAlpha; data.blendEquationAlpha = material.blendEquationAlpha;
  55106. data.colorWrite = material.colorWrite;
  55107. data.depthWrite = material.depthWrite; data.depthTest = material.depthTest; data.depthFunc = material.depthFunc;
  55108. data.stencilWrite = material.stencilWrite; data.stencilFunc = material.stencilFunc;
  55109. data.stencilFail = material.stencilFail; data.stencilZFail = material.stencilZFail; data.stencilZPass = material.stencilZPass;
  55110. data.stencilFuncMask = material.stencilFuncMask; data.stencilWriteMask = material.stencilWriteMask;
  55111. data.side = material.side; data.alphaToCoverage = material.alphaToCoverage;
  55112. data.sampleCount = sampleCount;
  55113. data.colorSpace = colorSpace;
  55114. data.colorFormat = colorFormat;
  55115. data.depthStencilFormat = depthStencilFormat;
  55116. data.primitiveTopology = primitiveTopology;
  55117. data.clippingContextCacheKey = renderObject.clippingContextCacheKey;
  55118. needsUpdate = true;
  55119. }
  55120. return needsUpdate;
  55121. }
  55122. /**
  55123. * Returns a cache key that is used to identify render pipelines.
  55124. *
  55125. * @param {RenderObject} renderObject - The render object.
  55126. * @return {string} The cache key.
  55127. */
  55128. getRenderCacheKey( renderObject ) {
  55129. const { object, material } = renderObject;
  55130. const utils = this.utils;
  55131. const renderContext = renderObject.context;
  55132. // meshes with negative scale have a different frontFace render pipeline
  55133. // descriptor value so the following must be honored in the cache key
  55134. const frontFaceCW = ( object.isMesh && object.matrixWorld.determinant() < 0 );
  55135. return [
  55136. material.transparent, material.blending, material.premultipliedAlpha,
  55137. material.blendSrc, material.blendDst, material.blendEquation,
  55138. material.blendSrcAlpha, material.blendDstAlpha, material.blendEquationAlpha,
  55139. material.colorWrite,
  55140. material.depthWrite, material.depthTest, material.depthFunc,
  55141. material.stencilWrite, material.stencilFunc,
  55142. material.stencilFail, material.stencilZFail, material.stencilZPass,
  55143. material.stencilFuncMask, material.stencilWriteMask,
  55144. material.side,
  55145. frontFaceCW,
  55146. utils.getSampleCountRenderContext( renderContext ),
  55147. utils.getCurrentColorSpace( renderContext ), utils.getCurrentColorFormat( renderContext ), utils.getCurrentDepthStencilFormat( renderContext ),
  55148. utils.getPrimitiveTopology( object, material ),
  55149. renderObject.getGeometryCacheKey(),
  55150. renderObject.clippingContextCacheKey
  55151. ].join();
  55152. }
  55153. // textures
  55154. /**
  55155. * Updates a GPU sampler for the given texture.
  55156. *
  55157. * @param {Texture} texture - The texture to update the sampler for.
  55158. * @return {string} The current sampler key.
  55159. */
  55160. updateSampler( texture ) {
  55161. return this.textureUtils.updateSampler( texture );
  55162. }
  55163. /**
  55164. * Creates a default texture for the given texture that can be used
  55165. * as a placeholder until the actual texture is ready for usage.
  55166. *
  55167. * @param {Texture} texture - The texture to create a default texture for.
  55168. * @return {boolean} Whether the sampler has been updated or not.
  55169. */
  55170. createDefaultTexture( texture ) {
  55171. return this.textureUtils.createDefaultTexture( texture );
  55172. }
  55173. /**
  55174. * Defines a texture on the GPU for the given texture object.
  55175. *
  55176. * @param {Texture} texture - The texture.
  55177. * @param {Object} [options={}] - Optional configuration parameter.
  55178. */
  55179. createTexture( texture, options ) {
  55180. this.textureUtils.createTexture( texture, options );
  55181. }
  55182. /**
  55183. * Uploads the updated texture data to the GPU.
  55184. *
  55185. * @param {Texture} texture - The texture.
  55186. * @param {Object} [options={}] - Optional configuration parameter.
  55187. */
  55188. updateTexture( texture, options ) {
  55189. this.textureUtils.updateTexture( texture, options );
  55190. }
  55191. /**
  55192. * Generates mipmaps for the given texture.
  55193. *
  55194. * @param {Texture} texture - The texture.
  55195. */
  55196. generateMipmaps( texture ) {
  55197. this.textureUtils.generateMipmaps( texture );
  55198. }
  55199. /**
  55200. * Destroys the GPU data for the given texture object.
  55201. *
  55202. * @param {Texture} texture - The texture.
  55203. * @param {boolean} [isDefaultTexture=false] - Whether the texture uses a default GPU texture or not.
  55204. */
  55205. destroyTexture( texture, isDefaultTexture = false ) {
  55206. this.textureUtils.destroyTexture( texture, isDefaultTexture );
  55207. }
  55208. /**
  55209. * Returns texture data as a typed array.
  55210. *
  55211. * @async
  55212. * @param {Texture} texture - The texture to copy.
  55213. * @param {number} x - The x coordinate of the copy origin.
  55214. * @param {number} y - The y coordinate of the copy origin.
  55215. * @param {number} width - The width of the copy.
  55216. * @param {number} height - The height of the copy.
  55217. * @param {number} faceIndex - The face index.
  55218. * @return {Promise<TypedArray>} A Promise that resolves with a typed array when the copy operation has finished.
  55219. */
  55220. async copyTextureToBuffer( texture, x, y, width, height, faceIndex ) {
  55221. return this.textureUtils.copyTextureToBuffer( texture, x, y, width, height, faceIndex );
  55222. }
  55223. /**
  55224. * Inits a time stamp query for the given render context.
  55225. *
  55226. * @param {string} type - The type of the timestamp query (e.g. 'render', 'compute').
  55227. * @param {number} uid - Unique id for the context (e.g. render context id).
  55228. * @param {Object} descriptor - The query descriptor.
  55229. */
  55230. initTimestampQuery( type, uid, descriptor ) {
  55231. if ( ! this.trackTimestamp ) return;
  55232. if ( ! this.timestampQueryPool[ type ] ) {
  55233. // TODO: Variable maxQueries?
  55234. this.timestampQueryPool[ type ] = new WebGPUTimestampQueryPool( this.device, type, 2048 );
  55235. }
  55236. const timestampQueryPool = this.timestampQueryPool[ type ];
  55237. const baseOffset = timestampQueryPool.allocateQueriesForContext( uid );
  55238. descriptor.timestampWrites = {
  55239. querySet: timestampQueryPool.querySet,
  55240. beginningOfPassWriteIndex: baseOffset,
  55241. endOfPassWriteIndex: baseOffset + 1,
  55242. };
  55243. }
  55244. // node builder
  55245. /**
  55246. * Returns a node builder for the given render object.
  55247. *
  55248. * @param {RenderObject} object - The render object.
  55249. * @param {Renderer} renderer - The renderer.
  55250. * @return {WGSLNodeBuilder} The node builder.
  55251. */
  55252. createNodeBuilder( object, renderer ) {
  55253. return new WGSLNodeBuilder( object, renderer );
  55254. }
  55255. // program
  55256. /**
  55257. * Creates a shader program from the given programmable stage.
  55258. *
  55259. * @param {ProgrammableStage} program - The programmable stage.
  55260. */
  55261. createProgram( program ) {
  55262. const programGPU = this.get( program );
  55263. programGPU.module = {
  55264. module: this.device.createShaderModule( { code: program.code, label: program.stage + ( program.name !== '' ? `_${ program.name }` : '' ) } ),
  55265. entryPoint: 'main'
  55266. };
  55267. }
  55268. /**
  55269. * Destroys the shader program of the given programmable stage.
  55270. *
  55271. * @param {ProgrammableStage} program - The programmable stage.
  55272. */
  55273. destroyProgram( program ) {
  55274. this.delete( program );
  55275. }
  55276. // pipelines
  55277. /**
  55278. * Creates a render pipeline for the given render object.
  55279. *
  55280. * @param {RenderObject} renderObject - The render object.
  55281. * @param {Array<Promise>} promises - An array of compilation promises which are used in `compileAsync()`.
  55282. */
  55283. createRenderPipeline( renderObject, promises ) {
  55284. this.pipelineUtils.createRenderPipeline( renderObject, promises );
  55285. }
  55286. /**
  55287. * Creates a compute pipeline for the given compute node.
  55288. *
  55289. * @param {ComputePipeline} computePipeline - The compute pipeline.
  55290. * @param {Array<BindGroup>} bindings - The bindings.
  55291. */
  55292. createComputePipeline( computePipeline, bindings ) {
  55293. this.pipelineUtils.createComputePipeline( computePipeline, bindings );
  55294. }
  55295. /**
  55296. * Prepares the state for encoding render bundles.
  55297. *
  55298. * @param {RenderContext} renderContext - The render context.
  55299. */
  55300. beginBundle( renderContext ) {
  55301. const renderContextData = this.get( renderContext );
  55302. renderContextData._currentPass = renderContextData.currentPass;
  55303. renderContextData._currentSets = renderContextData.currentSets;
  55304. renderContextData.currentSets = { attributes: {}, bindingGroups: [], pipeline: null, index: null };
  55305. renderContextData.currentPass = this.pipelineUtils.createBundleEncoder( renderContext );
  55306. }
  55307. /**
  55308. * After processing render bundles this method finalizes related work.
  55309. *
  55310. * @param {RenderContext} renderContext - The render context.
  55311. * @param {RenderBundle} bundle - The render bundle.
  55312. */
  55313. finishBundle( renderContext, bundle ) {
  55314. const renderContextData = this.get( renderContext );
  55315. const bundleEncoder = renderContextData.currentPass;
  55316. const bundleGPU = bundleEncoder.finish();
  55317. this.get( bundle ).bundleGPU = bundleGPU;
  55318. // restore render pass state
  55319. renderContextData.currentSets = renderContextData._currentSets;
  55320. renderContextData.currentPass = renderContextData._currentPass;
  55321. }
  55322. /**
  55323. * Adds a render bundle to the render context data.
  55324. *
  55325. * @param {RenderContext} renderContext - The render context.
  55326. * @param {RenderBundle} bundle - The render bundle to add.
  55327. */
  55328. addBundle( renderContext, bundle ) {
  55329. const renderContextData = this.get( renderContext );
  55330. renderContextData.renderBundles.push( this.get( bundle ).bundleGPU );
  55331. }
  55332. // bindings
  55333. /**
  55334. * Creates bindings from the given bind group definition.
  55335. *
  55336. * @param {BindGroup} bindGroup - The bind group.
  55337. * @param {Array<BindGroup>} bindings - Array of bind groups.
  55338. * @param {number} cacheIndex - The cache index.
  55339. * @param {number} version - The version.
  55340. */
  55341. createBindings( bindGroup, bindings, cacheIndex, version ) {
  55342. this.bindingUtils.createBindings( bindGroup, bindings, cacheIndex, version );
  55343. }
  55344. /**
  55345. * Updates the given bind group definition.
  55346. *
  55347. * @param {BindGroup} bindGroup - The bind group.
  55348. * @param {Array<BindGroup>} bindings - Array of bind groups.
  55349. * @param {number} cacheIndex - The cache index.
  55350. * @param {number} version - The version.
  55351. */
  55352. updateBindings( bindGroup, bindings, cacheIndex, version ) {
  55353. this.bindingUtils.createBindings( bindGroup, bindings, cacheIndex, version );
  55354. }
  55355. /**
  55356. * Updates a buffer binding.
  55357. *
  55358. * @param {Buffer} binding - The buffer binding to update.
  55359. */
  55360. updateBinding( binding ) {
  55361. this.bindingUtils.updateBinding( binding );
  55362. }
  55363. // attributes
  55364. /**
  55365. * Creates the buffer of an indexed shader attribute.
  55366. *
  55367. * @param {BufferAttribute} attribute - The indexed buffer attribute.
  55368. */
  55369. createIndexAttribute( attribute ) {
  55370. let usage = GPUBufferUsage.INDEX | GPUBufferUsage.COPY_SRC | GPUBufferUsage.COPY_DST;
  55371. if ( attribute.isStorageBufferAttribute || attribute.isStorageInstancedBufferAttribute ) {
  55372. usage |= GPUBufferUsage.STORAGE;
  55373. }
  55374. this.attributeUtils.createAttribute( attribute, usage );
  55375. }
  55376. /**
  55377. * Creates the GPU buffer of a shader attribute.
  55378. *
  55379. * @param {BufferAttribute} attribute - The buffer attribute.
  55380. */
  55381. createAttribute( attribute ) {
  55382. this.attributeUtils.createAttribute( attribute, GPUBufferUsage.VERTEX | GPUBufferUsage.COPY_SRC | GPUBufferUsage.COPY_DST );
  55383. }
  55384. /**
  55385. * Creates the GPU buffer of a storage attribute.
  55386. *
  55387. * @param {BufferAttribute} attribute - The buffer attribute.
  55388. */
  55389. createStorageAttribute( attribute ) {
  55390. this.attributeUtils.createAttribute( attribute, GPUBufferUsage.STORAGE | GPUBufferUsage.VERTEX | GPUBufferUsage.COPY_SRC | GPUBufferUsage.COPY_DST );
  55391. }
  55392. /**
  55393. * Creates the GPU buffer of an indirect storage attribute.
  55394. *
  55395. * @param {BufferAttribute} attribute - The buffer attribute.
  55396. */
  55397. createIndirectStorageAttribute( attribute ) {
  55398. this.attributeUtils.createAttribute( attribute, GPUBufferUsage.STORAGE | GPUBufferUsage.INDIRECT | GPUBufferUsage.COPY_SRC | GPUBufferUsage.COPY_DST );
  55399. }
  55400. /**
  55401. * Updates the GPU buffer of a shader attribute.
  55402. *
  55403. * @param {BufferAttribute} attribute - The buffer attribute to update.
  55404. */
  55405. updateAttribute( attribute ) {
  55406. this.attributeUtils.updateAttribute( attribute );
  55407. }
  55408. /**
  55409. * Destroys the GPU buffer of a shader attribute.
  55410. *
  55411. * @param {BufferAttribute} attribute - The buffer attribute to destroy.
  55412. */
  55413. destroyAttribute( attribute ) {
  55414. this.attributeUtils.destroyAttribute( attribute );
  55415. }
  55416. // canvas
  55417. /**
  55418. * Triggers an update of the default render pass descriptor.
  55419. */
  55420. updateSize() {
  55421. this.delete( this.renderer.getCanvasTarget() );
  55422. }
  55423. // utils public
  55424. /**
  55425. * Returns the maximum anisotropy texture filtering value.
  55426. *
  55427. * @return {number} The maximum anisotropy texture filtering value.
  55428. */
  55429. getMaxAnisotropy() {
  55430. return 16;
  55431. }
  55432. /**
  55433. * Checks if the given feature is supported by the backend.
  55434. *
  55435. * @param {string} name - The feature's name.
  55436. * @return {boolean} Whether the feature is supported or not.
  55437. */
  55438. hasFeature( name ) {
  55439. if ( GPUFeatureMap[ name ] !== undefined ) name = GPUFeatureMap[ name ];
  55440. return this.device.features.has( name );
  55441. }
  55442. /**
  55443. * Copies data of the given source texture to the given destination texture.
  55444. *
  55445. * @param {Texture} srcTexture - The source texture.
  55446. * @param {Texture} dstTexture - The destination texture.
  55447. * @param {?(Box3|Box2)} [srcRegion=null] - The region of the source texture to copy.
  55448. * @param {?(Vector2|Vector3)} [dstPosition=null] - The destination position of the copy.
  55449. * @param {number} [srcLevel=0] - The mipmap level to copy.
  55450. * @param {number} [dstLevel=0] - The destination mip level to copy to.
  55451. */
  55452. copyTextureToTexture( srcTexture, dstTexture, srcRegion = null, dstPosition = null, srcLevel = 0, dstLevel = 0 ) {
  55453. let dstX = 0;
  55454. let dstY = 0;
  55455. let dstZ = 0;
  55456. let srcX = 0;
  55457. let srcY = 0;
  55458. let srcZ = 0;
  55459. let srcWidth = srcTexture.image.width;
  55460. let srcHeight = srcTexture.image.height;
  55461. let srcDepth = 1;
  55462. if ( srcRegion !== null ) {
  55463. if ( srcRegion.isBox3 === true ) {
  55464. srcX = srcRegion.min.x;
  55465. srcY = srcRegion.min.y;
  55466. srcZ = srcRegion.min.z;
  55467. srcWidth = srcRegion.max.x - srcRegion.min.x;
  55468. srcHeight = srcRegion.max.y - srcRegion.min.y;
  55469. srcDepth = srcRegion.max.z - srcRegion.min.z;
  55470. } else {
  55471. // Assume it's a Box2
  55472. srcX = srcRegion.min.x;
  55473. srcY = srcRegion.min.y;
  55474. srcWidth = srcRegion.max.x - srcRegion.min.x;
  55475. srcHeight = srcRegion.max.y - srcRegion.min.y;
  55476. srcDepth = 1;
  55477. }
  55478. }
  55479. if ( dstPosition !== null ) {
  55480. dstX = dstPosition.x;
  55481. dstY = dstPosition.y;
  55482. dstZ = dstPosition.z || 0;
  55483. }
  55484. const encoder = this.device.createCommandEncoder( { label: 'copyTextureToTexture_' + srcTexture.id + '_' + dstTexture.id } );
  55485. const sourceGPU = this.get( srcTexture ).texture;
  55486. const destinationGPU = this.get( dstTexture ).texture;
  55487. encoder.copyTextureToTexture(
  55488. {
  55489. texture: sourceGPU,
  55490. mipLevel: srcLevel,
  55491. origin: { x: srcX, y: srcY, z: srcZ }
  55492. },
  55493. {
  55494. texture: destinationGPU,
  55495. mipLevel: dstLevel,
  55496. origin: { x: dstX, y: dstY, z: dstZ }
  55497. },
  55498. [
  55499. srcWidth,
  55500. srcHeight,
  55501. srcDepth
  55502. ]
  55503. );
  55504. this.device.queue.submit( [ encoder.finish() ] );
  55505. if ( dstLevel === 0 && dstTexture.generateMipmaps ) {
  55506. this.textureUtils.generateMipmaps( dstTexture );
  55507. }
  55508. }
  55509. /**
  55510. * Copies the current bound framebuffer to the given texture.
  55511. *
  55512. * @param {Texture} texture - The destination texture.
  55513. * @param {RenderContext} renderContext - The render context.
  55514. * @param {Vector4} rectangle - A four dimensional vector defining the origin and dimension of the copy.
  55515. */
  55516. copyFramebufferToTexture( texture, renderContext, rectangle ) {
  55517. const renderContextData = this.get( renderContext );
  55518. let sourceGPU = null;
  55519. if ( renderContext.renderTarget ) {
  55520. if ( texture.isDepthTexture ) {
  55521. sourceGPU = this.get( renderContext.depthTexture ).texture;
  55522. } else {
  55523. sourceGPU = this.get( renderContext.textures[ 0 ] ).texture;
  55524. }
  55525. } else {
  55526. if ( texture.isDepthTexture ) {
  55527. sourceGPU = this.textureUtils.getDepthBuffer( renderContext.depth, renderContext.stencil );
  55528. } else {
  55529. sourceGPU = this.context.getCurrentTexture();
  55530. }
  55531. }
  55532. const destinationGPU = this.get( texture ).texture;
  55533. if ( sourceGPU.format !== destinationGPU.format ) {
  55534. error( 'WebGPUBackend: copyFramebufferToTexture: Source and destination formats do not match.', sourceGPU.format, destinationGPU.format );
  55535. return;
  55536. }
  55537. let encoder;
  55538. if ( renderContextData.currentPass ) {
  55539. renderContextData.currentPass.end();
  55540. encoder = renderContextData.encoder;
  55541. } else {
  55542. encoder = this.device.createCommandEncoder( { label: 'copyFramebufferToTexture_' + texture.id } );
  55543. }
  55544. encoder.copyTextureToTexture(
  55545. {
  55546. texture: sourceGPU,
  55547. origin: [ rectangle.x, rectangle.y, 0 ],
  55548. },
  55549. {
  55550. texture: destinationGPU
  55551. },
  55552. [
  55553. rectangle.z,
  55554. rectangle.w
  55555. ]
  55556. );
  55557. // mipmaps must be genereated with the same encoder otherwise the copied texture data
  55558. // might be out-of-sync, see #31768
  55559. if ( texture.generateMipmaps ) {
  55560. this.textureUtils.generateMipmaps( texture, encoder );
  55561. }
  55562. if ( renderContextData.currentPass ) {
  55563. const { descriptor } = renderContextData;
  55564. for ( let i = 0; i < descriptor.colorAttachments.length; i ++ ) {
  55565. descriptor.colorAttachments[ i ].loadOp = GPULoadOp.Load;
  55566. }
  55567. if ( renderContext.depth ) descriptor.depthStencilAttachment.depthLoadOp = GPULoadOp.Load;
  55568. if ( renderContext.stencil ) descriptor.depthStencilAttachment.stencilLoadOp = GPULoadOp.Load;
  55569. renderContextData.currentPass = encoder.beginRenderPass( descriptor );
  55570. renderContextData.currentSets = { attributes: {}, bindingGroups: [], pipeline: null, index: null };
  55571. if ( renderContext.viewport ) {
  55572. this.updateViewport( renderContext );
  55573. }
  55574. if ( renderContext.scissor ) {
  55575. this.updateScissor( renderContext );
  55576. }
  55577. } else {
  55578. this.device.queue.submit( [ encoder.finish() ] );
  55579. }
  55580. }
  55581. dispose() {
  55582. this.textureUtils.dispose();
  55583. }
  55584. }
  55585. /**
  55586. * A IES version of {@link SpotLight}. Can only be used with {@link WebGPURenderer}.
  55587. *
  55588. * @augments SpotLight
  55589. */
  55590. class IESSpotLight extends SpotLight {
  55591. /**
  55592. * Constructs a new IES spot light.
  55593. *
  55594. * @param {(number|Color|string)} [color=0xffffff] - The light's color.
  55595. * @param {number} [intensity=1] - The light's strength/intensity measured in candela (cd).
  55596. * @param {number} [distance=0] - Maximum range of the light. `0` means no limit.
  55597. * @param {number} [angle=Math.PI/3] - Maximum angle of light dispersion from its direction whose upper bound is `Math.PI/2`.
  55598. * @param {number} [penumbra=0] - Percent of the spotlight cone that is attenuated due to penumbra. Value range is `[0,1]`.
  55599. * @param {number} [decay=2] - The amount the light dims along the distance of the light.
  55600. */
  55601. constructor( color, intensity, distance, angle, penumbra, decay ) {
  55602. super( color, intensity, distance, angle, penumbra, decay );
  55603. /**
  55604. * TODO
  55605. *
  55606. * @type {?Texture}
  55607. * @default null
  55608. */
  55609. this.iesMap = null;
  55610. }
  55611. copy( source, recursive ) {
  55612. super.copy( source, recursive );
  55613. this.iesMap = source.iesMap;
  55614. return this;
  55615. }
  55616. }
  55617. /**
  55618. * A projector light version of {@link SpotLight}. Can only be used with {@link WebGPURenderer}.
  55619. *
  55620. * @augments SpotLight
  55621. */
  55622. class ProjectorLight extends SpotLight {
  55623. /**
  55624. * Constructs a new projector light.
  55625. *
  55626. * @param {(number|Color|string)} [color=0xffffff] - The light's color.
  55627. * @param {number} [intensity=1] - The light's strength/intensity measured in candela (cd).
  55628. * @param {number} [distance=0] - Maximum range of the light. `0` means no limit.
  55629. * @param {number} [angle=Math.PI/3] - Maximum angle of light dispersion from its direction whose upper bound is `Math.PI/2`.
  55630. * @param {number} [penumbra=0] - Percent of the spotlight cone that is attenuated due to penumbra. Value range is `[0,1]`.
  55631. * @param {number} [decay=2] - The amount the light dims along the distance of the light.
  55632. */
  55633. constructor( color, intensity, distance, angle, penumbra, decay ) {
  55634. super( color, intensity, distance, angle, penumbra, decay );
  55635. /**
  55636. * Aspect ratio of the light. Set to `null` to use the texture aspect ratio.
  55637. *
  55638. * @type {?number}
  55639. * @default null
  55640. */
  55641. this.aspect = null;
  55642. }
  55643. copy( source, recursive ) {
  55644. super.copy( source, recursive );
  55645. this.aspect = source.aspect;
  55646. return this;
  55647. }
  55648. }
  55649. /**
  55650. * This version of a node library represents the standard version
  55651. * used in {@link WebGPURenderer}. It maps lights, tone mapping
  55652. * techniques and materials to node-based implementations.
  55653. *
  55654. * @private
  55655. * @augments NodeLibrary
  55656. */
  55657. class StandardNodeLibrary extends NodeLibrary {
  55658. /**
  55659. * Constructs a new standard node library.
  55660. */
  55661. constructor() {
  55662. super();
  55663. this.addMaterial( MeshPhongNodeMaterial, 'MeshPhongMaterial' );
  55664. this.addMaterial( MeshStandardNodeMaterial, 'MeshStandardMaterial' );
  55665. this.addMaterial( MeshPhysicalNodeMaterial, 'MeshPhysicalMaterial' );
  55666. this.addMaterial( MeshToonNodeMaterial, 'MeshToonMaterial' );
  55667. this.addMaterial( MeshBasicNodeMaterial, 'MeshBasicMaterial' );
  55668. this.addMaterial( MeshLambertNodeMaterial, 'MeshLambertMaterial' );
  55669. this.addMaterial( MeshNormalNodeMaterial, 'MeshNormalMaterial' );
  55670. this.addMaterial( MeshMatcapNodeMaterial, 'MeshMatcapMaterial' );
  55671. this.addMaterial( LineBasicNodeMaterial, 'LineBasicMaterial' );
  55672. this.addMaterial( LineDashedNodeMaterial, 'LineDashedMaterial' );
  55673. this.addMaterial( PointsNodeMaterial, 'PointsMaterial' );
  55674. this.addMaterial( SpriteNodeMaterial, 'SpriteMaterial' );
  55675. this.addMaterial( ShadowNodeMaterial, 'ShadowMaterial' );
  55676. this.addLight( PointLightNode, PointLight );
  55677. this.addLight( DirectionalLightNode, DirectionalLight );
  55678. this.addLight( RectAreaLightNode, RectAreaLight );
  55679. this.addLight( SpotLightNode, SpotLight );
  55680. this.addLight( AmbientLightNode, AmbientLight );
  55681. this.addLight( HemisphereLightNode, HemisphereLight );
  55682. this.addLight( LightProbeNode, LightProbe );
  55683. this.addLight( IESSpotLightNode, IESSpotLight );
  55684. this.addLight( ProjectorLightNode, ProjectorLight );
  55685. this.addToneMapping( linearToneMapping, LinearToneMapping );
  55686. this.addToneMapping( reinhardToneMapping, ReinhardToneMapping );
  55687. this.addToneMapping( cineonToneMapping, CineonToneMapping );
  55688. this.addToneMapping( acesFilmicToneMapping, ACESFilmicToneMapping );
  55689. this.addToneMapping( agxToneMapping, AgXToneMapping );
  55690. this.addToneMapping( neutralToneMapping, NeutralToneMapping );
  55691. }
  55692. }
  55693. /*
  55694. const debugHandler = {
  55695. get: function ( target, name ) {
  55696. // Add |update
  55697. if ( /^(create|destroy)/.test( name ) ) log( 'WebGPUBackend.' + name );
  55698. return target[ name ];
  55699. }
  55700. };
  55701. */
  55702. /**
  55703. * This renderer is the new alternative of `WebGLRenderer`. `WebGPURenderer` has the ability
  55704. * to target different backends. By default, the renderer tries to use a WebGPU backend if the
  55705. * browser supports WebGPU. If not, `WebGPURenderer` falls backs to a WebGL 2 backend.
  55706. *
  55707. * @augments Renderer
  55708. */
  55709. class WebGPURenderer extends Renderer {
  55710. /**
  55711. * WebGPURenderer options.
  55712. *
  55713. * @typedef {Object} WebGPURenderer~Options
  55714. * @property {boolean} [logarithmicDepthBuffer=false] - Whether logarithmic depth buffer is enabled or not.
  55715. * @property {boolean} [alpha=true] - Whether the default framebuffer (which represents the final contents of the canvas) should be transparent or opaque.
  55716. * @property {boolean} [depth=true] - Whether the default framebuffer should have a depth buffer or not.
  55717. * @property {boolean} [stencil=false] - Whether the default framebuffer should have a stencil buffer or not.
  55718. * @property {boolean} [antialias=false] - Whether MSAA as the default anti-aliasing should be enabled or not.
  55719. * @property {number} [samples=0] - When `antialias` is `true`, `4` samples are used by default. Set this parameter to any other integer value than 0 to overwrite the default.
  55720. * @property {boolean} [forceWebGL=false] - If set to `true`, the renderer uses a WebGL 2 backend no matter if WebGPU is supported or not.
  55721. * @property {boolean} [multiview=false] - If set to `true`, the renderer will use multiview during WebXR rendering if supported.
  55722. * @property {number} [outputType=undefined] - Texture type for output to canvas. By default, device's preferred format is used; other formats may incur overhead.
  55723. * @property {number} [colorBufferType=HalfFloatType] - Defines the type of color buffers. The default `HalfFloatType` is recommend for best
  55724. * quality. To save memory and bandwidth, `UnsignedByteType` might be used. This will reduce rendering quality though.
  55725. */
  55726. /**
  55727. * Constructs a new WebGPU renderer.
  55728. *
  55729. * @param {WebGPURenderer~Options} [parameters] - The configuration parameter.
  55730. */
  55731. constructor( parameters = {} ) {
  55732. let BackendClass;
  55733. if ( parameters.forceWebGL ) {
  55734. BackendClass = WebGLBackend;
  55735. } else {
  55736. BackendClass = WebGPUBackend;
  55737. parameters.getFallback = () => {
  55738. warn( 'WebGPURenderer: WebGPU is not available, running under WebGL2 backend.' );
  55739. return new WebGLBackend( parameters );
  55740. };
  55741. }
  55742. const backend = new BackendClass( parameters );
  55743. //super( new Proxy( backend, debugHandler ) );
  55744. super( backend, parameters );
  55745. /**
  55746. * The generic default value is overwritten with the
  55747. * standard node library for type mapping.
  55748. *
  55749. * @type {StandardNodeLibrary}
  55750. */
  55751. this.library = new StandardNodeLibrary();
  55752. /**
  55753. * This flag can be used for type testing.
  55754. *
  55755. * @type {boolean}
  55756. * @readonly
  55757. * @default true
  55758. */
  55759. this.isWebGPURenderer = true;
  55760. if ( typeof __THREE_DEVTOOLS__ !== 'undefined' ) {
  55761. __THREE_DEVTOOLS__.dispatchEvent( new CustomEvent( 'observe', { detail: this } ) );
  55762. }
  55763. }
  55764. }
  55765. /**
  55766. * A specialized group which enables applications access to the
  55767. * Render Bundle API of WebGPU. The group with all its descendant nodes
  55768. * are considered as one render bundle and processed as such by
  55769. * the renderer.
  55770. *
  55771. * This module is only fully supported by `WebGPURenderer` with a WebGPU backend.
  55772. * With a WebGL backend, the group can technically be rendered but without
  55773. * any performance improvements.
  55774. *
  55775. * @augments Group
  55776. */
  55777. class BundleGroup extends Group {
  55778. /**
  55779. * Constructs a new bundle group.
  55780. */
  55781. constructor() {
  55782. super();
  55783. /**
  55784. * This flag can be used for type testing.
  55785. *
  55786. * @type {boolean}
  55787. * @readonly
  55788. * @default true
  55789. */
  55790. this.isBundleGroup = true;
  55791. /**
  55792. * This property is only relevant for detecting types
  55793. * during serialization/deserialization. It should always
  55794. * match the class name.
  55795. *
  55796. * @type {string}
  55797. * @readonly
  55798. * @default 'BundleGroup'
  55799. */
  55800. this.type = 'BundleGroup';
  55801. /**
  55802. * Whether the bundle is static or not. When set to `true`, the structure
  55803. * is assumed to be static and does not change. E.g. no new objects are
  55804. * added to the group
  55805. *
  55806. * If a change is required, an update can still be forced by setting the
  55807. * `needsUpdate` flag to `true`.
  55808. *
  55809. * @type {boolean}
  55810. * @default true
  55811. */
  55812. this.static = true;
  55813. /**
  55814. * The bundle group's version.
  55815. *
  55816. * @type {number}
  55817. * @readonly
  55818. * @default 0
  55819. */
  55820. this.version = 0;
  55821. }
  55822. /**
  55823. * Set this property to `true` when the bundle group has changed.
  55824. *
  55825. * @type {boolean}
  55826. * @default false
  55827. * @param {boolean} value
  55828. */
  55829. set needsUpdate( value ) {
  55830. if ( value === true ) this.version ++;
  55831. }
  55832. }
  55833. /**
  55834. * This module is responsible to manage the post processing setups in apps.
  55835. * You usually create a single instance of this class and use it to define
  55836. * the output of your post processing effect chain.
  55837. * ```js
  55838. * const postProcessing = new PostProcessing( renderer );
  55839. *
  55840. * const scenePass = pass( scene, camera );
  55841. *
  55842. * postProcessing.outputNode = scenePass;
  55843. * ```
  55844. *
  55845. * Note: This module can only be used with `WebGPURenderer`.
  55846. */
  55847. class PostProcessing {
  55848. /**
  55849. * Constructs a new post processing management module.
  55850. *
  55851. * @param {Renderer} renderer - A reference to the renderer.
  55852. * @param {Node<vec4>} outputNode - An optional output node.
  55853. */
  55854. constructor( renderer, outputNode = vec4( 0, 0, 1, 1 ) ) {
  55855. /**
  55856. * A reference to the renderer.
  55857. *
  55858. * @type {Renderer}
  55859. */
  55860. this.renderer = renderer;
  55861. /**
  55862. * A node which defines the final output of the post
  55863. * processing. This is usually the last node in a chain
  55864. * of effect nodes.
  55865. *
  55866. * @type {Node<vec4>}
  55867. */
  55868. this.outputNode = outputNode;
  55869. /**
  55870. * Whether the default output tone mapping and color
  55871. * space transformation should be enabled or not.
  55872. *
  55873. * It is enabled by default by it must be disabled when
  55874. * effects must be executed after tone mapping and color
  55875. * space conversion. A typical example is FXAA which
  55876. * requires sRGB input.
  55877. *
  55878. * When set to `false`, the app must control the output
  55879. * transformation with `RenderOutputNode`.
  55880. *
  55881. * ```js
  55882. * const outputPass = renderOutput( scenePass );
  55883. * ```
  55884. *
  55885. * @type {boolean}
  55886. */
  55887. this.outputColorTransform = true;
  55888. /**
  55889. * Must be set to `true` when the output node changes.
  55890. *
  55891. * @type {Node<vec4>}
  55892. */
  55893. this.needsUpdate = true;
  55894. const material = new NodeMaterial();
  55895. material.name = 'PostProcessing';
  55896. /**
  55897. * The full screen quad that is used to render
  55898. * the effects.
  55899. *
  55900. * @private
  55901. * @type {QuadMesh}
  55902. */
  55903. this._quadMesh = new QuadMesh( material );
  55904. this._quadMesh.name = 'Post-Processing';
  55905. /**
  55906. * The context of the post processing stack.
  55907. *
  55908. * @private
  55909. * @type {?Object}
  55910. * @default null
  55911. */
  55912. this._context = null;
  55913. }
  55914. /**
  55915. * When `PostProcessing` is used to apply post processing effects,
  55916. * the application must use this version of `render()` inside
  55917. * its animation loop (not the one from the renderer).
  55918. */
  55919. render() {
  55920. const renderer = this.renderer;
  55921. this._update();
  55922. if ( this._context.onBeforePostProcessing !== null ) this._context.onBeforePostProcessing();
  55923. const toneMapping = renderer.toneMapping;
  55924. const outputColorSpace = renderer.outputColorSpace;
  55925. renderer.toneMapping = NoToneMapping;
  55926. renderer.outputColorSpace = ColorManagement.workingColorSpace;
  55927. //
  55928. const currentXR = renderer.xr.enabled;
  55929. renderer.xr.enabled = false;
  55930. this._quadMesh.render( renderer );
  55931. renderer.xr.enabled = currentXR;
  55932. //
  55933. renderer.toneMapping = toneMapping;
  55934. renderer.outputColorSpace = outputColorSpace;
  55935. if ( this._context.onAfterPostProcessing !== null ) this._context.onAfterPostProcessing();
  55936. }
  55937. /**
  55938. * Returns the current context of the post processing stack.
  55939. *
  55940. * @readonly
  55941. * @type {?Object}
  55942. */
  55943. get context() {
  55944. return this._context;
  55945. }
  55946. /**
  55947. * Frees internal resources.
  55948. */
  55949. dispose() {
  55950. this._quadMesh.material.dispose();
  55951. }
  55952. /**
  55953. * Updates the state of the module.
  55954. *
  55955. * @private
  55956. */
  55957. _update() {
  55958. if ( this.needsUpdate === true ) {
  55959. const renderer = this.renderer;
  55960. const toneMapping = renderer.toneMapping;
  55961. const outputColorSpace = renderer.outputColorSpace;
  55962. const context = {
  55963. postProcessing: this,
  55964. onBeforePostProcessing: null,
  55965. onAfterPostProcessing: null
  55966. };
  55967. let outputNode = this.outputNode;
  55968. if ( this.outputColorTransform === true ) {
  55969. outputNode = outputNode.context( context );
  55970. outputNode = renderOutput( outputNode, toneMapping, outputColorSpace );
  55971. } else {
  55972. context.toneMapping = toneMapping;
  55973. context.outputColorSpace = outputColorSpace;
  55974. outputNode = outputNode.context( context );
  55975. }
  55976. this._context = context;
  55977. this._quadMesh.material.fragmentNode = outputNode;
  55978. this._quadMesh.material.needsUpdate = true;
  55979. this.needsUpdate = false;
  55980. }
  55981. }
  55982. /**
  55983. * When `PostProcessing` is used to apply post processing effects,
  55984. * the application must use this version of `renderAsync()` inside
  55985. * its animation loop (not the one from the renderer).
  55986. *
  55987. * @async
  55988. * @deprecated
  55989. * @return {Promise} A Promise that resolves when the render has been finished.
  55990. */
  55991. async renderAsync() {
  55992. warnOnce( 'PostProcessing: "renderAsync()" has been deprecated. Use "render()" and "await renderer.init();" when creating the renderer.' ); // @deprecated r181
  55993. await this.renderer.init();
  55994. this.render();
  55995. }
  55996. }
  55997. /**
  55998. * This special type of texture is intended for compute shaders.
  55999. * It can be used to compute the data of a texture with a compute shader.
  56000. *
  56001. * Note: This type of texture can only be used with `WebGPURenderer`
  56002. * and a WebGPU backend.
  56003. *
  56004. * @augments Texture
  56005. */
  56006. class StorageTexture extends Texture {
  56007. /**
  56008. * Constructs a new storage texture.
  56009. *
  56010. * @param {number} [width=1] - The storage texture's width.
  56011. * @param {number} [height=1] - The storage texture's height.
  56012. */
  56013. constructor( width = 1, height = 1 ) {
  56014. super();
  56015. /**
  56016. * The image object which just represents the texture's dimension.
  56017. *
  56018. * @type {{width: number, height: number}}
  56019. */
  56020. this.image = { width, height };
  56021. /**
  56022. * The default `magFilter` for storage textures is `THREE.LinearFilter`.
  56023. *
  56024. * @type {number}
  56025. */
  56026. this.magFilter = LinearFilter;
  56027. /**
  56028. * The default `minFilter` for storage textures is `THREE.LinearFilter`.
  56029. *
  56030. * @type {number}
  56031. */
  56032. this.minFilter = LinearFilter;
  56033. /**
  56034. * This flag can be used for type testing.
  56035. *
  56036. * @type {boolean}
  56037. * @readonly
  56038. * @default true
  56039. */
  56040. this.isStorageTexture = true;
  56041. /**
  56042. * When `true`, mipmaps will be auto-generated after compute writes.
  56043. * When `false`, mipmaps must be written manually via compute shaders.
  56044. *
  56045. * @type {boolean}
  56046. * @default true
  56047. */
  56048. this.mipmapsAutoUpdate = true;
  56049. }
  56050. /**
  56051. * Sets the size of the storage texture.
  56052. *
  56053. * @param {number} width - The new width of the storage texture.
  56054. * @param {number} height - The new height of the storage texture.
  56055. */
  56056. setSize( width, height ) {
  56057. if ( this.image.width !== width || this.image.height !== height ) {
  56058. this.image.width = width;
  56059. this.image.height = height;
  56060. this.dispose();
  56061. }
  56062. }
  56063. }
  56064. /**
  56065. * This special type of texture is intended for compute shaders.
  56066. * It can be used to compute the data of a texture with a compute shader.
  56067. *
  56068. * Note: This type of texture can only be used with `WebGPURenderer`
  56069. * and a WebGPU backend.
  56070. *
  56071. * @augments Texture
  56072. */
  56073. class Storage3DTexture extends Texture {
  56074. /**
  56075. * Constructs a new storage texture.
  56076. *
  56077. * @param {number} [width=1] - The storage texture's width.
  56078. * @param {number} [height=1] - The storage texture's height.
  56079. * @param {number} [depth=1] - The storage texture's depth.
  56080. */
  56081. constructor( width = 1, height = 1, depth = 1 ) {
  56082. super();
  56083. //inherited from texture. Must be false for 3DTexture
  56084. this.isArrayTexture = false;
  56085. /**
  56086. * The image object which just represents the texture's dimension.
  56087. *
  56088. * @type {{width: number, height: number, depth: number}}
  56089. */
  56090. this.image = { width, height, depth };
  56091. /**
  56092. * The default `magFilter` for storage textures is `THREE.LinearFilter`.
  56093. *
  56094. * @type {number}
  56095. */
  56096. this.magFilter = LinearFilter;
  56097. /**
  56098. * The default `minFilter` for storage textures is `THREE.LinearFilter`.
  56099. *
  56100. * @type {number}
  56101. */
  56102. this.minFilter = LinearFilter;
  56103. /**
  56104. * This defines how the texture is wrapped in the depth direction and corresponds to
  56105. * *W* in UVW mapping.
  56106. *
  56107. * @type {number}
  56108. */
  56109. this.wrapR = ClampToEdgeWrapping;
  56110. /**
  56111. * This flag can be used for type testing.
  56112. *
  56113. * @type {boolean}
  56114. * @readonly
  56115. * @default true
  56116. */
  56117. this.isStorageTexture = true;
  56118. /**
  56119. * Indicates whether this texture is a 3D texture.
  56120. *
  56121. * @type {boolean}
  56122. *
  56123. */
  56124. this.is3DTexture = true;
  56125. }
  56126. /**
  56127. * Sets the size of the storage 3d texture.
  56128. *
  56129. * @param {number} width - The new width of the storage texture.
  56130. * @param {number} height - The new height of the storage texture.
  56131. * @param {number} depth - The new depth of the storage texture.
  56132. */
  56133. setSize( width, height, depth ) {
  56134. if ( this.image.width !== width || this.image.height !== height || this.image.depth !== depth ) {
  56135. this.image.width = width;
  56136. this.image.height = height;
  56137. this.image.depth = depth;
  56138. this.dispose();
  56139. }
  56140. }
  56141. }
  56142. /**
  56143. * This special type of texture is intended for compute shaders.
  56144. * It can be used to compute the data of a texture with a compute shader.
  56145. *
  56146. * Note: This type of texture can only be used with `WebGPURenderer`
  56147. * and a WebGPU backend.
  56148. *
  56149. * @augments Texture
  56150. */
  56151. class StorageArrayTexture extends Texture {
  56152. /**
  56153. * Constructs a new storage texture.
  56154. *
  56155. * @param {number} [width=1] - The storage texture's width.
  56156. * @param {number} [height=1] - The storage texture's height.
  56157. * @param {number} [depth=1] - The storage texture's depth.
  56158. */
  56159. constructor( width = 1, height = 1, depth = 1 ) {
  56160. super();
  56161. //inherited from texture
  56162. this.isArrayTexture = true;
  56163. /**
  56164. * The image object which just represents the texture's dimension.
  56165. *
  56166. * @type {{width: number, height: number, depth: number}}
  56167. */
  56168. this.image = { width, height, depth };
  56169. /**
  56170. * The default `magFilter` for storage textures is `THREE.LinearFilter`.
  56171. *
  56172. * @type {number}
  56173. */
  56174. this.magFilter = LinearFilter;
  56175. /**
  56176. * The default `minFilter` for storage textures is `THREE.LinearFilter`.
  56177. *
  56178. * @type {number}
  56179. */
  56180. this.minFilter = LinearFilter;
  56181. /**
  56182. * This flag can be used for type testing.
  56183. *
  56184. * @type {boolean}
  56185. * @readonly
  56186. * @default true
  56187. */
  56188. this.isStorageTexture = true;
  56189. }
  56190. /**
  56191. * Sets the size of the storage array texture.
  56192. *
  56193. * @param {number} width - The new width of the storage texture.
  56194. * @param {number} height - The new height of the storage texture.
  56195. * @param {number} depth - The new depth of the storage texture.
  56196. */
  56197. setSize( width, height, depth ) {
  56198. if ( this.image.width !== width || this.image.height !== height || this.image.depth !== depth ) {
  56199. this.image.width = width;
  56200. this.image.height = height;
  56201. this.image.depth = depth;
  56202. this.dispose();
  56203. }
  56204. }
  56205. }
  56206. /**
  56207. * This special type of buffer attribute is intended for compute shaders.
  56208. * It can be used to encode draw parameters for indirect draw calls.
  56209. *
  56210. * Note: This type of buffer attribute can only be used with `WebGPURenderer`
  56211. * and a WebGPU backend.
  56212. *
  56213. * @augments StorageBufferAttribute
  56214. */
  56215. class IndirectStorageBufferAttribute extends StorageBufferAttribute {
  56216. /**
  56217. * Constructs a new storage buffer attribute.
  56218. *
  56219. * @param {number|Uint32Array} count - The item count. It is also valid to pass a `Uint32Array` as an argument.
  56220. * The subsequent parameter is then obsolete.
  56221. * @param {number} itemSize - The item size.
  56222. */
  56223. constructor( count, itemSize ) {
  56224. super( count, itemSize, Uint32Array );
  56225. /**
  56226. * This flag can be used for type testing.
  56227. *
  56228. * @type {boolean}
  56229. * @readonly
  56230. * @default true
  56231. */
  56232. this.isIndirectStorageBufferAttribute = true;
  56233. }
  56234. }
  56235. /**
  56236. * A loader for loading node objects in the three.js JSON Object/Scene format.
  56237. *
  56238. * @augments Loader
  56239. */
  56240. class NodeLoader extends Loader {
  56241. /**
  56242. * Constructs a new node loader.
  56243. *
  56244. * @param {LoadingManager} [manager] - A reference to a loading manager.
  56245. */
  56246. constructor( manager ) {
  56247. super( manager );
  56248. /**
  56249. * Represents a dictionary of textures.
  56250. *
  56251. * @type {Object<string,Texture>}
  56252. */
  56253. this.textures = {};
  56254. /**
  56255. * Represents a dictionary of node types.
  56256. *
  56257. * @type {Object<string,Node.constructor>}
  56258. */
  56259. this.nodes = {};
  56260. }
  56261. /**
  56262. * Loads the node definitions from the given URL.
  56263. *
  56264. * @param {string} url - The path/URL of the file to be loaded.
  56265. * @param {Function} onLoad - Will be called when load completes.
  56266. * @param {Function} onProgress - Will be called while load progresses.
  56267. * @param {Function} onError - Will be called when errors are thrown during the loading process.
  56268. */
  56269. load( url, onLoad, onProgress, onError ) {
  56270. const loader = new FileLoader( this.manager );
  56271. loader.setPath( this.path );
  56272. loader.setRequestHeader( this.requestHeader );
  56273. loader.setWithCredentials( this.withCredentials );
  56274. loader.load( url, ( text ) => {
  56275. try {
  56276. onLoad( this.parse( JSON.parse( text ) ) );
  56277. } catch ( e ) {
  56278. if ( onError ) {
  56279. onError( e );
  56280. } else {
  56281. error( e );
  56282. }
  56283. this.manager.itemError( url );
  56284. }
  56285. }, onProgress, onError );
  56286. }
  56287. /**
  56288. * Parse the node dependencies for the loaded node.
  56289. *
  56290. * @param {Array<Object>} [json] - The JSON definition
  56291. * @return {Object<string,Node>} A dictionary with node dependencies.
  56292. */
  56293. parseNodes( json ) {
  56294. const nodes = {};
  56295. if ( json !== undefined ) {
  56296. for ( const nodeJSON of json ) {
  56297. const { uuid, type } = nodeJSON;
  56298. nodes[ uuid ] = this.createNodeFromType( type );
  56299. nodes[ uuid ].uuid = uuid;
  56300. }
  56301. const meta = { nodes, textures: this.textures };
  56302. for ( const nodeJSON of json ) {
  56303. nodeJSON.meta = meta;
  56304. const node = nodes[ nodeJSON.uuid ];
  56305. node.deserialize( nodeJSON );
  56306. delete nodeJSON.meta;
  56307. }
  56308. }
  56309. return nodes;
  56310. }
  56311. /**
  56312. * Parses the node from the given JSON.
  56313. *
  56314. * @param {Object} json - The JSON definition
  56315. * @param {string} json.type - The node type.
  56316. * @param {string} json.uuid - The node UUID.
  56317. * @param {Array<Object>} [json.nodes] - The node dependencies.
  56318. * @param {Object} [json.meta] - The meta data.
  56319. * @return {Node} The parsed node.
  56320. */
  56321. parse( json ) {
  56322. const node = this.createNodeFromType( json.type );
  56323. node.uuid = json.uuid;
  56324. const nodes = this.parseNodes( json.nodes );
  56325. const meta = { nodes, textures: this.textures };
  56326. json.meta = meta;
  56327. node.deserialize( json );
  56328. delete json.meta;
  56329. return node;
  56330. }
  56331. /**
  56332. * Defines the dictionary of textures.
  56333. *
  56334. * @param {Object<string,Texture>} value - The texture library defines as `<uuid,texture>`.
  56335. * @return {NodeLoader} A reference to this loader.
  56336. */
  56337. setTextures( value ) {
  56338. this.textures = value;
  56339. return this;
  56340. }
  56341. /**
  56342. * Defines the dictionary of node types.
  56343. *
  56344. * @param {Object<string,Node.constructor>} value - The node library defined as `<classname,class>`.
  56345. * @return {NodeLoader} A reference to this loader.
  56346. */
  56347. setNodes( value ) {
  56348. this.nodes = value;
  56349. return this;
  56350. }
  56351. /**
  56352. * Creates a node object from the given type.
  56353. *
  56354. * @param {string} type - The node type.
  56355. * @return {Node} The created node instance.
  56356. */
  56357. createNodeFromType( type ) {
  56358. if ( this.nodes[ type ] === undefined ) {
  56359. error( 'NodeLoader: Node type not found:', type );
  56360. return float();
  56361. }
  56362. return nodeObject( new this.nodes[ type ]() );
  56363. }
  56364. }
  56365. /**
  56366. * A special type of material loader for loading node materials.
  56367. *
  56368. * @augments MaterialLoader
  56369. */
  56370. class NodeMaterialLoader extends MaterialLoader {
  56371. /**
  56372. * Constructs a new node material loader.
  56373. *
  56374. * @param {LoadingManager} [manager] - A reference to a loading manager.
  56375. */
  56376. constructor( manager ) {
  56377. super( manager );
  56378. /**
  56379. * Represents a dictionary of node types.
  56380. *
  56381. * @type {Object<string,Node.constructor>}
  56382. */
  56383. this.nodes = {};
  56384. /**
  56385. * Represents a dictionary of node material types.
  56386. *
  56387. * @type {Object<string,NodeMaterial.constructor>}
  56388. */
  56389. this.nodeMaterials = {};
  56390. }
  56391. /**
  56392. * Parses the node material from the given JSON.
  56393. *
  56394. * @param {Object} json - The JSON definition
  56395. * @return {NodeMaterial}. The parsed material.
  56396. */
  56397. parse( json ) {
  56398. const material = super.parse( json );
  56399. const nodes = this.nodes;
  56400. const inputNodes = json.inputNodes;
  56401. for ( const property in inputNodes ) {
  56402. const uuid = inputNodes[ property ];
  56403. material[ property ] = nodes[ uuid ];
  56404. }
  56405. return material;
  56406. }
  56407. /**
  56408. * Defines the dictionary of node types.
  56409. *
  56410. * @param {Object<string,Node.constructor>} value - The node library defined as `<classname,class>`.
  56411. * @return {NodeLoader} A reference to this loader.
  56412. */
  56413. setNodes( value ) {
  56414. this.nodes = value;
  56415. return this;
  56416. }
  56417. /**
  56418. * Defines the dictionary of node material types.
  56419. *
  56420. * @param {Object<string,NodeMaterial.constructor>} value - The node material library defined as `<classname,class>`.
  56421. * @return {NodeLoader} A reference to this loader.
  56422. */
  56423. setNodeMaterials( value ) {
  56424. this.nodeMaterials = value;
  56425. return this;
  56426. }
  56427. /**
  56428. * Creates a node material from the given type.
  56429. *
  56430. * @param {string} type - The node material type.
  56431. * @return {Node} The created node material instance.
  56432. */
  56433. createMaterialFromType( type ) {
  56434. const materialClass = this.nodeMaterials[ type ];
  56435. if ( materialClass !== undefined ) {
  56436. return new materialClass();
  56437. }
  56438. return super.createMaterialFromType( type );
  56439. }
  56440. }
  56441. /**
  56442. * A special type of object loader for loading 3D objects using
  56443. * node materials.
  56444. *
  56445. * @augments ObjectLoader
  56446. */
  56447. class NodeObjectLoader extends ObjectLoader {
  56448. /**
  56449. * Constructs a new node object loader.
  56450. *
  56451. * @param {LoadingManager} [manager] - A reference to a loading manager.
  56452. */
  56453. constructor( manager ) {
  56454. super( manager );
  56455. /**
  56456. * Represents a dictionary of node types.
  56457. *
  56458. * @type {Object<string,Node.constructor>}
  56459. */
  56460. this.nodes = {};
  56461. /**
  56462. * Represents a dictionary of node material types.
  56463. *
  56464. * @type {Object<string,NodeMaterial.constructor>}
  56465. */
  56466. this.nodeMaterials = {};
  56467. /**
  56468. * A reference to hold the `nodes` JSON property.
  56469. *
  56470. * @private
  56471. * @type {?Object[]}
  56472. */
  56473. this._nodesJSON = null;
  56474. }
  56475. /**
  56476. * Defines the dictionary of node types.
  56477. *
  56478. * @param {Object<string,Node.constructor>} value - The node library defined as `<classname,class>`.
  56479. * @return {NodeObjectLoader} A reference to this loader.
  56480. */
  56481. setNodes( value ) {
  56482. this.nodes = value;
  56483. return this;
  56484. }
  56485. /**
  56486. * Defines the dictionary of node material types.
  56487. *
  56488. * @param {Object<string,NodeMaterial.constructor>} value - The node material library defined as `<classname,class>`.
  56489. * @return {NodeObjectLoader} A reference to this loader.
  56490. */
  56491. setNodeMaterials( value ) {
  56492. this.nodeMaterials = value;
  56493. return this;
  56494. }
  56495. /**
  56496. * Parses the node objects from the given JSON.
  56497. *
  56498. * @param {Object} json - The JSON definition
  56499. * @param {Function} onLoad - The onLoad callback function.
  56500. * @return {Object3D}. The parsed 3D object.
  56501. */
  56502. parse( json, onLoad ) {
  56503. this._nodesJSON = json.nodes;
  56504. const data = super.parse( json, onLoad );
  56505. this._nodesJSON = null; // dispose
  56506. return data;
  56507. }
  56508. /**
  56509. * Parses the node objects from the given JSON and textures.
  56510. *
  56511. * @param {Object[]} json - The JSON definition
  56512. * @param {Object<string,Texture>} textures - The texture library.
  56513. * @return {Object<string,Node>}. The parsed nodes.
  56514. */
  56515. parseNodes( json, textures ) {
  56516. if ( json !== undefined ) {
  56517. const loader = new NodeLoader();
  56518. loader.setNodes( this.nodes );
  56519. loader.setTextures( textures );
  56520. return loader.parseNodes( json );
  56521. }
  56522. return {};
  56523. }
  56524. /**
  56525. * Parses the node objects from the given JSON and textures.
  56526. *
  56527. * @param {Object} json - The JSON definition
  56528. * @param {Object<string,Texture>} textures - The texture library.
  56529. * @return {Object<string,NodeMaterial>}. The parsed materials.
  56530. */
  56531. parseMaterials( json, textures ) {
  56532. const materials = {};
  56533. if ( json !== undefined ) {
  56534. const nodes = this.parseNodes( this._nodesJSON, textures );
  56535. const loader = new NodeMaterialLoader();
  56536. loader.setTextures( textures );
  56537. loader.setNodes( nodes );
  56538. loader.setNodeMaterials( this.nodeMaterials );
  56539. for ( let i = 0, l = json.length; i < l; i ++ ) {
  56540. const data = json[ i ];
  56541. materials[ data.uuid ] = loader.parse( data );
  56542. }
  56543. }
  56544. return materials;
  56545. }
  56546. }
  56547. /**
  56548. * In earlier three.js versions, clipping was defined globally
  56549. * on the renderer or on material level. This special version of
  56550. * `THREE.Group` allows to encode the clipping state into the scene
  56551. * graph. Meaning if you create an instance of this group, all
  56552. * descendant 3D objects will be affected by the respective clipping
  56553. * planes.
  56554. *
  56555. * Note: `ClippingGroup` can only be used with `WebGPURenderer`.
  56556. *
  56557. * @augments Group
  56558. */
  56559. class ClippingGroup extends Group {
  56560. /**
  56561. * Constructs a new clipping group.
  56562. */
  56563. constructor() {
  56564. super();
  56565. /**
  56566. * This flag can be used for type testing.
  56567. *
  56568. * @type {boolean}
  56569. * @readonly
  56570. * @default true
  56571. */
  56572. this.isClippingGroup = true;
  56573. /**
  56574. * An array with clipping planes.
  56575. *
  56576. * @type {Array<Plane>}
  56577. */
  56578. this.clippingPlanes = [];
  56579. /**
  56580. * Whether clipping should be enabled or not.
  56581. *
  56582. * @type {boolean}
  56583. * @default true
  56584. */
  56585. this.enabled = true;
  56586. /**
  56587. * Whether the intersection of the clipping planes is used to clip objects, rather than their union.
  56588. *
  56589. * @type {boolean}
  56590. * @default false
  56591. */
  56592. this.clipIntersection = false;
  56593. /**
  56594. * Whether shadows should be clipped or not.
  56595. *
  56596. * @type {boolean}
  56597. * @default false
  56598. */
  56599. this.clipShadows = false;
  56600. }
  56601. }
  56602. export { ACESFilmicToneMapping, AONode, AddEquation, AddOperation, AdditiveBlending, AgXToneMapping, AlphaFormat, AlwaysCompare, AlwaysDepth, AlwaysStencilFunc, AmbientLight, AmbientLightNode, AnalyticLightNode, ArrayCamera, ArrayElementNode, ArrayNode, AssignNode, AttributeNode, BackSide, BasicEnvironmentNode, BasicShadowMap, BatchNode, BitcastNode, BoxGeometry, BufferAttribute, BufferAttributeNode, BufferGeometry, BufferNode, BumpMapNode, BundleGroup, BypassNode, ByteType, Camera, CanvasTarget, CineonToneMapping, ClampToEdgeWrapping, ClippingGroup, CodeNode, Color, ColorManagement, ColorSpaceNode, ComputeNode, ConstNode, ContextNode, ConvertNode, CubeCamera, CubeReflectionMapping, CubeRefractionMapping, CubeTexture, CubeTextureNode, CubeUVReflectionMapping, CullFaceBack, CullFaceFront, CullFaceNone, CustomBlending, CylinderGeometry, DataArrayTexture, DataTexture, DebugNode, DecrementStencilOp, DecrementWrapStencilOp, DepthFormat, DepthStencilFormat, DepthTexture, DirectionalLight, DirectionalLightNode, DoubleSide, DstAlphaFactor, DstColorFactor, DynamicDrawUsage, EnvironmentNode, EqualCompare, EqualDepth, EqualStencilFunc, EquirectangularReflectionMapping, EquirectangularRefractionMapping, Euler, EventDispatcher, EventNode, ExpressionNode, FileLoader, Float16BufferAttribute, Float32BufferAttribute, FloatType, FramebufferTexture, FrontFacingNode, FrontSide, Frustum, FrustumArray, FunctionCallNode, FunctionNode, FunctionOverloadingNode, GLSLNodeParser, GreaterCompare, GreaterDepth, GreaterEqualCompare, GreaterEqualDepth, GreaterEqualStencilFunc, GreaterStencilFunc, Group, HalfFloatType, HemisphereLight, HemisphereLightNode, IESSpotLight, IESSpotLightNode, IncrementStencilOp, IncrementWrapStencilOp, IndexNode, IndirectStorageBufferAttribute, InspectorBase, InstanceNode, InstancedBufferAttribute, InstancedInterleavedBuffer, InstancedMeshNode, IntType, InterleavedBuffer, InterleavedBufferAttribute, InvertStencilOp, IrradianceNode, IsolateNode, 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, LinearTransfer, Loader, LoopNode, MRTNode, Material, MaterialLoader, MaterialNode, MaterialReferenceNode, MathUtils, Matrix2, Matrix3, Matrix4, MaxEquation, MaxMipLevelNode, MemberNode, Mesh, MeshBasicMaterial, MeshBasicNodeMaterial, MeshLambertMaterial, MeshLambertNodeMaterial, MeshMatcapMaterial, MeshMatcapNodeMaterial, MeshNormalMaterial, MeshNormalNodeMaterial, MeshPhongMaterial, MeshPhongNodeMaterial, MeshPhysicalMaterial, MeshPhysicalNodeMaterial, MeshSSSNodeMaterial, MeshStandardMaterial, MeshStandardNodeMaterial, MeshToonMaterial, MeshToonNodeMaterial, MinEquation, MirroredRepeatWrapping, MixOperation, ModelNode, 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, PlaneGeometry, PointLight, PointLightNode, PointUVNode, PointsMaterial, PointsNodeMaterial, PostProcessing, PosterizeNode, ProjectorLight, ProjectorLightNode, PropertyNode, QuadMesh, Quaternion, 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, RendererUtils, 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, Sphere, SphereGeometry, SplitNode, SpotLight, SpotLightNode, SpriteMaterial, SpriteNodeMaterial, SpriteSheetUVNode, SrcAlphaFactor, SrcAlphaSaturateFactor, SrcColorFactor, StackNode, StaticDrawUsage, Storage3DTexture, StorageArrayElementNode, StorageArrayTexture, StorageBufferAttribute, StorageBufferNode, StorageInstancedBufferAttribute, StorageTexture, StorageTextureNode, StructNode, StructTypeNode, SubBuildNode, SubtractEquation, SubtractiveBlending, TSL, TangentSpaceNormalMap, TempNode, Texture, Texture3DNode, TextureNode, TextureSizeNode, TimestampQuery, ToneMappingNode, ToonOutlinePassNode, UVMapping, Uint16BufferAttribute, Uint32BufferAttribute, UniformArrayNode, UniformGroupNode, UniformNode, UnsignedByteType, UnsignedInt101111Type, UnsignedInt248Type, UnsignedInt5999Type, UnsignedIntType, UnsignedShort4444Type, UnsignedShort5551Type, UnsignedShortType, UserDataNode, VSMShadowMap, VarNode, VaryingNode, Vector2, Vector3, Vector4, VertexColorNode, ViewportDepthNode, ViewportDepthTextureNode, ViewportSharedTextureNode, ViewportTextureNode, VolumeNodeMaterial, WebGLCoordinateSystem, WebGLCubeRenderTarget, WebGPUCoordinateSystem, WebGPURenderer, WebXRController, ZeroFactor, ZeroStencilOp, createCanvasElement, defaultBuildStages, defaultShaderStages, error, log$1 as log, shaderStages, vectorComponents, warn, warnOnce };
粤ICP备19079148号