three.webgpu.nodes.js 1.9 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345333463334733348333493335033351333523335333354333553335633357333583335933360333613336233363333643336533366333673336833369333703337133372333733337433375333763337733378333793338033381333823338333384333853338633387333883338933390333913339233393333943339533396333973339833399334003340133402334033340433405334063340733408334093341033411334123341333414334153341633417334183341933420334213342233423334243342533426334273342833429334303343133432334333343433435334363343733438334393344033441334423344333444334453344633447334483344933450334513345233453334543345533456334573345833459334603346133462334633346433465334663346733468334693347033471334723347333474334753347633477334783347933480334813348233483334843348533486334873348833489334903349133492334933349433495334963349733498334993350033501335023350333504335053350633507335083350933510335113351233513335143351533516335173351833519335203352133522335233352433525335263352733528335293353033531335323353333534335353353633537335383353933540335413354233543335443354533546335473354833549335503355133552335533355433555335563355733558335593356033561335623356333564335653356633567335683356933570335713357233573335743357533576335773357833579335803358133582335833358433585335863358733588335893359033591335923359333594335953359633597335983359933600336013360233603336043360533606336073360833609336103361133612336133361433615336163361733618336193362033621336223362333624336253362633627336283362933630336313363233633336343363533636336373363833639336403364133642336433364433645336463364733648336493365033651336523365333654336553365633657336583365933660336613366233663336643366533666336673366833669336703367133672336733367433675336763367733678336793368033681336823368333684336853368633687336883368933690336913369233693336943369533696336973369833699337003370133702337033370433705337063370733708337093371033711337123371333714337153371633717337183371933720337213372233723337243372533726337273372833729337303373133732337333373433735337363373733738337393374033741337423374333744337453374633747337483374933750337513375233753337543375533756337573375833759337603376133762337633376433765337663376733768337693377033771337723377333774337753377633777337783377933780337813378233783337843378533786337873378833789337903379133792337933379433795337963379733798337993380033801338023380333804338053380633807338083380933810338113381233813338143381533816338173381833819338203382133822338233382433825338263382733828338293383033831338323383333834338353383633837338383383933840338413384233843338443384533846338473384833849338503385133852338533385433855338563385733858338593386033861338623386333864338653386633867338683386933870338713387233873338743387533876338773387833879338803388133882338833388433885338863388733888338893389033891338923389333894338953389633897338983389933900339013390233903339043390533906339073390833909339103391133912339133391433915339163391733918339193392033921339223392333924339253392633927339283392933930339313393233933339343393533936339373393833939339403394133942339433394433945339463394733948339493395033951339523395333954339553395633957339583395933960339613396233963339643396533966339673396833969339703397133972339733397433975339763397733978339793398033981339823398333984339853398633987339883398933990339913399233993339943399533996339973399833999340003400134002340033400434005340063400734008340093401034011340123401334014340153401634017340183401934020340213402234023340243402534026340273402834029340303403134032340333403434035340363403734038340393404034041340423404334044340453404634047340483404934050340513405234053340543405534056340573405834059340603406134062340633406434065340663406734068340693407034071340723407334074340753407634077340783407934080340813408234083340843408534086340873408834089340903409134092340933409434095340963409734098340993410034101341023410334104341053410634107341083410934110341113411234113341143411534116341173411834119341203412134122341233412434125341263412734128341293413034131341323413334134341353413634137341383413934140341413414234143341443414534146341473414834149341503415134152341533415434155341563415734158341593416034161341623416334164341653416634167341683416934170341713417234173341743417534176341773417834179341803418134182341833418434185341863418734188341893419034191341923419334194341953419634197341983419934200342013420234203342043420534206342073420834209342103421134212342133421434215342163421734218342193422034221342223422334224342253422634227342283422934230342313423234233342343423534236342373423834239342403424134242342433424434245342463424734248342493425034251342523425334254342553425634257342583425934260342613426234263342643426534266342673426834269342703427134272342733427434275342763427734278342793428034281342823428334284342853428634287342883428934290342913429234293342943429534296342973429834299343003430134302343033430434305343063430734308343093431034311343123431334314343153431634317343183431934320343213432234323343243432534326343273432834329343303433134332343333433434335343363433734338343393434034341343423434334344343453434634347343483434934350343513435234353343543435534356343573435834359343603436134362343633436434365343663436734368343693437034371343723437334374343753437634377343783437934380343813438234383343843438534386343873438834389343903439134392343933439434395343963439734398343993440034401344023440334404344053440634407344083440934410344113441234413344143441534416344173441834419344203442134422344233442434425344263442734428344293443034431344323443334434344353443634437344383443934440344413444234443344443444534446344473444834449344503445134452344533445434455344563445734458344593446034461344623446334464344653446634467344683446934470344713447234473344743447534476344773447834479344803448134482344833448434485344863448734488344893449034491344923449334494344953449634497344983449934500345013450234503345043450534506345073450834509345103451134512345133451434515345163451734518345193452034521345223452334524345253452634527345283452934530345313453234533345343453534536345373453834539345403454134542345433454434545345463454734548345493455034551345523455334554345553455634557345583455934560345613456234563345643456534566345673456834569345703457134572345733457434575345763457734578345793458034581345823458334584345853458634587345883458934590345913459234593345943459534596345973459834599346003460134602346033460434605346063460734608346093461034611346123461334614346153461634617346183461934620346213462234623346243462534626346273462834629346303463134632346333463434635346363463734638346393464034641346423464334644346453464634647346483464934650346513465234653346543465534656346573465834659346603466134662346633466434665346663466734668346693467034671346723467334674346753467634677346783467934680346813468234683346843468534686346873468834689346903469134692346933469434695346963469734698346993470034701347023470334704347053470634707347083470934710347113471234713347143471534716347173471834719347203472134722347233472434725347263472734728347293473034731347323473334734347353473634737347383473934740347413474234743347443474534746347473474834749347503475134752347533475434755347563475734758347593476034761347623476334764347653476634767347683476934770347713477234773347743477534776347773477834779347803478134782347833478434785347863478734788347893479034791347923479334794347953479634797347983479934800348013480234803348043480534806348073480834809348103481134812348133481434815348163481734818348193482034821348223482334824348253482634827348283482934830348313483234833348343483534836348373483834839348403484134842348433484434845348463484734848348493485034851348523485334854348553485634857348583485934860348613486234863348643486534866348673486834869348703487134872348733487434875348763487734878348793488034881348823488334884348853488634887348883488934890348913489234893348943489534896348973489834899349003490134902349033490434905349063490734908349093491034911349123491334914349153491634917349183491934920349213492234923349243492534926349273492834929349303493134932349333493434935349363493734938349393494034941349423494334944349453494634947349483494934950349513495234953349543495534956349573495834959349603496134962349633496434965349663496734968349693497034971349723497334974349753497634977349783497934980349813498234983349843498534986349873498834989349903499134992349933499434995349963499734998349993500035001350023500335004350053500635007350083500935010350113501235013350143501535016350173501835019350203502135022350233502435025350263502735028350293503035031350323503335034350353503635037350383503935040350413504235043350443504535046350473504835049350503505135052350533505435055350563505735058350593506035061350623506335064350653506635067350683506935070350713507235073350743507535076350773507835079350803508135082350833508435085350863508735088350893509035091350923509335094350953509635097350983509935100351013510235103351043510535106351073510835109351103511135112351133511435115351163511735118351193512035121351223512335124351253512635127351283512935130351313513235133351343513535136351373513835139351403514135142351433514435145351463514735148351493515035151351523515335154351553515635157351583515935160351613516235163351643516535166351673516835169351703517135172351733517435175351763517735178351793518035181351823518335184351853518635187351883518935190351913519235193351943519535196351973519835199352003520135202352033520435205352063520735208352093521035211352123521335214352153521635217352183521935220352213522235223352243522535226352273522835229352303523135232352333523435235352363523735238352393524035241352423524335244352453524635247352483524935250352513525235253352543525535256352573525835259352603526135262352633526435265352663526735268352693527035271352723527335274352753527635277352783527935280352813528235283352843528535286352873528835289352903529135292352933529435295352963529735298352993530035301353023530335304353053530635307353083530935310353113531235313353143531535316353173531835319353203532135322353233532435325353263532735328353293533035331353323533335334353353533635337353383533935340353413534235343353443534535346353473534835349353503535135352353533535435355353563535735358353593536035361353623536335364353653536635367353683536935370353713537235373353743537535376353773537835379353803538135382353833538435385353863538735388353893539035391353923539335394353953539635397353983539935400354013540235403354043540535406354073540835409354103541135412354133541435415354163541735418354193542035421354223542335424354253542635427354283542935430354313543235433354343543535436354373543835439354403544135442354433544435445354463544735448354493545035451354523545335454354553545635457354583545935460354613546235463354643546535466354673546835469354703547135472354733547435475354763547735478354793548035481354823548335484354853548635487354883548935490354913549235493354943549535496354973549835499355003550135502355033550435505355063550735508355093551035511355123551335514355153551635517355183551935520355213552235523355243552535526355273552835529355303553135532355333553435535355363553735538355393554035541355423554335544355453554635547355483554935550355513555235553355543555535556355573555835559355603556135562355633556435565355663556735568355693557035571355723557335574355753557635577355783557935580355813558235583355843558535586355873558835589355903559135592355933559435595355963559735598355993560035601356023560335604356053560635607356083560935610356113561235613356143561535616356173561835619356203562135622356233562435625356263562735628356293563035631356323563335634356353563635637356383563935640356413564235643356443564535646356473564835649356503565135652356533565435655356563565735658356593566035661356623566335664356653566635667356683566935670356713567235673356743567535676356773567835679356803568135682356833568435685356863568735688356893569035691356923569335694356953569635697356983569935700357013570235703357043570535706357073570835709357103571135712357133571435715357163571735718357193572035721357223572335724357253572635727357283572935730357313573235733357343573535736357373573835739357403574135742357433574435745357463574735748357493575035751357523575335754357553575635757357583575935760357613576235763357643576535766357673576835769357703577135772357733577435775357763577735778357793578035781357823578335784357853578635787357883578935790357913579235793357943579535796357973579835799358003580135802358033580435805358063580735808358093581035811358123581335814358153581635817358183581935820358213582235823358243582535826358273582835829358303583135832358333583435835358363583735838358393584035841358423584335844358453584635847358483584935850358513585235853358543585535856358573585835859358603586135862358633586435865358663586735868358693587035871358723587335874358753587635877358783587935880358813588235883358843588535886358873588835889358903589135892358933589435895358963589735898358993590035901359023590335904359053590635907359083590935910359113591235913359143591535916359173591835919359203592135922359233592435925359263592735928359293593035931359323593335934359353593635937359383593935940359413594235943359443594535946359473594835949359503595135952359533595435955359563595735958359593596035961359623596335964359653596635967359683596935970359713597235973359743597535976359773597835979359803598135982359833598435985359863598735988359893599035991359923599335994359953599635997359983599936000360013600236003360043600536006360073600836009360103601136012360133601436015360163601736018360193602036021360223602336024360253602636027360283602936030360313603236033360343603536036360373603836039360403604136042360433604436045360463604736048360493605036051360523605336054360553605636057360583605936060360613606236063360643606536066360673606836069360703607136072360733607436075360763607736078360793608036081360823608336084360853608636087360883608936090360913609236093360943609536096360973609836099361003610136102361033610436105361063610736108361093611036111361123611336114361153611636117361183611936120361213612236123361243612536126361273612836129361303613136132361333613436135361363613736138361393614036141361423614336144361453614636147361483614936150361513615236153361543615536156361573615836159361603616136162361633616436165361663616736168361693617036171361723617336174361753617636177361783617936180361813618236183361843618536186361873618836189361903619136192361933619436195361963619736198361993620036201362023620336204362053620636207362083620936210362113621236213362143621536216362173621836219362203622136222362233622436225362263622736228362293623036231362323623336234362353623636237362383623936240362413624236243362443624536246362473624836249362503625136252362533625436255362563625736258362593626036261362623626336264362653626636267362683626936270362713627236273362743627536276362773627836279362803628136282362833628436285362863628736288362893629036291362923629336294362953629636297362983629936300363013630236303363043630536306363073630836309363103631136312363133631436315363163631736318363193632036321363223632336324363253632636327363283632936330363313633236333363343633536336363373633836339363403634136342363433634436345363463634736348363493635036351363523635336354363553635636357363583635936360363613636236363363643636536366363673636836369363703637136372363733637436375363763637736378363793638036381363823638336384363853638636387363883638936390363913639236393363943639536396363973639836399364003640136402364033640436405364063640736408364093641036411364123641336414364153641636417364183641936420364213642236423364243642536426364273642836429364303643136432364333643436435364363643736438364393644036441364423644336444364453644636447364483644936450364513645236453364543645536456364573645836459364603646136462364633646436465364663646736468364693647036471364723647336474364753647636477364783647936480364813648236483364843648536486364873648836489364903649136492364933649436495364963649736498364993650036501365023650336504365053650636507365083650936510365113651236513365143651536516365173651836519365203652136522365233652436525365263652736528365293653036531365323653336534365353653636537365383653936540365413654236543365443654536546365473654836549365503655136552365533655436555365563655736558365593656036561365623656336564365653656636567365683656936570365713657236573365743657536576365773657836579365803658136582365833658436585365863658736588365893659036591365923659336594365953659636597365983659936600366013660236603366043660536606366073660836609366103661136612366133661436615366163661736618366193662036621366223662336624366253662636627366283662936630366313663236633366343663536636366373663836639366403664136642366433664436645366463664736648366493665036651366523665336654366553665636657366583665936660366613666236663366643666536666366673666836669366703667136672366733667436675366763667736678366793668036681366823668336684366853668636687366883668936690366913669236693366943669536696366973669836699367003670136702367033670436705367063670736708367093671036711367123671336714367153671636717367183671936720367213672236723367243672536726367273672836729367303673136732367333673436735367363673736738367393674036741367423674336744367453674636747367483674936750367513675236753367543675536756367573675836759367603676136762367633676436765367663676736768367693677036771367723677336774367753677636777367783677936780367813678236783367843678536786367873678836789367903679136792367933679436795367963679736798367993680036801368023680336804368053680636807368083680936810368113681236813368143681536816368173681836819368203682136822368233682436825368263682736828368293683036831368323683336834368353683636837368383683936840368413684236843368443684536846368473684836849368503685136852368533685436855368563685736858368593686036861368623686336864368653686636867368683686936870368713687236873368743687536876368773687836879368803688136882368833688436885368863688736888368893689036891368923689336894368953689636897368983689936900369013690236903369043690536906369073690836909369103691136912369133691436915369163691736918369193692036921369223692336924369253692636927369283692936930369313693236933369343693536936369373693836939369403694136942369433694436945369463694736948369493695036951369523695336954369553695636957369583695936960369613696236963369643696536966369673696836969369703697136972369733697436975369763697736978369793698036981369823698336984369853698636987369883698936990369913699236993369943699536996369973699836999370003700137002370033700437005370063700737008370093701037011370123701337014370153701637017370183701937020370213702237023370243702537026370273702837029370303703137032370333703437035370363703737038370393704037041370423704337044370453704637047370483704937050370513705237053370543705537056370573705837059370603706137062370633706437065370663706737068370693707037071370723707337074370753707637077370783707937080370813708237083370843708537086370873708837089370903709137092370933709437095370963709737098370993710037101371023710337104371053710637107371083710937110371113711237113371143711537116371173711837119371203712137122371233712437125371263712737128371293713037131371323713337134371353713637137371383713937140371413714237143371443714537146371473714837149371503715137152371533715437155371563715737158371593716037161371623716337164371653716637167371683716937170371713717237173371743717537176371773717837179371803718137182371833718437185371863718737188371893719037191371923719337194371953719637197371983719937200372013720237203372043720537206372073720837209372103721137212372133721437215372163721737218372193722037221372223722337224372253722637227372283722937230372313723237233372343723537236372373723837239372403724137242372433724437245372463724737248372493725037251372523725337254372553725637257372583725937260372613726237263372643726537266372673726837269372703727137272372733727437275372763727737278372793728037281372823728337284372853728637287372883728937290372913729237293372943729537296372973729837299373003730137302373033730437305373063730737308373093731037311373123731337314373153731637317373183731937320373213732237323373243732537326373273732837329373303733137332373333733437335373363733737338373393734037341373423734337344373453734637347373483734937350373513735237353373543735537356373573735837359373603736137362373633736437365373663736737368373693737037371373723737337374373753737637377373783737937380373813738237383373843738537386373873738837389373903739137392373933739437395373963739737398373993740037401374023740337404374053740637407374083740937410374113741237413374143741537416374173741837419374203742137422374233742437425374263742737428374293743037431374323743337434374353743637437374383743937440374413744237443374443744537446374473744837449374503745137452374533745437455374563745737458374593746037461374623746337464374653746637467374683746937470374713747237473374743747537476374773747837479374803748137482374833748437485374863748737488374893749037491374923749337494374953749637497374983749937500375013750237503375043750537506375073750837509375103751137512375133751437515375163751737518375193752037521375223752337524375253752637527375283752937530375313753237533375343753537536375373753837539375403754137542375433754437545375463754737548375493755037551375523755337554375553755637557375583755937560375613756237563375643756537566375673756837569375703757137572375733757437575375763757737578375793758037581375823758337584375853758637587375883758937590375913759237593375943759537596375973759837599376003760137602376033760437605376063760737608376093761037611376123761337614376153761637617376183761937620376213762237623376243762537626376273762837629376303763137632376333763437635376363763737638376393764037641376423764337644376453764637647376483764937650376513765237653376543765537656376573765837659376603766137662376633766437665376663766737668376693767037671376723767337674376753767637677376783767937680376813768237683376843768537686376873768837689376903769137692376933769437695376963769737698376993770037701377023770337704377053770637707377083770937710377113771237713377143771537716377173771837719377203772137722377233772437725377263772737728377293773037731377323773337734377353773637737377383773937740377413774237743377443774537746377473774837749377503775137752377533775437755377563775737758377593776037761377623776337764377653776637767377683776937770377713777237773377743777537776377773777837779377803778137782377833778437785377863778737788377893779037791377923779337794377953779637797377983779937800378013780237803378043780537806378073780837809378103781137812378133781437815378163781737818378193782037821378223782337824378253782637827378283782937830378313783237833378343783537836378373783837839378403784137842378433784437845378463784737848378493785037851378523785337854378553785637857378583785937860378613786237863378643786537866378673786837869378703787137872378733787437875378763787737878378793788037881378823788337884378853788637887378883788937890378913789237893378943789537896378973789837899379003790137902379033790437905379063790737908379093791037911379123791337914379153791637917379183791937920379213792237923379243792537926379273792837929379303793137932379333793437935379363793737938379393794037941379423794337944379453794637947379483794937950379513795237953379543795537956379573795837959379603796137962379633796437965379663796737968379693797037971379723797337974379753797637977379783797937980379813798237983379843798537986379873798837989379903799137992379933799437995379963799737998379993800038001380023800338004380053800638007380083800938010380113801238013380143801538016380173801838019380203802138022380233802438025380263802738028380293803038031380323803338034380353803638037380383803938040380413804238043380443804538046380473804838049380503805138052380533805438055380563805738058380593806038061380623806338064380653806638067380683806938070380713807238073380743807538076380773807838079380803808138082380833808438085380863808738088380893809038091380923809338094380953809638097380983809938100381013810238103381043810538106381073810838109381103811138112381133811438115381163811738118381193812038121381223812338124381253812638127381283812938130381313813238133381343813538136381373813838139381403814138142381433814438145381463814738148381493815038151381523815338154381553815638157381583815938160381613816238163381643816538166381673816838169381703817138172381733817438175381763817738178381793818038181381823818338184381853818638187381883818938190381913819238193381943819538196381973819838199382003820138202382033820438205382063820738208382093821038211382123821338214382153821638217382183821938220382213822238223382243822538226382273822838229382303823138232382333823438235382363823738238382393824038241382423824338244382453824638247382483824938250382513825238253382543825538256382573825838259382603826138262382633826438265382663826738268382693827038271382723827338274382753827638277382783827938280382813828238283382843828538286382873828838289382903829138292382933829438295382963829738298382993830038301383023830338304383053830638307383083830938310383113831238313383143831538316383173831838319383203832138322383233832438325383263832738328383293833038331383323833338334383353833638337383383833938340383413834238343383443834538346383473834838349383503835138352383533835438355383563835738358383593836038361383623836338364383653836638367383683836938370383713837238373383743837538376383773837838379383803838138382383833838438385383863838738388383893839038391383923839338394383953839638397383983839938400384013840238403384043840538406384073840838409384103841138412384133841438415384163841738418384193842038421384223842338424384253842638427384283842938430384313843238433384343843538436384373843838439384403844138442384433844438445384463844738448384493845038451384523845338454384553845638457384583845938460384613846238463384643846538466384673846838469384703847138472384733847438475384763847738478384793848038481384823848338484384853848638487384883848938490384913849238493384943849538496384973849838499385003850138502385033850438505385063850738508385093851038511385123851338514385153851638517385183851938520385213852238523385243852538526385273852838529385303853138532385333853438535385363853738538385393854038541385423854338544385453854638547385483854938550385513855238553385543855538556385573855838559385603856138562385633856438565385663856738568385693857038571385723857338574385753857638577385783857938580385813858238583385843858538586385873858838589385903859138592385933859438595385963859738598385993860038601386023860338604386053860638607386083860938610386113861238613386143861538616386173861838619386203862138622386233862438625386263862738628386293863038631386323863338634386353863638637386383863938640386413864238643386443864538646386473864838649386503865138652386533865438655386563865738658386593866038661386623866338664386653866638667386683866938670386713867238673386743867538676386773867838679386803868138682386833868438685386863868738688386893869038691386923869338694386953869638697386983869938700387013870238703387043870538706387073870838709387103871138712387133871438715387163871738718387193872038721387223872338724387253872638727387283872938730387313873238733387343873538736387373873838739387403874138742387433874438745387463874738748387493875038751387523875338754387553875638757387583875938760387613876238763387643876538766387673876838769387703877138772387733877438775387763877738778387793878038781387823878338784387853878638787387883878938790387913879238793387943879538796387973879838799388003880138802388033880438805388063880738808388093881038811388123881338814388153881638817388183881938820388213882238823388243882538826388273882838829388303883138832388333883438835388363883738838388393884038841388423884338844388453884638847388483884938850388513885238853388543885538856388573885838859388603886138862388633886438865388663886738868388693887038871388723887338874388753887638877388783887938880388813888238883388843888538886388873888838889388903889138892388933889438895388963889738898388993890038901389023890338904389053890638907389083890938910389113891238913389143891538916389173891838919389203892138922389233892438925389263892738928389293893038931389323893338934389353893638937389383893938940389413894238943389443894538946389473894838949389503895138952389533895438955389563895738958389593896038961389623896338964389653896638967389683896938970389713897238973389743897538976389773897838979389803898138982389833898438985389863898738988389893899038991389923899338994389953899638997389983899939000390013900239003390043900539006390073900839009390103901139012390133901439015390163901739018390193902039021390223902339024390253902639027390283902939030390313903239033390343903539036390373903839039390403904139042390433904439045390463904739048390493905039051390523905339054390553905639057390583905939060390613906239063390643906539066390673906839069390703907139072390733907439075390763907739078390793908039081390823908339084390853908639087390883908939090390913909239093390943909539096390973909839099391003910139102391033910439105391063910739108391093911039111391123911339114391153911639117391183911939120391213912239123391243912539126391273912839129391303913139132391333913439135391363913739138391393914039141391423914339144391453914639147391483914939150391513915239153391543915539156391573915839159391603916139162391633916439165391663916739168391693917039171391723917339174391753917639177391783917939180391813918239183391843918539186391873918839189391903919139192391933919439195391963919739198391993920039201392023920339204392053920639207392083920939210392113921239213392143921539216392173921839219392203922139222392233922439225392263922739228392293923039231392323923339234392353923639237392383923939240392413924239243392443924539246392473924839249392503925139252392533925439255392563925739258392593926039261392623926339264392653926639267392683926939270392713927239273392743927539276392773927839279392803928139282392833928439285392863928739288392893929039291392923929339294392953929639297392983929939300393013930239303393043930539306393073930839309393103931139312393133931439315393163931739318393193932039321393223932339324393253932639327393283932939330393313933239333393343933539336393373933839339393403934139342393433934439345393463934739348393493935039351393523935339354393553935639357393583935939360393613936239363393643936539366393673936839369393703937139372393733937439375393763937739378393793938039381393823938339384393853938639387393883938939390393913939239393393943939539396393973939839399394003940139402394033940439405394063940739408394093941039411394123941339414394153941639417394183941939420394213942239423394243942539426394273942839429394303943139432394333943439435394363943739438394393944039441394423944339444394453944639447394483944939450394513945239453394543945539456394573945839459394603946139462394633946439465394663946739468394693947039471394723947339474394753947639477394783947939480394813948239483394843948539486394873948839489394903949139492394933949439495394963949739498394993950039501395023950339504395053950639507395083950939510395113951239513395143951539516395173951839519395203952139522395233952439525395263952739528395293953039531395323953339534395353953639537395383953939540395413954239543395443954539546395473954839549395503955139552395533955439555395563955739558395593956039561395623956339564395653956639567395683956939570395713957239573395743957539576395773957839579395803958139582395833958439585395863958739588395893959039591395923959339594395953959639597395983959939600396013960239603396043960539606396073960839609396103961139612396133961439615396163961739618396193962039621396223962339624396253962639627396283962939630396313963239633396343963539636396373963839639396403964139642396433964439645396463964739648396493965039651396523965339654396553965639657396583965939660396613966239663396643966539666396673966839669396703967139672396733967439675396763967739678396793968039681396823968339684396853968639687396883968939690396913969239693396943969539696396973969839699397003970139702397033970439705397063970739708397093971039711397123971339714397153971639717397183971939720397213972239723397243972539726397273972839729397303973139732397333973439735397363973739738397393974039741397423974339744397453974639747397483974939750397513975239753397543975539756397573975839759397603976139762397633976439765397663976739768397693977039771397723977339774397753977639777397783977939780397813978239783397843978539786397873978839789397903979139792397933979439795397963979739798397993980039801398023980339804398053980639807398083980939810398113981239813398143981539816398173981839819398203982139822398233982439825398263982739828398293983039831398323983339834398353983639837398383983939840398413984239843398443984539846398473984839849398503985139852398533985439855398563985739858398593986039861398623986339864398653986639867398683986939870398713987239873398743987539876398773987839879398803988139882398833988439885398863988739888398893989039891398923989339894398953989639897398983989939900399013990239903399043990539906399073990839909399103991139912399133991439915399163991739918399193992039921399223992339924399253992639927399283992939930399313993239933399343993539936399373993839939399403994139942399433994439945399463994739948399493995039951399523995339954399553995639957399583995939960399613996239963399643996539966399673996839969399703997139972399733997439975399763997739978399793998039981399823998339984399853998639987399883998939990399913999239993399943999539996399973999839999400004000140002400034000440005400064000740008400094001040011400124001340014400154001640017400184001940020400214002240023400244002540026400274002840029400304003140032400334003440035400364003740038400394004040041400424004340044400454004640047400484004940050400514005240053400544005540056400574005840059400604006140062400634006440065400664006740068400694007040071400724007340074400754007640077400784007940080400814008240083400844008540086400874008840089400904009140092400934009440095400964009740098400994010040101401024010340104401054010640107401084010940110401114011240113401144011540116401174011840119401204012140122401234012440125401264012740128401294013040131401324013340134401354013640137401384013940140401414014240143401444014540146401474014840149401504015140152401534015440155401564015740158401594016040161401624016340164401654016640167401684016940170401714017240173401744017540176401774017840179401804018140182401834018440185401864018740188401894019040191401924019340194401954019640197401984019940200402014020240203402044020540206402074020840209402104021140212402134021440215402164021740218402194022040221402224022340224402254022640227402284022940230402314023240233402344023540236402374023840239402404024140242402434024440245402464024740248402494025040251402524025340254402554025640257402584025940260402614026240263402644026540266402674026840269402704027140272402734027440275402764027740278402794028040281402824028340284402854028640287402884028940290402914029240293402944029540296402974029840299403004030140302403034030440305403064030740308403094031040311403124031340314403154031640317403184031940320403214032240323403244032540326403274032840329403304033140332403334033440335403364033740338403394034040341403424034340344403454034640347403484034940350403514035240353403544035540356403574035840359403604036140362403634036440365403664036740368403694037040371403724037340374403754037640377403784037940380403814038240383403844038540386403874038840389403904039140392403934039440395403964039740398403994040040401404024040340404404054040640407404084040940410404114041240413404144041540416404174041840419404204042140422404234042440425404264042740428404294043040431404324043340434404354043640437404384043940440404414044240443404444044540446404474044840449404504045140452404534045440455404564045740458404594046040461404624046340464404654046640467404684046940470404714047240473404744047540476404774047840479404804048140482404834048440485404864048740488404894049040491404924049340494404954049640497404984049940500405014050240503405044050540506405074050840509405104051140512405134051440515405164051740518405194052040521405224052340524405254052640527405284052940530405314053240533405344053540536405374053840539405404054140542405434054440545405464054740548405494055040551405524055340554405554055640557405584055940560405614056240563405644056540566405674056840569405704057140572405734057440575405764057740578405794058040581405824058340584405854058640587405884058940590405914059240593405944059540596405974059840599406004060140602406034060440605406064060740608406094061040611406124061340614406154061640617406184061940620406214062240623406244062540626406274062840629406304063140632406334063440635406364063740638406394064040641406424064340644406454064640647406484064940650406514065240653406544065540656406574065840659406604066140662406634066440665406664066740668406694067040671406724067340674406754067640677406784067940680406814068240683406844068540686406874068840689406904069140692406934069440695406964069740698406994070040701407024070340704407054070640707407084070940710407114071240713407144071540716407174071840719407204072140722407234072440725407264072740728407294073040731407324073340734407354073640737407384073940740407414074240743407444074540746407474074840749407504075140752407534075440755407564075740758407594076040761407624076340764407654076640767407684076940770407714077240773407744077540776407774077840779407804078140782407834078440785407864078740788407894079040791407924079340794407954079640797407984079940800408014080240803408044080540806408074080840809408104081140812408134081440815408164081740818408194082040821408224082340824408254082640827408284082940830408314083240833408344083540836408374083840839408404084140842408434084440845408464084740848408494085040851408524085340854408554085640857408584085940860408614086240863408644086540866408674086840869408704087140872408734087440875408764087740878408794088040881408824088340884408854088640887408884088940890408914089240893408944089540896408974089840899409004090140902409034090440905409064090740908409094091040911409124091340914409154091640917409184091940920409214092240923409244092540926409274092840929409304093140932409334093440935409364093740938409394094040941409424094340944409454094640947409484094940950409514095240953409544095540956409574095840959409604096140962409634096440965409664096740968409694097040971409724097340974409754097640977409784097940980409814098240983409844098540986409874098840989409904099140992409934099440995409964099740998409994100041001410024100341004410054100641007410084100941010410114101241013410144101541016410174101841019410204102141022410234102441025410264102741028410294103041031410324103341034410354103641037410384103941040410414104241043410444104541046410474104841049410504105141052410534105441055410564105741058410594106041061410624106341064410654106641067410684106941070410714107241073410744107541076410774107841079410804108141082410834108441085410864108741088410894109041091410924109341094410954109641097410984109941100411014110241103411044110541106411074110841109411104111141112411134111441115411164111741118411194112041121411224112341124411254112641127411284112941130411314113241133411344113541136411374113841139411404114141142411434114441145411464114741148411494115041151411524115341154411554115641157411584115941160411614116241163411644116541166411674116841169411704117141172411734117441175411764117741178411794118041181411824118341184411854118641187411884118941190411914119241193411944119541196411974119841199412004120141202412034120441205412064120741208412094121041211412124121341214412154121641217412184121941220412214122241223412244122541226412274122841229412304123141232412334123441235412364123741238412394124041241412424124341244412454124641247412484124941250412514125241253412544125541256412574125841259412604126141262412634126441265412664126741268412694127041271412724127341274412754127641277412784127941280412814128241283412844128541286412874128841289412904129141292412934129441295412964129741298412994130041301413024130341304413054130641307413084130941310413114131241313413144131541316413174131841319413204132141322413234132441325413264132741328413294133041331413324133341334413354133641337413384133941340413414134241343413444134541346413474134841349413504135141352413534135441355413564135741358413594136041361413624136341364413654136641367413684136941370413714137241373413744137541376413774137841379413804138141382413834138441385413864138741388413894139041391413924139341394413954139641397413984139941400414014140241403414044140541406414074140841409414104141141412414134141441415414164141741418414194142041421414224142341424414254142641427414284142941430414314143241433414344143541436414374143841439414404144141442414434144441445414464144741448414494145041451414524145341454414554145641457414584145941460414614146241463414644146541466414674146841469414704147141472414734147441475414764147741478414794148041481414824148341484414854148641487414884148941490414914149241493414944149541496414974149841499415004150141502415034150441505415064150741508415094151041511415124151341514415154151641517415184151941520415214152241523415244152541526415274152841529415304153141532415334153441535415364153741538415394154041541415424154341544415454154641547415484154941550415514155241553415544155541556415574155841559415604156141562415634156441565415664156741568415694157041571415724157341574415754157641577415784157941580415814158241583415844158541586415874158841589415904159141592415934159441595415964159741598415994160041601416024160341604416054160641607416084160941610416114161241613416144161541616416174161841619416204162141622416234162441625416264162741628416294163041631416324163341634416354163641637416384163941640416414164241643416444164541646416474164841649416504165141652416534165441655416564165741658416594166041661416624166341664416654166641667416684166941670416714167241673416744167541676416774167841679416804168141682416834168441685416864168741688416894169041691416924169341694416954169641697416984169941700417014170241703417044170541706417074170841709417104171141712417134171441715417164171741718417194172041721417224172341724417254172641727417284172941730417314173241733417344173541736417374173841739417404174141742417434174441745417464174741748417494175041751417524175341754417554175641757417584175941760417614176241763417644176541766417674176841769417704177141772417734177441775417764177741778417794178041781417824178341784417854178641787417884178941790417914179241793417944179541796417974179841799418004180141802418034180441805418064180741808418094181041811418124181341814418154181641817418184181941820418214182241823418244182541826418274182841829418304183141832418334183441835418364183741838418394184041841418424184341844418454184641847418484184941850418514185241853418544185541856418574185841859418604186141862418634186441865418664186741868418694187041871418724187341874418754187641877418784187941880418814188241883418844188541886418874188841889418904189141892418934189441895418964189741898418994190041901419024190341904419054190641907419084190941910419114191241913419144191541916419174191841919419204192141922419234192441925419264192741928419294193041931419324193341934419354193641937419384193941940419414194241943419444194541946419474194841949419504195141952419534195441955419564195741958419594196041961419624196341964419654196641967419684196941970419714197241973419744197541976419774197841979419804198141982419834198441985419864198741988419894199041991419924199341994419954199641997419984199942000420014200242003420044200542006420074200842009420104201142012420134201442015420164201742018420194202042021420224202342024420254202642027420284202942030420314203242033420344203542036420374203842039420404204142042420434204442045420464204742048420494205042051420524205342054420554205642057420584205942060420614206242063420644206542066420674206842069420704207142072420734207442075420764207742078420794208042081420824208342084420854208642087420884208942090420914209242093420944209542096420974209842099421004210142102421034210442105421064210742108421094211042111421124211342114421154211642117421184211942120421214212242123421244212542126421274212842129421304213142132421334213442135421364213742138421394214042141421424214342144421454214642147421484214942150421514215242153421544215542156421574215842159421604216142162421634216442165421664216742168421694217042171421724217342174421754217642177421784217942180421814218242183421844218542186421874218842189421904219142192421934219442195421964219742198421994220042201422024220342204422054220642207422084220942210422114221242213422144221542216422174221842219422204222142222422234222442225422264222742228422294223042231422324223342234422354223642237422384223942240422414224242243422444224542246422474224842249422504225142252422534225442255422564225742258422594226042261422624226342264422654226642267422684226942270422714227242273422744227542276422774227842279422804228142282422834228442285422864228742288422894229042291422924229342294422954229642297422984229942300423014230242303423044230542306423074230842309423104231142312423134231442315423164231742318423194232042321423224232342324423254232642327423284232942330423314233242333423344233542336423374233842339423404234142342423434234442345423464234742348423494235042351423524235342354423554235642357423584235942360423614236242363423644236542366423674236842369423704237142372423734237442375423764237742378423794238042381423824238342384423854238642387423884238942390423914239242393423944239542396423974239842399424004240142402424034240442405424064240742408424094241042411424124241342414424154241642417424184241942420424214242242423424244242542426424274242842429424304243142432424334243442435424364243742438424394244042441424424244342444424454244642447424484244942450424514245242453424544245542456424574245842459424604246142462424634246442465424664246742468424694247042471424724247342474424754247642477424784247942480424814248242483424844248542486424874248842489424904249142492424934249442495424964249742498424994250042501425024250342504425054250642507425084250942510425114251242513425144251542516425174251842519425204252142522425234252442525425264252742528425294253042531425324253342534425354253642537425384253942540425414254242543425444254542546425474254842549425504255142552425534255442555425564255742558425594256042561425624256342564425654256642567425684256942570425714257242573425744257542576425774257842579425804258142582425834258442585425864258742588425894259042591425924259342594425954259642597425984259942600426014260242603426044260542606426074260842609426104261142612426134261442615426164261742618426194262042621426224262342624426254262642627426284262942630426314263242633426344263542636426374263842639426404264142642426434264442645426464264742648426494265042651426524265342654426554265642657426584265942660426614266242663426644266542666426674266842669426704267142672426734267442675426764267742678426794268042681426824268342684426854268642687426884268942690426914269242693426944269542696426974269842699427004270142702427034270442705427064270742708427094271042711427124271342714427154271642717427184271942720427214272242723427244272542726427274272842729427304273142732427334273442735427364273742738427394274042741427424274342744427454274642747427484274942750427514275242753427544275542756427574275842759427604276142762427634276442765427664276742768427694277042771427724277342774427754277642777427784277942780427814278242783427844278542786427874278842789427904279142792427934279442795427964279742798427994280042801428024280342804428054280642807428084280942810428114281242813428144281542816428174281842819428204282142822428234282442825428264282742828428294283042831428324283342834428354283642837428384283942840428414284242843428444284542846428474284842849428504285142852428534285442855428564285742858428594286042861428624286342864428654286642867428684286942870428714287242873428744287542876428774287842879428804288142882428834288442885428864288742888428894289042891428924289342894428954289642897428984289942900429014290242903429044290542906429074290842909429104291142912429134291442915429164291742918429194292042921429224292342924429254292642927429284292942930429314293242933429344293542936429374293842939429404294142942429434294442945429464294742948429494295042951429524295342954429554295642957429584295942960429614296242963429644296542966429674296842969429704297142972429734297442975429764297742978429794298042981429824298342984429854298642987429884298942990429914299242993429944299542996429974299842999430004300143002430034300443005430064300743008430094301043011430124301343014430154301643017430184301943020430214302243023430244302543026430274302843029430304303143032430334303443035430364303743038430394304043041430424304343044430454304643047430484304943050430514305243053430544305543056430574305843059430604306143062430634306443065430664306743068430694307043071430724307343074430754307643077430784307943080430814308243083430844308543086430874308843089430904309143092430934309443095430964309743098430994310043101431024310343104431054310643107431084310943110431114311243113431144311543116431174311843119431204312143122431234312443125431264312743128431294313043131431324313343134431354313643137431384313943140431414314243143431444314543146431474314843149431504315143152431534315443155431564315743158431594316043161431624316343164431654316643167431684316943170431714317243173431744317543176431774317843179431804318143182431834318443185431864318743188431894319043191431924319343194431954319643197431984319943200432014320243203432044320543206432074320843209432104321143212432134321443215432164321743218432194322043221432224322343224432254322643227432284322943230432314323243233432344323543236432374323843239432404324143242432434324443245432464324743248432494325043251432524325343254432554325643257432584325943260432614326243263432644326543266432674326843269432704327143272432734327443275432764327743278432794328043281432824328343284432854328643287432884328943290432914329243293432944329543296432974329843299433004330143302433034330443305433064330743308433094331043311433124331343314433154331643317433184331943320433214332243323433244332543326433274332843329433304333143332433334333443335433364333743338433394334043341433424334343344433454334643347433484334943350433514335243353433544335543356433574335843359433604336143362433634336443365433664336743368433694337043371433724337343374433754337643377433784337943380433814338243383433844338543386433874338843389433904339143392433934339443395433964339743398433994340043401434024340343404434054340643407434084340943410434114341243413434144341543416434174341843419434204342143422434234342443425434264342743428434294343043431434324343343434434354343643437434384343943440434414344243443434444344543446434474344843449434504345143452434534345443455434564345743458434594346043461434624346343464434654346643467434684346943470434714347243473434744347543476434774347843479434804348143482434834348443485434864348743488434894349043491434924349343494434954349643497434984349943500435014350243503435044350543506435074350843509435104351143512435134351443515435164351743518435194352043521435224352343524435254352643527435284352943530435314353243533435344353543536435374353843539435404354143542435434354443545435464354743548435494355043551435524355343554435554355643557435584355943560435614356243563435644356543566435674356843569435704357143572435734357443575435764357743578435794358043581435824358343584435854358643587435884358943590435914359243593435944359543596435974359843599436004360143602436034360443605436064360743608436094361043611436124361343614436154361643617436184361943620436214362243623436244362543626436274362843629436304363143632436334363443635436364363743638436394364043641436424364343644436454364643647436484364943650436514365243653436544365543656436574365843659436604366143662436634366443665436664366743668436694367043671436724367343674436754367643677436784367943680436814368243683436844368543686436874368843689436904369143692436934369443695436964369743698436994370043701437024370343704437054370643707437084370943710437114371243713437144371543716437174371843719437204372143722437234372443725437264372743728437294373043731437324373343734437354373643737437384373943740437414374243743437444374543746437474374843749437504375143752437534375443755437564375743758437594376043761437624376343764437654376643767437684376943770437714377243773437744377543776437774377843779437804378143782437834378443785437864378743788437894379043791437924379343794437954379643797437984379943800438014380243803438044380543806438074380843809438104381143812438134381443815438164381743818438194382043821438224382343824438254382643827438284382943830438314383243833438344383543836438374383843839438404384143842438434384443845438464384743848438494385043851438524385343854438554385643857438584385943860438614386243863438644386543866438674386843869438704387143872438734387443875438764387743878438794388043881438824388343884438854388643887438884388943890438914389243893438944389543896438974389843899439004390143902439034390443905439064390743908439094391043911439124391343914439154391643917439184391943920439214392243923439244392543926439274392843929439304393143932439334393443935439364393743938439394394043941439424394343944439454394643947439484394943950439514395243953439544395543956439574395843959439604396143962439634396443965439664396743968439694397043971439724397343974439754397643977439784397943980439814398243983439844398543986439874398843989439904399143992439934399443995439964399743998439994400044001440024400344004440054400644007440084400944010440114401244013440144401544016440174401844019440204402144022440234402444025440264402744028440294403044031440324403344034440354403644037440384403944040440414404244043440444404544046440474404844049440504405144052440534405444055440564405744058440594406044061440624406344064440654406644067440684406944070440714407244073440744407544076440774407844079440804408144082440834408444085440864408744088440894409044091440924409344094440954409644097440984409944100441014410244103441044410544106441074410844109441104411144112441134411444115441164411744118441194412044121441224412344124441254412644127441284412944130441314413244133441344413544136441374413844139441404414144142441434414444145441464414744148441494415044151441524415344154441554415644157441584415944160441614416244163441644416544166441674416844169441704417144172441734417444175441764417744178441794418044181441824418344184441854418644187441884418944190441914419244193441944419544196441974419844199442004420144202442034420444205442064420744208442094421044211442124421344214442154421644217442184421944220442214422244223442244422544226442274422844229442304423144232442334423444235442364423744238442394424044241442424424344244442454424644247442484424944250442514425244253442544425544256442574425844259442604426144262442634426444265442664426744268442694427044271442724427344274442754427644277442784427944280442814428244283442844428544286442874428844289442904429144292442934429444295442964429744298442994430044301443024430344304443054430644307443084430944310443114431244313443144431544316443174431844319443204432144322443234432444325443264432744328443294433044331443324433344334443354433644337443384433944340443414434244343443444434544346443474434844349443504435144352443534435444355443564435744358443594436044361443624436344364443654436644367443684436944370443714437244373443744437544376443774437844379443804438144382443834438444385443864438744388443894439044391443924439344394443954439644397443984439944400444014440244403444044440544406444074440844409444104441144412444134441444415444164441744418444194442044421444224442344424444254442644427444284442944430444314443244433444344443544436444374443844439444404444144442444434444444445444464444744448444494445044451444524445344454444554445644457444584445944460444614446244463444644446544466444674446844469444704447144472444734447444475444764447744478444794448044481444824448344484444854448644487444884448944490444914449244493444944449544496444974449844499445004450144502445034450444505445064450744508445094451044511445124451344514445154451644517445184451944520445214452244523445244452544526445274452844529445304453144532445334453444535445364453744538445394454044541445424454344544445454454644547445484454944550445514455244553445544455544556445574455844559445604456144562445634456444565445664456744568445694457044571445724457344574445754457644577445784457944580445814458244583445844458544586445874458844589445904459144592445934459444595445964459744598445994460044601446024460344604446054460644607446084460944610446114461244613446144461544616446174461844619446204462144622446234462444625446264462744628446294463044631446324463344634446354463644637446384463944640446414464244643446444464544646446474464844649446504465144652446534465444655446564465744658446594466044661446624466344664446654466644667446684466944670446714467244673446744467544676446774467844679446804468144682446834468444685446864468744688446894469044691446924469344694446954469644697446984469944700447014470244703447044470544706447074470844709447104471144712447134471444715447164471744718447194472044721447224472344724447254472644727447284472944730447314473244733447344473544736447374473844739447404474144742447434474444745447464474744748447494475044751447524475344754447554475644757447584475944760447614476244763447644476544766447674476844769447704477144772447734477444775447764477744778447794478044781447824478344784447854478644787447884478944790447914479244793447944479544796447974479844799448004480144802448034480444805448064480744808448094481044811448124481344814448154481644817448184481944820448214482244823448244482544826448274482844829448304483144832448334483444835448364483744838448394484044841448424484344844448454484644847448484484944850448514485244853448544485544856448574485844859448604486144862448634486444865448664486744868448694487044871448724487344874448754487644877448784487944880448814488244883448844488544886448874488844889448904489144892448934489444895448964489744898448994490044901449024490344904449054490644907449084490944910449114491244913449144491544916449174491844919449204492144922449234492444925449264492744928449294493044931449324493344934449354493644937449384493944940449414494244943449444494544946449474494844949449504495144952449534495444955449564495744958449594496044961449624496344964449654496644967449684496944970449714497244973449744497544976449774497844979449804498144982449834498444985449864498744988449894499044991449924499344994449954499644997449984499945000450014500245003450044500545006450074500845009450104501145012450134501445015450164501745018450194502045021450224502345024450254502645027450284502945030450314503245033450344503545036450374503845039450404504145042450434504445045450464504745048450494505045051450524505345054450554505645057450584505945060450614506245063450644506545066450674506845069450704507145072450734507445075450764507745078450794508045081450824508345084450854508645087450884508945090450914509245093450944509545096450974509845099451004510145102451034510445105451064510745108451094511045111451124511345114451154511645117451184511945120451214512245123451244512545126451274512845129451304513145132451334513445135451364513745138451394514045141451424514345144451454514645147451484514945150451514515245153451544515545156451574515845159451604516145162451634516445165451664516745168451694517045171451724517345174451754517645177451784517945180451814518245183451844518545186451874518845189451904519145192451934519445195451964519745198451994520045201452024520345204452054520645207452084520945210452114521245213452144521545216452174521845219452204522145222452234522445225452264522745228452294523045231452324523345234452354523645237452384523945240452414524245243452444524545246452474524845249452504525145252452534525445255452564525745258452594526045261452624526345264452654526645267452684526945270452714527245273452744527545276452774527845279452804528145282452834528445285452864528745288452894529045291452924529345294452954529645297452984529945300453014530245303453044530545306453074530845309453104531145312453134531445315453164531745318453194532045321453224532345324453254532645327453284532945330453314533245333453344533545336453374533845339453404534145342453434534445345453464534745348453494535045351453524535345354453554535645357453584535945360453614536245363453644536545366453674536845369453704537145372453734537445375453764537745378453794538045381453824538345384453854538645387453884538945390453914539245393453944539545396453974539845399454004540145402454034540445405454064540745408454094541045411454124541345414454154541645417454184541945420454214542245423454244542545426454274542845429454304543145432454334543445435454364543745438454394544045441454424544345444454454544645447454484544945450454514545245453454544545545456454574545845459454604546145462454634546445465454664546745468454694547045471454724547345474454754547645477454784547945480454814548245483454844548545486454874548845489454904549145492454934549445495454964549745498454994550045501455024550345504455054550645507455084550945510455114551245513455144551545516455174551845519455204552145522455234552445525455264552745528455294553045531455324553345534455354553645537455384553945540455414554245543455444554545546455474554845549455504555145552455534555445555455564555745558455594556045561455624556345564455654556645567455684556945570455714557245573455744557545576455774557845579455804558145582455834558445585455864558745588455894559045591455924559345594455954559645597455984559945600456014560245603456044560545606456074560845609456104561145612456134561445615456164561745618456194562045621456224562345624456254562645627456284562945630456314563245633456344563545636456374563845639456404564145642456434564445645456464564745648456494565045651456524565345654456554565645657456584565945660456614566245663456644566545666456674566845669456704567145672456734567445675456764567745678456794568045681456824568345684456854568645687456884568945690456914569245693456944569545696456974569845699457004570145702457034570445705457064570745708457094571045711457124571345714457154571645717457184571945720457214572245723457244572545726457274572845729457304573145732457334573445735457364573745738457394574045741457424574345744457454574645747457484574945750457514575245753457544575545756457574575845759457604576145762457634576445765457664576745768457694577045771457724577345774457754577645777457784577945780457814578245783457844578545786457874578845789457904579145792457934579445795457964579745798457994580045801458024580345804458054580645807458084580945810458114581245813458144581545816458174581845819458204582145822458234582445825458264582745828458294583045831458324583345834458354583645837458384583945840458414584245843458444584545846458474584845849458504585145852458534585445855458564585745858458594586045861458624586345864458654586645867458684586945870458714587245873458744587545876458774587845879458804588145882458834588445885458864588745888458894589045891458924589345894458954589645897458984589945900459014590245903459044590545906459074590845909459104591145912459134591445915459164591745918459194592045921459224592345924459254592645927459284592945930459314593245933459344593545936459374593845939459404594145942459434594445945459464594745948459494595045951459524595345954459554595645957459584595945960459614596245963459644596545966459674596845969459704597145972459734597445975459764597745978459794598045981459824598345984459854598645987459884598945990459914599245993459944599545996459974599845999460004600146002460034600446005460064600746008460094601046011460124601346014460154601646017460184601946020460214602246023460244602546026460274602846029460304603146032460334603446035460364603746038460394604046041460424604346044460454604646047460484604946050460514605246053460544605546056460574605846059460604606146062460634606446065460664606746068460694607046071460724607346074460754607646077460784607946080460814608246083460844608546086460874608846089460904609146092460934609446095460964609746098460994610046101461024610346104461054610646107461084610946110461114611246113461144611546116461174611846119461204612146122461234612446125461264612746128461294613046131461324613346134461354613646137461384613946140461414614246143461444614546146461474614846149461504615146152461534615446155461564615746158461594616046161461624616346164461654616646167461684616946170461714617246173461744617546176461774617846179461804618146182461834618446185461864618746188461894619046191461924619346194461954619646197461984619946200462014620246203462044620546206462074620846209462104621146212462134621446215462164621746218462194622046221462224622346224462254622646227462284622946230462314623246233462344623546236462374623846239462404624146242462434624446245462464624746248462494625046251462524625346254462554625646257462584625946260462614626246263462644626546266462674626846269462704627146272462734627446275462764627746278462794628046281462824628346284462854628646287462884628946290462914629246293462944629546296462974629846299463004630146302463034630446305463064630746308463094631046311463124631346314463154631646317463184631946320463214632246323463244632546326463274632846329463304633146332463334633446335463364633746338463394634046341463424634346344463454634646347463484634946350463514635246353463544635546356463574635846359463604636146362463634636446365463664636746368463694637046371463724637346374463754637646377463784637946380463814638246383463844638546386463874638846389463904639146392463934639446395463964639746398463994640046401464024640346404464054640646407464084640946410464114641246413464144641546416464174641846419464204642146422464234642446425464264642746428464294643046431464324643346434464354643646437464384643946440464414644246443464444644546446464474644846449464504645146452464534645446455464564645746458464594646046461464624646346464464654646646467464684646946470464714647246473464744647546476464774647846479464804648146482464834648446485464864648746488464894649046491464924649346494464954649646497464984649946500465014650246503465044650546506465074650846509465104651146512465134651446515465164651746518465194652046521465224652346524465254652646527465284652946530465314653246533465344653546536465374653846539465404654146542465434654446545465464654746548465494655046551465524655346554465554655646557465584655946560465614656246563465644656546566465674656846569465704657146572465734657446575465764657746578465794658046581465824658346584465854658646587465884658946590465914659246593465944659546596465974659846599466004660146602466034660446605466064660746608466094661046611466124661346614466154661646617466184661946620466214662246623466244662546626466274662846629466304663146632466334663446635466364663746638466394664046641466424664346644466454664646647466484664946650466514665246653466544665546656466574665846659466604666146662466634666446665466664666746668466694667046671466724667346674466754667646677466784667946680466814668246683466844668546686466874668846689466904669146692466934669446695466964669746698466994670046701467024670346704467054670646707467084670946710467114671246713467144671546716467174671846719467204672146722467234672446725467264672746728467294673046731467324673346734467354673646737467384673946740467414674246743467444674546746467474674846749467504675146752467534675446755467564675746758467594676046761467624676346764467654676646767467684676946770467714677246773467744677546776467774677846779467804678146782467834678446785467864678746788467894679046791467924679346794467954679646797467984679946800468014680246803468044680546806468074680846809468104681146812468134681446815468164681746818468194682046821468224682346824468254682646827468284682946830468314683246833468344683546836468374683846839468404684146842468434684446845468464684746848468494685046851468524685346854468554685646857468584685946860468614686246863468644686546866468674686846869468704687146872468734687446875468764687746878468794688046881468824688346884468854688646887468884688946890468914689246893468944689546896468974689846899469004690146902469034690446905469064690746908469094691046911469124691346914469154691646917469184691946920469214692246923469244692546926469274692846929469304693146932469334693446935469364693746938469394694046941469424694346944469454694646947469484694946950469514695246953469544695546956469574695846959469604696146962469634696446965469664696746968469694697046971469724697346974469754697646977469784697946980469814698246983469844698546986469874698846989469904699146992469934699446995469964699746998469994700047001470024700347004470054700647007470084700947010470114701247013470144701547016470174701847019470204702147022470234702447025470264702747028470294703047031470324703347034470354703647037470384703947040470414704247043470444704547046470474704847049470504705147052470534705447055470564705747058470594706047061470624706347064470654706647067470684706947070470714707247073470744707547076470774707847079470804708147082470834708447085470864708747088470894709047091470924709347094470954709647097470984709947100471014710247103471044710547106471074710847109471104711147112471134711447115471164711747118471194712047121471224712347124471254712647127471284712947130471314713247133471344713547136471374713847139471404714147142471434714447145471464714747148471494715047151471524715347154471554715647157471584715947160471614716247163471644716547166471674716847169471704717147172471734717447175471764717747178471794718047181471824718347184471854718647187471884718947190471914719247193471944719547196471974719847199472004720147202472034720447205472064720747208472094721047211472124721347214472154721647217472184721947220472214722247223472244722547226472274722847229472304723147232472334723447235472364723747238472394724047241472424724347244472454724647247472484724947250472514725247253472544725547256472574725847259472604726147262472634726447265472664726747268472694727047271472724727347274472754727647277472784727947280472814728247283472844728547286472874728847289472904729147292472934729447295472964729747298472994730047301473024730347304473054730647307473084730947310473114731247313473144731547316473174731847319473204732147322473234732447325473264732747328473294733047331473324733347334473354733647337473384733947340473414734247343473444734547346473474734847349473504735147352473534735447355473564735747358473594736047361473624736347364473654736647367473684736947370473714737247373473744737547376473774737847379473804738147382473834738447385473864738747388473894739047391473924739347394473954739647397473984739947400474014740247403474044740547406474074740847409474104741147412474134741447415474164741747418474194742047421474224742347424474254742647427474284742947430474314743247433474344743547436474374743847439474404744147442474434744447445474464744747448474494745047451474524745347454474554745647457474584745947460474614746247463474644746547466474674746847469474704747147472474734747447475474764747747478474794748047481474824748347484474854748647487474884748947490474914749247493474944749547496474974749847499475004750147502475034750447505475064750747508475094751047511475124751347514475154751647517475184751947520475214752247523475244752547526475274752847529475304753147532475334753447535475364753747538475394754047541475424754347544475454754647547475484754947550475514755247553475544755547556475574755847559475604756147562475634756447565475664756747568475694757047571475724757347574475754757647577475784757947580475814758247583475844758547586475874758847589475904759147592475934759447595475964759747598475994760047601476024760347604476054760647607476084760947610476114761247613476144761547616476174761847619476204762147622476234762447625476264762747628476294763047631476324763347634476354763647637476384763947640476414764247643476444764547646476474764847649476504765147652476534765447655476564765747658476594766047661476624766347664476654766647667476684766947670476714767247673476744767547676476774767847679476804768147682476834768447685476864768747688476894769047691476924769347694476954769647697476984769947700477014770247703477044770547706477074770847709477104771147712477134771447715477164771747718477194772047721477224772347724477254772647727477284772947730477314773247733477344773547736477374773847739477404774147742477434774447745477464774747748477494775047751477524775347754477554775647757477584775947760477614776247763477644776547766477674776847769477704777147772477734777447775477764777747778477794778047781477824778347784477854778647787477884778947790477914779247793477944779547796477974779847799478004780147802478034780447805478064780747808478094781047811478124781347814478154781647817478184781947820478214782247823478244782547826478274782847829478304783147832478334783447835478364783747838478394784047841478424784347844478454784647847478484784947850478514785247853478544785547856478574785847859478604786147862478634786447865478664786747868478694787047871478724787347874478754787647877478784787947880478814788247883478844788547886478874788847889478904789147892478934789447895478964789747898478994790047901479024790347904479054790647907479084790947910479114791247913479144791547916479174791847919479204792147922479234792447925479264792747928479294793047931479324793347934479354793647937479384793947940479414794247943479444794547946479474794847949479504795147952479534795447955479564795747958479594796047961479624796347964479654796647967479684796947970479714797247973479744797547976479774797847979479804798147982479834798447985479864798747988479894799047991479924799347994479954799647997479984799948000480014800248003480044800548006480074800848009480104801148012480134801448015480164801748018480194802048021480224802348024480254802648027480284802948030480314803248033480344803548036480374803848039480404804148042480434804448045480464804748048480494805048051480524805348054480554805648057480584805948060480614806248063480644806548066480674806848069480704807148072480734807448075480764807748078480794808048081480824808348084480854808648087480884808948090480914809248093480944809548096480974809848099481004810148102481034810448105481064810748108481094811048111481124811348114481154811648117481184811948120481214812248123481244812548126481274812848129481304813148132481334813448135481364813748138481394814048141481424814348144481454814648147481484814948150481514815248153481544815548156481574815848159481604816148162481634816448165481664816748168481694817048171481724817348174481754817648177481784817948180481814818248183481844818548186481874818848189481904819148192481934819448195481964819748198481994820048201482024820348204482054820648207482084820948210482114821248213482144821548216482174821848219482204822148222482234822448225482264822748228482294823048231482324823348234482354823648237482384823948240482414824248243482444824548246482474824848249482504825148252482534825448255482564825748258482594826048261482624826348264482654826648267482684826948270482714827248273482744827548276482774827848279482804828148282482834828448285482864828748288482894829048291482924829348294482954829648297482984829948300483014830248303483044830548306483074830848309483104831148312483134831448315483164831748318483194832048321483224832348324483254832648327483284832948330483314833248333483344833548336483374833848339483404834148342483434834448345483464834748348483494835048351483524835348354483554835648357483584835948360483614836248363483644836548366483674836848369483704837148372483734837448375483764837748378483794838048381483824838348384483854838648387483884838948390483914839248393483944839548396483974839848399484004840148402484034840448405484064840748408484094841048411484124841348414484154841648417484184841948420484214842248423484244842548426484274842848429484304843148432484334843448435484364843748438484394844048441484424844348444484454844648447484484844948450484514845248453484544845548456484574845848459484604846148462484634846448465484664846748468484694847048471484724847348474484754847648477484784847948480484814848248483484844848548486484874848848489484904849148492484934849448495484964849748498484994850048501485024850348504485054850648507485084850948510485114851248513485144851548516485174851848519485204852148522485234852448525485264852748528485294853048531485324853348534485354853648537485384853948540485414854248543485444854548546485474854848549485504855148552485534855448555485564855748558485594856048561485624856348564485654856648567485684856948570485714857248573485744857548576485774857848579485804858148582485834858448585485864858748588485894859048591485924859348594485954859648597485984859948600486014860248603486044860548606486074860848609486104861148612486134861448615486164861748618486194862048621486224862348624486254862648627486284862948630486314863248633486344863548636486374863848639486404864148642486434864448645486464864748648486494865048651486524865348654486554865648657486584865948660486614866248663486644866548666486674866848669486704867148672486734867448675486764867748678486794868048681486824868348684486854868648687486884868948690486914869248693486944869548696486974869848699487004870148702487034870448705487064870748708487094871048711487124871348714487154871648717487184871948720487214872248723487244872548726487274872848729487304873148732487334873448735487364873748738487394874048741487424874348744487454874648747487484874948750487514875248753487544875548756487574875848759487604876148762487634876448765487664876748768487694877048771487724877348774487754877648777487784877948780487814878248783487844878548786487874878848789487904879148792487934879448795487964879748798487994880048801488024880348804488054880648807488084880948810488114881248813488144881548816488174881848819488204882148822488234882448825488264882748828488294883048831488324883348834488354883648837488384883948840488414884248843488444884548846488474884848849488504885148852488534885448855488564885748858488594886048861488624886348864488654886648867488684886948870488714887248873488744887548876488774887848879488804888148882488834888448885488864888748888488894889048891488924889348894488954889648897488984889948900489014890248903489044890548906489074890848909489104891148912489134891448915489164891748918489194892048921489224892348924489254892648927489284892948930489314893248933489344893548936489374893848939489404894148942489434894448945489464894748948489494895048951489524895348954489554895648957489584895948960489614896248963489644896548966489674896848969489704897148972489734897448975489764897748978489794898048981489824898348984489854898648987489884898948990489914899248993489944899548996489974899848999490004900149002490034900449005490064900749008490094901049011490124901349014490154901649017490184901949020490214902249023490244902549026490274902849029490304903149032490334903449035490364903749038490394904049041490424904349044490454904649047490484904949050490514905249053490544905549056490574905849059490604906149062490634906449065490664906749068490694907049071490724907349074490754907649077490784907949080490814908249083490844908549086490874908849089490904909149092490934909449095490964909749098490994910049101491024910349104491054910649107491084910949110491114911249113491144911549116491174911849119491204912149122491234912449125491264912749128491294913049131491324913349134491354913649137491384913949140491414914249143491444914549146491474914849149491504915149152491534915449155491564915749158491594916049161491624916349164491654916649167491684916949170491714917249173491744917549176491774917849179491804918149182491834918449185491864918749188491894919049191491924919349194491954919649197491984919949200492014920249203492044920549206492074920849209492104921149212492134921449215492164921749218492194922049221492224922349224492254922649227492284922949230492314923249233492344923549236492374923849239492404924149242492434924449245492464924749248492494925049251492524925349254492554925649257492584925949260492614926249263492644926549266492674926849269492704927149272492734927449275492764927749278492794928049281492824928349284492854928649287492884928949290492914929249293492944929549296492974929849299493004930149302493034930449305493064930749308493094931049311493124931349314493154931649317493184931949320493214932249323493244932549326493274932849329493304933149332493334933449335493364933749338493394934049341493424934349344493454934649347493484934949350493514935249353493544935549356493574935849359493604936149362493634936449365493664936749368493694937049371493724937349374493754937649377493784937949380493814938249383493844938549386493874938849389493904939149392493934939449395493964939749398493994940049401494024940349404494054940649407494084940949410494114941249413494144941549416494174941849419494204942149422494234942449425494264942749428494294943049431494324943349434494354943649437494384943949440494414944249443494444944549446494474944849449494504945149452494534945449455494564945749458494594946049461494624946349464494654946649467494684946949470494714947249473494744947549476494774947849479494804948149482494834948449485494864948749488494894949049491494924949349494494954949649497494984949949500495014950249503495044950549506495074950849509495104951149512495134951449515495164951749518495194952049521495224952349524495254952649527495284952949530495314953249533495344953549536495374953849539495404954149542495434954449545495464954749548495494955049551495524955349554495554955649557495584955949560495614956249563495644956549566495674956849569495704957149572495734957449575495764957749578495794958049581495824958349584495854958649587495884958949590495914959249593495944959549596495974959849599496004960149602496034960449605496064960749608496094961049611496124961349614496154961649617496184961949620496214962249623496244962549626496274962849629496304963149632496334963449635496364963749638496394964049641496424964349644496454964649647496484964949650496514965249653496544965549656496574965849659496604966149662496634966449665496664966749668496694967049671496724967349674496754967649677496784967949680496814968249683496844968549686496874968849689496904969149692496934969449695496964969749698496994970049701497024970349704497054970649707497084970949710497114971249713497144971549716497174971849719497204972149722497234972449725497264972749728497294973049731497324973349734497354973649737497384973949740497414974249743497444974549746497474974849749497504975149752497534975449755497564975749758497594976049761497624976349764497654976649767497684976949770497714977249773497744977549776497774977849779497804978149782497834978449785497864978749788497894979049791497924979349794497954979649797497984979949800498014980249803498044980549806498074980849809498104981149812498134981449815498164981749818498194982049821498224982349824498254982649827498284982949830498314983249833498344983549836498374983849839498404984149842498434984449845498464984749848498494985049851498524985349854498554985649857498584985949860498614986249863498644986549866498674986849869498704987149872498734987449875498764987749878498794988049881498824988349884498854988649887498884988949890498914989249893498944989549896498974989849899499004990149902499034990449905499064990749908499094991049911499124991349914499154991649917499184991949920499214992249923499244992549926499274992849929499304993149932499334993449935499364993749938499394994049941499424994349944499454994649947499484994949950499514995249953499544995549956499574995849959499604996149962499634996449965499664996749968499694997049971499724997349974499754997649977499784997949980499814998249983499844998549986499874998849989499904999149992499934999449995499964999749998499995000050001500025000350004500055000650007500085000950010500115001250013500145001550016500175001850019500205002150022500235002450025500265002750028500295003050031500325003350034500355003650037500385003950040500415004250043500445004550046500475004850049500505005150052500535005450055500565005750058500595006050061500625006350064500655006650067500685006950070500715007250073500745007550076500775007850079500805008150082500835008450085500865008750088500895009050091500925009350094500955009650097500985009950100501015010250103501045010550106501075010850109501105011150112501135011450115501165011750118501195012050121501225012350124501255012650127501285012950130501315013250133501345013550136501375013850139501405014150142501435014450145501465014750148501495015050151501525015350154501555015650157501585015950160501615016250163501645016550166501675016850169501705017150172501735017450175501765017750178501795018050181501825018350184501855018650187501885018950190501915019250193501945019550196501975019850199502005020150202502035020450205502065020750208502095021050211502125021350214502155021650217502185021950220502215022250223502245022550226502275022850229502305023150232502335023450235502365023750238502395024050241502425024350244502455024650247502485024950250502515025250253502545025550256502575025850259502605026150262502635026450265502665026750268502695027050271502725027350274502755027650277502785027950280502815028250283502845028550286502875028850289502905029150292502935029450295502965029750298502995030050301503025030350304503055030650307503085030950310503115031250313503145031550316503175031850319503205032150322503235032450325503265032750328503295033050331503325033350334503355033650337503385033950340503415034250343503445034550346503475034850349503505035150352503535035450355503565035750358503595036050361503625036350364503655036650367503685036950370503715037250373503745037550376503775037850379503805038150382503835038450385503865038750388503895039050391503925039350394503955039650397503985039950400504015040250403504045040550406504075040850409504105041150412504135041450415504165041750418504195042050421504225042350424504255042650427504285042950430504315043250433504345043550436504375043850439504405044150442504435044450445504465044750448504495045050451504525045350454504555045650457504585045950460504615046250463504645046550466504675046850469504705047150472504735047450475504765047750478504795048050481504825048350484504855048650487504885048950490504915049250493504945049550496504975049850499505005050150502505035050450505505065050750508505095051050511505125051350514505155051650517505185051950520505215052250523505245052550526505275052850529505305053150532505335053450535505365053750538505395054050541505425054350544505455054650547505485054950550505515055250553505545055550556505575055850559505605056150562505635056450565505665056750568505695057050571505725057350574505755057650577505785057950580505815058250583505845058550586505875058850589505905059150592505935059450595505965059750598505995060050601506025060350604506055060650607506085060950610506115061250613506145061550616506175061850619506205062150622506235062450625506265062750628506295063050631506325063350634506355063650637506385063950640506415064250643506445064550646506475064850649506505065150652506535065450655506565065750658506595066050661506625066350664506655066650667506685066950670506715067250673506745067550676506775067850679506805068150682506835068450685506865068750688506895069050691506925069350694506955069650697506985069950700507015070250703507045070550706507075070850709507105071150712507135071450715507165071750718507195072050721507225072350724507255072650727507285072950730507315073250733507345073550736507375073850739507405074150742507435074450745507465074750748507495075050751507525075350754507555075650757507585075950760507615076250763507645076550766507675076850769507705077150772507735077450775507765077750778507795078050781507825078350784507855078650787507885078950790507915079250793507945079550796507975079850799508005080150802508035080450805508065080750808508095081050811508125081350814508155081650817508185081950820508215082250823508245082550826508275082850829508305083150832508335083450835508365083750838508395084050841508425084350844508455084650847508485084950850508515085250853508545085550856508575085850859508605086150862508635086450865508665086750868508695087050871508725087350874508755087650877508785087950880508815088250883508845088550886508875088850889508905089150892508935089450895508965089750898508995090050901509025090350904509055090650907509085090950910509115091250913509145091550916509175091850919509205092150922509235092450925509265092750928509295093050931509325093350934509355093650937509385093950940509415094250943509445094550946509475094850949509505095150952509535095450955509565095750958509595096050961509625096350964509655096650967509685096950970509715097250973509745097550976509775097850979509805098150982509835098450985509865098750988509895099050991509925099350994509955099650997509985099951000510015100251003510045100551006510075100851009510105101151012510135101451015510165101751018510195102051021510225102351024510255102651027510285102951030510315103251033510345103551036510375103851039510405104151042510435104451045510465104751048510495105051051510525105351054510555105651057510585105951060510615106251063510645106551066510675106851069510705107151072510735107451075510765107751078510795108051081510825108351084510855108651087510885108951090510915109251093510945109551096510975109851099511005110151102511035110451105511065110751108511095111051111511125111351114511155111651117511185111951120511215112251123511245112551126511275112851129511305113151132511335113451135511365113751138511395114051141511425114351144511455114651147511485114951150511515115251153511545115551156511575115851159511605116151162511635116451165511665116751168511695117051171511725117351174511755117651177511785117951180511815118251183511845118551186511875118851189511905119151192511935119451195511965119751198511995120051201512025120351204512055120651207512085120951210512115121251213512145121551216512175121851219512205122151222512235122451225512265122751228512295123051231512325123351234512355123651237512385123951240512415124251243512445124551246512475124851249512505125151252512535125451255512565125751258512595126051261512625126351264512655126651267512685126951270512715127251273512745127551276512775127851279512805128151282512835128451285512865128751288512895129051291512925129351294512955129651297512985129951300513015130251303513045130551306513075130851309513105131151312513135131451315513165131751318513195132051321513225132351324513255132651327513285132951330513315133251333513345133551336513375133851339513405134151342513435134451345513465134751348513495135051351513525135351354513555135651357513585135951360513615136251363513645136551366513675136851369513705137151372513735137451375513765137751378513795138051381513825138351384513855138651387513885138951390513915139251393513945139551396513975139851399514005140151402514035140451405514065140751408514095141051411514125141351414514155141651417514185141951420514215142251423514245142551426514275142851429514305143151432514335143451435514365143751438514395144051441514425144351444514455144651447514485144951450514515145251453514545145551456514575145851459514605146151462514635146451465514665146751468514695147051471514725147351474514755147651477514785147951480514815148251483514845148551486514875148851489514905149151492514935149451495514965149751498514995150051501515025150351504515055150651507515085150951510515115151251513515145151551516515175151851519515205152151522515235152451525515265152751528515295153051531515325153351534515355153651537515385153951540515415154251543515445154551546515475154851549515505155151552515535155451555515565155751558515595156051561515625156351564515655156651567515685156951570515715157251573515745157551576515775157851579515805158151582515835158451585515865158751588515895159051591515925159351594515955159651597515985159951600516015160251603516045160551606516075160851609516105161151612516135161451615516165161751618516195162051621516225162351624516255162651627516285162951630516315163251633516345163551636516375163851639516405164151642516435164451645516465164751648516495165051651516525165351654516555165651657516585165951660516615166251663516645166551666516675166851669516705167151672516735167451675516765167751678516795168051681516825168351684516855168651687516885168951690516915169251693516945169551696516975169851699517005170151702517035170451705517065170751708517095171051711517125171351714517155171651717517185171951720517215172251723517245172551726517275172851729517305173151732517335173451735517365173751738517395174051741517425174351744517455174651747517485174951750517515175251753517545175551756517575175851759517605176151762517635176451765517665176751768517695177051771517725177351774517755177651777517785177951780517815178251783517845178551786517875178851789517905179151792517935179451795517965179751798517995180051801518025180351804518055180651807518085180951810518115181251813518145181551816518175181851819518205182151822518235182451825518265182751828518295183051831518325183351834518355183651837518385183951840518415184251843518445184551846518475184851849518505185151852518535185451855518565185751858518595186051861518625186351864518655186651867518685186951870518715187251873518745187551876518775187851879518805188151882518835188451885518865188751888518895189051891518925189351894518955189651897518985189951900519015190251903519045190551906519075190851909519105191151912519135191451915519165191751918519195192051921519225192351924519255192651927519285192951930519315193251933519345193551936519375193851939519405194151942519435194451945519465194751948519495195051951519525195351954519555195651957519585195951960519615196251963519645196551966519675196851969519705197151972519735197451975519765197751978519795198051981519825198351984519855198651987519885198951990519915199251993519945199551996519975199851999520005200152002520035200452005520065200752008520095201052011520125201352014520155201652017520185201952020520215202252023520245202552026520275202852029520305203152032520335203452035520365203752038520395204052041520425204352044520455204652047520485204952050520515205252053520545205552056520575205852059520605206152062520635206452065520665206752068520695207052071520725207352074520755207652077520785207952080520815208252083520845208552086520875208852089520905209152092520935209452095520965209752098520995210052101521025210352104521055210652107521085210952110521115211252113521145211552116521175211852119521205212152122521235212452125521265212752128521295213052131521325213352134521355213652137521385213952140521415214252143521445214552146521475214852149521505215152152521535215452155521565215752158521595216052161521625216352164521655216652167521685216952170521715217252173521745217552176521775217852179521805218152182521835218452185521865218752188521895219052191521925219352194521955219652197521985219952200522015220252203522045220552206522075220852209522105221152212522135221452215522165221752218522195222052221522225222352224522255222652227522285222952230522315223252233522345223552236522375223852239522405224152242522435224452245522465224752248522495225052251522525225352254522555225652257522585225952260522615226252263522645226552266522675226852269522705227152272522735227452275522765227752278522795228052281522825228352284522855228652287522885228952290522915229252293522945229552296522975229852299523005230152302523035230452305523065230752308523095231052311523125231352314523155231652317523185231952320523215232252323523245232552326523275232852329523305233152332523335233452335523365233752338523395234052341523425234352344523455234652347523485234952350523515235252353523545235552356523575235852359523605236152362523635236452365523665236752368523695237052371523725237352374523755237652377523785237952380523815238252383523845238552386523875238852389523905239152392523935239452395523965239752398523995240052401524025240352404524055240652407524085240952410524115241252413524145241552416524175241852419524205242152422524235242452425524265242752428524295243052431524325243352434524355243652437524385243952440524415244252443524445244552446524475244852449524505245152452524535245452455524565245752458524595246052461524625246352464524655246652467524685246952470524715247252473524745247552476524775247852479524805248152482524835248452485524865248752488524895249052491524925249352494524955249652497524985249952500525015250252503525045250552506525075250852509525105251152512525135251452515525165251752518525195252052521525225252352524525255252652527525285252952530525315253252533525345253552536525375253852539525405254152542525435254452545525465254752548525495255052551525525255352554525555255652557525585255952560525615256252563525645256552566525675256852569525705257152572525735257452575525765257752578525795258052581525825258352584525855258652587525885258952590525915259252593525945259552596525975259852599526005260152602526035260452605526065260752608526095261052611526125261352614526155261652617526185261952620526215262252623526245262552626526275262852629526305263152632526335263452635526365263752638526395264052641526425264352644526455264652647526485264952650526515265252653526545265552656526575265852659526605266152662526635266452665526665266752668526695267052671526725267352674526755267652677526785267952680526815268252683526845268552686526875268852689526905269152692526935269452695526965269752698526995270052701527025270352704527055270652707527085270952710527115271252713527145271552716527175271852719527205272152722527235272452725527265272752728527295273052731527325273352734527355273652737527385273952740527415274252743527445274552746527475274852749527505275152752527535275452755527565275752758527595276052761527625276352764527655276652767527685276952770527715277252773527745277552776527775277852779527805278152782527835278452785527865278752788527895279052791527925279352794527955279652797527985279952800528015280252803528045280552806528075280852809528105281152812528135281452815528165281752818528195282052821528225282352824528255282652827528285282952830528315283252833528345283552836528375283852839528405284152842528435284452845528465284752848528495285052851528525285352854528555285652857528585285952860528615286252863528645286552866528675286852869528705287152872528735287452875528765287752878528795288052881528825288352884528855288652887528885288952890528915289252893528945289552896528975289852899529005290152902529035290452905529065290752908529095291052911529125291352914529155291652917529185291952920529215292252923529245292552926529275292852929529305293152932529335293452935529365293752938529395294052941529425294352944529455294652947529485294952950529515295252953529545295552956529575295852959529605296152962529635296452965529665296752968529695297052971529725297352974529755297652977529785297952980529815298252983529845298552986529875298852989529905299152992529935299452995529965299752998529995300053001530025300353004530055300653007530085300953010530115301253013530145301553016530175301853019530205302153022530235302453025530265302753028530295303053031530325303353034530355303653037530385303953040530415304253043530445304553046530475304853049530505305153052530535305453055530565305753058530595306053061530625306353064530655306653067530685306953070530715307253073530745307553076530775307853079530805308153082530835308453085530865308753088530895309053091530925309353094530955309653097530985309953100531015310253103531045310553106531075310853109531105311153112531135311453115531165311753118531195312053121531225312353124531255312653127531285312953130531315313253133531345313553136531375313853139531405314153142531435314453145531465314753148531495315053151531525315353154531555315653157531585315953160531615316253163531645316553166531675316853169531705317153172531735317453175531765317753178531795318053181531825318353184531855318653187531885318953190531915319253193531945319553196531975319853199532005320153202532035320453205532065320753208532095321053211532125321353214532155321653217532185321953220532215322253223532245322553226532275322853229532305323153232532335323453235532365323753238532395324053241532425324353244532455324653247532485324953250532515325253253532545325553256532575325853259532605326153262532635326453265532665326753268532695327053271532725327353274532755327653277532785327953280532815328253283532845328553286532875328853289532905329153292532935329453295532965329753298532995330053301533025330353304533055330653307533085330953310533115331253313533145331553316533175331853319533205332153322533235332453325533265332753328533295333053331533325333353334533355333653337533385333953340533415334253343533445334553346533475334853349533505335153352533535335453355533565335753358533595336053361533625336353364533655336653367533685336953370533715337253373533745337553376533775337853379533805338153382533835338453385533865338753388533895339053391533925339353394533955339653397533985339953400534015340253403534045340553406534075340853409534105341153412534135341453415534165341753418534195342053421534225342353424534255342653427534285342953430534315343253433534345343553436534375343853439534405344153442534435344453445534465344753448534495345053451534525345353454534555345653457534585345953460534615346253463534645346553466534675346853469534705347153472534735347453475534765347753478534795348053481534825348353484534855348653487534885348953490534915349253493534945349553496534975349853499535005350153502535035350453505535065350753508535095351053511535125351353514535155351653517535185351953520535215352253523535245352553526535275352853529535305353153532535335353453535535365353753538535395354053541535425354353544535455354653547535485354953550535515355253553535545355553556535575355853559535605356153562535635356453565535665356753568535695357053571535725357353574535755357653577535785357953580535815358253583535845358553586535875358853589535905359153592535935359453595535965359753598535995360053601536025360353604536055360653607536085360953610536115361253613536145361553616536175361853619536205362153622536235362453625536265362753628536295363053631536325363353634536355363653637536385363953640536415364253643536445364553646536475364853649536505365153652536535365453655536565365753658536595366053661536625366353664536655366653667536685366953670536715367253673536745367553676536775367853679536805368153682536835368453685536865368753688536895369053691536925369353694536955369653697536985369953700537015370253703537045370553706537075370853709537105371153712537135371453715537165371753718537195372053721537225372353724537255372653727537285372953730537315373253733537345373553736537375373853739537405374153742537435374453745537465374753748537495375053751537525375353754537555375653757537585375953760537615376253763537645376553766537675376853769537705377153772537735377453775537765377753778537795378053781537825378353784537855378653787537885378953790537915379253793537945379553796537975379853799538005380153802538035380453805538065380753808538095381053811538125381353814538155381653817538185381953820538215382253823538245382553826538275382853829538305383153832538335383453835538365383753838538395384053841538425384353844538455384653847538485384953850538515385253853538545385553856538575385853859538605386153862538635386453865538665386753868538695387053871538725387353874538755387653877538785387953880538815388253883538845388553886538875388853889538905389153892538935389453895538965389753898538995390053901539025390353904539055390653907539085390953910539115391253913539145391553916539175391853919539205392153922539235392453925539265392753928539295393053931539325393353934539355393653937539385393953940539415394253943539445394553946539475394853949539505395153952539535395453955539565395753958539595396053961539625396353964539655396653967539685396953970539715397253973539745397553976539775397853979539805398153982539835398453985539865398753988539895399053991539925399353994539955399653997539985399954000540015400254003540045400554006540075400854009540105401154012540135401454015540165401754018540195402054021540225402354024540255402654027540285402954030540315403254033540345403554036540375403854039540405404154042540435404454045540465404754048540495405054051540525405354054540555405654057540585405954060540615406254063540645406554066540675406854069540705407154072540735407454075540765407754078540795408054081540825408354084540855408654087540885408954090540915409254093540945409554096540975409854099541005410154102541035410454105541065410754108541095411054111541125411354114541155411654117541185411954120541215412254123541245412554126541275412854129541305413154132541335413454135541365413754138541395414054141541425414354144541455414654147541485414954150541515415254153541545415554156541575415854159541605416154162541635416454165541665416754168541695417054171541725417354174541755417654177541785417954180541815418254183541845418554186541875418854189541905419154192541935419454195541965419754198541995420054201542025420354204542055420654207542085420954210542115421254213542145421554216542175421854219542205422154222542235422454225542265422754228542295423054231542325423354234542355423654237542385423954240542415424254243542445424554246542475424854249542505425154252542535425454255542565425754258542595426054261542625426354264542655426654267542685426954270542715427254273542745427554276542775427854279542805428154282542835428454285542865428754288542895429054291542925429354294542955429654297542985429954300543015430254303543045430554306543075430854309543105431154312543135431454315543165431754318543195432054321543225432354324543255432654327543285432954330543315433254333543345433554336543375433854339543405434154342543435434454345543465434754348543495435054351543525435354354543555435654357543585435954360543615436254363543645436554366543675436854369543705437154372543735437454375543765437754378543795438054381543825438354384543855438654387543885438954390543915439254393543945439554396543975439854399544005440154402544035440454405544065440754408544095441054411544125441354414544155441654417544185441954420544215442254423544245442554426544275442854429544305443154432544335443454435544365443754438544395444054441544425444354444544455444654447544485444954450544515445254453544545445554456544575445854459544605446154462544635446454465544665446754468544695447054471544725447354474544755447654477544785447954480544815448254483544845448554486544875448854489544905449154492544935449454495544965449754498544995450054501545025450354504545055450654507545085450954510545115451254513545145451554516545175451854519545205452154522545235452454525545265452754528545295453054531545325453354534545355453654537545385453954540545415454254543545445454554546545475454854549545505455154552545535455454555545565455754558545595456054561545625456354564545655456654567545685456954570545715457254573545745457554576545775457854579545805458154582545835458454585545865458754588545895459054591545925459354594545955459654597545985459954600546015460254603546045460554606546075460854609546105461154612546135461454615546165461754618546195462054621546225462354624546255462654627546285462954630546315463254633546345463554636546375463854639546405464154642546435464454645546465464754648546495465054651546525465354654546555465654657546585465954660546615466254663546645466554666546675466854669546705467154672546735467454675546765467754678546795468054681546825468354684546855468654687546885468954690546915469254693546945469554696546975469854699547005470154702547035470454705547065470754708547095471054711547125471354714547155471654717547185471954720547215472254723547245472554726547275472854729547305473154732547335473454735547365473754738547395474054741547425474354744547455474654747547485474954750547515475254753547545475554756547575475854759547605476154762547635476454765547665476754768547695477054771547725477354774547755477654777547785477954780547815478254783547845478554786547875478854789547905479154792547935479454795547965479754798547995480054801548025480354804548055480654807548085480954810548115481254813548145481554816548175481854819548205482154822548235482454825548265482754828548295483054831548325483354834548355483654837548385483954840548415484254843548445484554846548475484854849548505485154852548535485454855548565485754858548595486054861548625486354864548655486654867548685486954870548715487254873548745487554876548775487854879548805488154882548835488454885548865488754888548895489054891548925489354894548955489654897548985489954900549015490254903549045490554906549075490854909549105491154912549135491454915549165491754918549195492054921549225492354924549255492654927549285492954930549315493254933549345493554936549375493854939549405494154942549435494454945549465494754948549495495054951549525495354954549555495654957549585495954960549615496254963549645496554966549675496854969549705497154972549735497454975549765497754978549795498054981549825498354984549855498654987549885498954990549915499254993549945499554996549975499854999550005500155002550035500455005550065500755008550095501055011550125501355014550155501655017550185501955020550215502255023550245502555026550275502855029550305503155032550335503455035550365503755038550395504055041550425504355044550455504655047550485504955050550515505255053550545505555056550575505855059550605506155062550635506455065550665506755068550695507055071550725507355074550755507655077550785507955080550815508255083550845508555086550875508855089550905509155092550935509455095550965509755098550995510055101551025510355104551055510655107551085510955110551115511255113551145511555116551175511855119551205512155122551235512455125551265512755128551295513055131551325513355134551355513655137551385513955140551415514255143551445514555146551475514855149551505515155152551535515455155551565515755158551595516055161551625516355164551655516655167551685516955170551715517255173551745517555176551775517855179551805518155182551835518455185551865518755188551895519055191551925519355194551955519655197551985519955200552015520255203552045520555206552075520855209552105521155212552135521455215552165521755218552195522055221552225522355224552255522655227552285522955230552315523255233552345523555236552375523855239552405524155242552435524455245552465524755248552495525055251552525525355254552555525655257552585525955260552615526255263552645526555266552675526855269552705527155272552735527455275552765527755278552795528055281552825528355284552855528655287552885528955290552915529255293552945529555296552975529855299553005530155302553035530455305553065530755308553095531055311553125531355314553155531655317553185531955320553215532255323553245532555326553275532855329553305533155332553335533455335553365533755338553395534055341553425534355344553455534655347553485534955350553515535255353553545535555356553575535855359553605536155362553635536455365553665536755368553695537055371553725537355374553755537655377553785537955380553815538255383553845538555386553875538855389553905539155392553935539455395553965539755398553995540055401554025540355404554055540655407554085540955410554115541255413554145541555416554175541855419554205542155422554235542455425554265542755428554295543055431554325543355434554355543655437554385543955440554415544255443554445544555446554475544855449554505545155452554535545455455554565545755458554595546055461554625546355464554655546655467554685546955470554715547255473554745547555476554775547855479554805548155482554835548455485554865548755488554895549055491554925549355494554955549655497554985549955500555015550255503555045550555506555075550855509555105551155512555135551455515555165551755518555195552055521555225552355524555255552655527555285552955530555315553255533555345553555536555375553855539555405554155542555435554455545555465554755548555495555055551555525555355554555555555655557555585555955560555615556255563555645556555566555675556855569555705557155572555735557455575555765557755578555795558055581555825558355584555855558655587555885558955590555915559255593555945559555596555975559855599556005560155602556035560455605556065560755608556095561055611556125561355614556155561655617556185561955620556215562255623556245562555626556275562855629556305563155632556335563455635556365563755638556395564055641556425564355644556455564655647556485564955650556515565255653556545565555656556575565855659556605566155662556635566455665556665566755668556695567055671556725567355674556755567655677556785567955680556815568255683556845568555686556875568855689556905569155692556935569455695556965569755698556995570055701557025570355704557055570655707557085570955710557115571255713557145571555716557175571855719557205572155722557235572455725557265572755728557295573055731557325573355734557355573655737557385573955740557415574255743557445574555746557475574855749557505575155752557535575455755557565575755758557595576055761557625576355764557655576655767557685576955770557715577255773557745577555776557775577855779557805578155782557835578455785557865578755788557895579055791557925579355794557955579655797557985579955800558015580255803558045580555806558075580855809558105581155812558135581455815558165581755818558195582055821558225582355824558255582655827558285582955830558315583255833558345583555836558375583855839558405584155842558435584455845558465584755848558495585055851558525585355854558555585655857558585585955860558615586255863558645586555866558675586855869558705587155872558735587455875558765587755878558795588055881558825588355884558855588655887558885588955890558915589255893558945589555896558975589855899559005590155902559035590455905559065590755908559095591055911559125591355914559155591655917559185591955920559215592255923559245592555926559275592855929559305593155932559335593455935559365593755938559395594055941559425594355944559455594655947559485594955950559515595255953559545595555956559575595855959559605596155962559635596455965559665596755968559695597055971559725597355974559755597655977559785597955980559815598255983559845598555986559875598855989559905599155992559935599455995559965599755998559995600056001560025600356004560055600656007560085600956010560115601256013560145601556016560175601856019560205602156022560235602456025560265602756028560295603056031560325603356034560355603656037560385603956040560415604256043560445604556046560475604856049560505605156052560535605456055560565605756058560595606056061560625606356064560655606656067560685606956070560715607256073560745607556076560775607856079560805608156082560835608456085560865608756088560895609056091560925609356094560955609656097560985609956100561015610256103561045610556106561075610856109561105611156112561135611456115561165611756118561195612056121561225612356124561255612656127561285612956130561315613256133561345613556136561375613856139561405614156142561435614456145561465614756148561495615056151561525615356154561555615656157561585615956160561615616256163561645616556166561675616856169561705617156172561735617456175561765617756178561795618056181561825618356184561855618656187561885618956190561915619256193561945619556196561975619856199562005620156202562035620456205562065620756208562095621056211562125621356214562155621656217562185621956220562215622256223562245622556226562275622856229562305623156232562335623456235562365623756238562395624056241562425624356244562455624656247562485624956250562515625256253562545625556256562575625856259562605626156262562635626456265562665626756268562695627056271562725627356274562755627656277562785627956280562815628256283562845628556286562875628856289562905629156292562935629456295562965629756298562995630056301563025630356304563055630656307563085630956310563115631256313563145631556316563175631856319563205632156322563235632456325563265632756328563295633056331563325633356334563355633656337563385633956340563415634256343563445634556346563475634856349563505635156352563535635456355563565635756358563595636056361563625636356364563655636656367563685636956370563715637256373563745637556376563775637856379563805638156382563835638456385563865638756388563895639056391563925639356394563955639656397563985639956400564015640256403564045640556406564075640856409564105641156412564135641456415564165641756418564195642056421564225642356424564255642656427564285642956430564315643256433564345643556436564375643856439564405644156442564435644456445564465644756448564495645056451564525645356454564555645656457564585645956460564615646256463564645646556466564675646856469564705647156472564735647456475564765647756478564795648056481564825648356484564855648656487564885648956490564915649256493564945649556496564975649856499565005650156502565035650456505565065650756508565095651056511565125651356514565155651656517565185651956520565215652256523565245652556526565275652856529565305653156532565335653456535565365653756538565395654056541565425654356544565455654656547565485654956550565515655256553565545655556556565575655856559565605656156562565635656456565565665656756568565695657056571565725657356574565755657656577565785657956580565815658256583565845658556586565875658856589565905659156592565935659456595565965659756598565995660056601566025660356604566055660656607566085660956610566115661256613566145661556616566175661856619566205662156622566235662456625566265662756628566295663056631566325663356634566355663656637566385663956640566415664256643566445664556646566475664856649566505665156652566535665456655566565665756658566595666056661566625666356664566655666656667566685666956670566715667256673566745667556676566775667856679566805668156682566835668456685566865668756688566895669056691566925669356694566955669656697566985669956700567015670256703567045670556706567075670856709567105671156712567135671456715567165671756718567195672056721567225672356724567255672656727567285672956730567315673256733567345673556736567375673856739567405674156742567435674456745567465674756748567495675056751567525675356754567555675656757567585675956760567615676256763567645676556766567675676856769567705677156772567735677456775567765677756778567795678056781567825678356784567855678656787567885678956790567915679256793567945679556796567975679856799568005680156802568035680456805568065680756808568095681056811568125681356814568155681656817568185681956820568215682256823568245682556826568275682856829568305683156832568335683456835568365683756838568395684056841568425684356844568455684656847568485684956850568515685256853568545685556856568575685856859568605686156862568635686456865568665686756868568695687056871568725687356874568755687656877568785687956880568815688256883568845688556886568875688856889568905689156892568935689456895568965689756898568995690056901569025690356904569055690656907569085690956910569115691256913569145691556916569175691856919569205692156922569235692456925569265692756928569295693056931569325693356934569355693656937569385693956940569415694256943569445694556946569475694856949569505695156952569535695456955569565695756958569595696056961569625696356964569655696656967569685696956970569715697256973569745697556976569775697856979569805698156982569835698456985569865698756988569895699056991569925699356994569955699656997569985699957000570015700257003570045700557006570075700857009570105701157012570135701457015570165701757018570195702057021570225702357024570255702657027570285702957030570315703257033570345703557036570375703857039570405704157042570435704457045570465704757048570495705057051570525705357054570555705657057570585705957060570615706257063570645706557066570675706857069570705707157072570735707457075570765707757078570795708057081570825708357084570855708657087570885708957090570915709257093570945709557096570975709857099571005710157102571035710457105571065710757108571095711057111571125711357114571155711657117571185711957120571215712257123571245712557126571275712857129571305713157132571335713457135571365713757138571395714057141571425714357144571455714657147571485714957150571515715257153571545715557156571575715857159571605716157162571635716457165571665716757168571695717057171571725717357174571755717657177571785717957180571815718257183571845718557186571875718857189571905719157192571935719457195571965719757198571995720057201572025720357204572055720657207572085720957210572115721257213572145721557216572175721857219572205722157222572235722457225572265722757228572295723057231572325723357234572355723657237572385723957240572415724257243572445724557246572475724857249572505725157252572535725457255572565725757258572595726057261572625726357264572655726657267572685726957270572715727257273572745727557276572775727857279572805728157282572835728457285572865728757288572895729057291572925729357294572955729657297572985729957300573015730257303573045730557306573075730857309573105731157312573135731457315573165731757318573195732057321573225732357324573255732657327573285732957330573315733257333573345733557336573375733857339573405734157342573435734457345573465734757348573495735057351573525735357354573555735657357573585735957360573615736257363573645736557366573675736857369573705737157372573735737457375573765737757378573795738057381573825738357384573855738657387573885738957390573915739257393573945739557396573975739857399574005740157402574035740457405574065740757408574095741057411574125741357414574155741657417574185741957420574215742257423574245742557426574275742857429574305743157432574335743457435574365743757438574395744057441574425744357444574455744657447574485744957450574515745257453574545745557456574575745857459574605746157462574635746457465574665746757468574695747057471574725747357474574755747657477574785747957480574815748257483574845748557486574875748857489574905749157492574935749457495574965749757498574995750057501575025750357504575055750657507575085750957510575115751257513575145751557516575175751857519575205752157522575235752457525575265752757528575295753057531575325753357534575355753657537575385753957540575415754257543575445754557546575475754857549575505755157552575535755457555575565755757558575595756057561575625756357564575655756657567575685756957570575715757257573575745757557576575775757857579575805758157582575835758457585575865758757588575895759057591575925759357594575955759657597575985759957600576015760257603576045760557606576075760857609576105761157612576135761457615576165761757618576195762057621576225762357624576255762657627576285762957630576315763257633576345763557636576375763857639576405764157642576435764457645576465764757648576495765057651576525765357654576555765657657576585765957660576615766257663576645766557666576675766857669576705767157672576735767457675576765767757678576795768057681576825768357684576855768657687576885768957690576915769257693576945769557696576975769857699577005770157702577035770457705577065770757708577095771057711577125771357714577155771657717577185771957720577215772257723577245772557726577275772857729577305773157732577335773457735577365773757738577395774057741577425774357744577455774657747577485774957750577515775257753577545775557756577575775857759577605776157762577635776457765577665776757768577695777057771577725777357774577755777657777577785777957780577815778257783577845778557786577875778857789577905779157792577935779457795577965779757798577995780057801578025780357804578055780657807578085780957810578115781257813578145781557816578175781857819578205782157822578235782457825578265782757828578295783057831578325783357834578355783657837578385783957840578415784257843578445784557846578475784857849578505785157852578535785457855578565785757858578595786057861578625786357864578655786657867578685786957870578715787257873578745787557876578775787857879578805788157882578835788457885578865788757888578895789057891578925789357894578955789657897578985789957900579015790257903579045790557906579075790857909579105791157912579135791457915579165791757918579195792057921579225792357924579255792657927579285792957930579315793257933579345793557936579375793857939579405794157942579435794457945579465794757948579495795057951579525795357954579555795657957579585795957960579615796257963579645796557966579675796857969579705797157972579735797457975579765797757978579795798057981579825798357984579855798657987579885798957990579915799257993579945799557996579975799857999580005800158002580035800458005580065800758008580095801058011580125801358014580155801658017580185801958020580215802258023580245802558026580275802858029580305803158032580335803458035580365803758038580395804058041580425804358044580455804658047580485804958050580515805258053580545805558056580575805858059580605806158062580635806458065580665806758068580695807058071580725807358074580755807658077580785807958080580815808258083580845808558086580875808858089580905809158092580935809458095580965809758098580995810058101581025810358104581055810658107581085810958110581115811258113581145811558116581175811858119581205812158122581235812458125581265812758128581295813058131581325813358134581355813658137581385813958140581415814258143581445814558146581475814858149581505815158152581535815458155581565815758158581595816058161581625816358164581655816658167581685816958170581715817258173581745817558176581775817858179581805818158182581835818458185581865818758188581895819058191581925819358194581955819658197581985819958200582015820258203582045820558206582075820858209582105821158212582135821458215582165821758218582195822058221582225822358224582255822658227582285822958230582315823258233582345823558236582375823858239582405824158242582435824458245582465824758248582495825058251582525825358254582555825658257582585825958260582615826258263582645826558266582675826858269582705827158272582735827458275582765827758278582795828058281582825828358284582855828658287582885828958290582915829258293582945829558296582975829858299583005830158302583035830458305583065830758308583095831058311583125831358314583155831658317583185831958320583215832258323583245832558326583275832858329583305833158332583335833458335583365833758338583395834058341583425834358344583455834658347583485834958350583515835258353583545835558356583575835858359583605836158362583635836458365583665836758368583695837058371583725837358374583755837658377583785837958380583815838258383583845838558386583875838858389583905839158392583935839458395583965839758398583995840058401584025840358404584055840658407584085840958410584115841258413584145841558416584175841858419584205842158422584235842458425584265842758428584295843058431584325843358434584355843658437584385843958440584415844258443584445844558446584475844858449584505845158452584535845458455584565845758458584595846058461584625846358464584655846658467584685846958470584715847258473584745847558476584775847858479584805848158482584835848458485584865848758488584895849058491584925849358494584955849658497584985849958500585015850258503585045850558506585075850858509585105851158512585135851458515585165851758518585195852058521585225852358524585255852658527585285852958530585315853258533585345853558536585375853858539585405854158542585435854458545585465854758548585495855058551585525855358554585555855658557585585855958560585615856258563585645856558566585675856858569585705857158572585735857458575585765857758578585795858058581585825858358584585855858658587585885858958590585915859258593585945859558596585975859858599586005860158602586035860458605586065860758608586095861058611586125861358614586155861658617586185861958620586215862258623586245862558626586275862858629586305863158632586335863458635586365863758638586395864058641586425864358644586455864658647586485864958650586515865258653586545865558656586575865858659586605866158662586635866458665586665866758668586695867058671586725867358674586755867658677586785867958680586815868258683586845868558686586875868858689586905869158692586935869458695586965869758698586995870058701587025870358704587055870658707587085870958710587115871258713587145871558716587175871858719587205872158722587235872458725587265872758728587295873058731587325873358734587355873658737587385873958740587415874258743587445874558746587475874858749587505875158752587535875458755587565875758758587595876058761587625876358764587655876658767587685876958770587715877258773587745877558776587775877858779587805878158782587835878458785587865878758788587895879058791587925879358794587955879658797587985879958800588015880258803588045880558806588075880858809588105881158812588135881458815588165881758818588195882058821588225882358824588255882658827588285882958830588315883258833588345883558836588375883858839588405884158842588435884458845588465884758848588495885058851588525885358854588555885658857588585885958860588615886258863588645886558866588675886858869588705887158872588735887458875588765887758878588795888058881588825888358884588855888658887588885888958890588915889258893588945889558896588975889858899589005890158902589035890458905589065890758908589095891058911589125891358914589155891658917589185891958920589215892258923589245892558926589275892858929589305893158932589335893458935589365893758938589395894058941589425894358944589455894658947589485894958950589515895258953589545895558956589575895858959589605896158962589635896458965589665896758968589695897058971589725897358974589755897658977589785897958980589815898258983589845898558986589875898858989589905899158992589935899458995589965899758998589995900059001590025900359004590055900659007590085900959010590115901259013590145901559016590175901859019590205902159022590235902459025590265902759028590295903059031590325903359034590355903659037590385903959040590415904259043590445904559046590475904859049590505905159052590535905459055590565905759058590595906059061590625906359064590655906659067590685906959070590715907259073590745907559076590775907859079590805908159082590835908459085590865908759088590895909059091590925909359094590955909659097590985909959100591015910259103591045910559106591075910859109591105911159112591135911459115591165911759118591195912059121591225912359124591255912659127591285912959130591315913259133591345913559136591375913859139591405914159142591435914459145591465914759148591495915059151591525915359154591555915659157591585915959160591615916259163591645916559166591675916859169591705917159172591735917459175591765917759178591795918059181591825918359184591855918659187591885918959190591915919259193591945919559196591975919859199592005920159202592035920459205592065920759208592095921059211592125921359214592155921659217592185921959220592215922259223592245922559226592275922859229592305923159232592335923459235592365923759238592395924059241592425924359244592455924659247592485924959250592515925259253592545925559256592575925859259592605926159262592635926459265592665926759268592695927059271592725927359274592755927659277592785927959280592815928259283592845928559286592875928859289592905929159292592935929459295592965929759298592995930059301593025930359304593055930659307593085930959310593115931259313593145931559316593175931859319593205932159322593235932459325593265932759328593295933059331593325933359334593355933659337593385933959340593415934259343593445934559346593475934859349593505935159352593535935459355593565935759358593595936059361593625936359364593655936659367593685936959370593715937259373593745937559376593775937859379593805938159382593835938459385593865938759388593895939059391593925939359394593955939659397593985939959400594015940259403594045940559406594075940859409594105941159412594135941459415594165941759418594195942059421594225942359424594255942659427594285942959430594315943259433594345943559436594375943859439594405944159442594435944459445594465944759448594495945059451594525945359454594555945659457594585945959460594615946259463594645946559466594675946859469594705947159472594735947459475594765947759478594795948059481594825948359484594855948659487594885948959490594915949259493594945949559496594975949859499595005950159502595035950459505595065950759508595095951059511595125951359514595155951659517595185951959520595215952259523595245952559526595275952859529595305953159532595335953459535595365953759538595395954059541595425954359544595455954659547595485954959550595515955259553595545955559556595575955859559595605956159562595635956459565595665956759568595695957059571595725957359574595755957659577595785957959580595815958259583595845958559586595875958859589595905959159592595935959459595595965959759598595995960059601596025960359604596055960659607596085960959610596115961259613596145961559616596175961859619596205962159622596235962459625596265962759628596295963059631596325963359634596355963659637596385963959640596415964259643596445964559646596475964859649596505965159652596535965459655596565965759658596595966059661596625966359664596655966659667596685966959670596715967259673596745967559676596775967859679596805968159682596835968459685596865968759688596895969059691596925969359694596955969659697596985969959700597015970259703597045970559706597075970859709597105971159712597135971459715597165971759718597195972059721597225972359724597255972659727597285972959730597315973259733597345973559736597375973859739597405974159742597435974459745597465974759748597495975059751597525975359754597555975659757597585975959760597615976259763597645976559766597675976859769597705977159772597735977459775597765977759778597795978059781597825978359784597855978659787597885978959790597915979259793597945979559796597975979859799598005980159802598035980459805598065980759808598095981059811598125981359814598155981659817598185981959820598215982259823598245982559826598275982859829598305983159832598335983459835598365983759838598395984059841598425984359844598455984659847598485984959850598515985259853598545985559856598575985859859598605986159862598635986459865598665986759868598695987059871598725987359874598755987659877598785987959880598815988259883598845988559886598875988859889598905989159892598935989459895598965989759898598995990059901599025990359904599055990659907599085990959910599115991259913599145991559916599175991859919599205992159922599235992459925599265992759928599295993059931599325993359934599355993659937599385993959940599415994259943599445994559946599475994859949599505995159952599535995459955599565995759958599595996059961599625996359964599655996659967599685996959970599715997259973599745997559976599775997859979599805998159982599835998459985599865998759988599895999059991599925999359994599955999659997599985999960000600016000260003600046000560006600076000860009600106001160012600136001460015600166001760018600196002060021600226002360024600256002660027600286002960030600316003260033600346003560036600376003860039600406004160042600436004460045600466004760048600496005060051600526005360054600556005660057600586005960060600616006260063600646006560066600676006860069600706007160072600736007460075600766007760078600796008060081600826008360084600856008660087600886008960090600916009260093600946009560096600976009860099601006010160102601036010460105601066010760108601096011060111601126011360114601156011660117601186011960120601216012260123601246012560126601276012860129601306013160132601336013460135601366013760138601396014060141601426014360144601456014660147601486014960150601516015260153601546015560156601576015860159601606016160162601636016460165601666016760168601696017060171601726017360174601756017660177601786017960180601816018260183601846018560186601876018860189601906019160192601936019460195601966019760198601996020060201602026020360204602056020660207602086020960210602116021260213602146021560216602176021860219602206022160222602236022460225602266022760228602296023060231602326023360234602356023660237602386023960240602416024260243602446024560246602476024860249602506025160252602536025460255602566025760258602596026060261602626026360264602656026660267602686026960270602716027260273602746027560276602776027860279602806028160282602836028460285602866028760288602896029060291602926029360294602956029660297602986029960300603016030260303603046030560306603076030860309603106031160312603136031460315603166031760318603196032060321603226032360324603256032660327603286032960330603316033260333603346033560336603376033860339603406034160342603436034460345603466034760348603496035060351603526035360354603556035660357603586035960360603616036260363603646036560366603676036860369603706037160372603736037460375603766037760378603796038060381603826038360384603856038660387603886038960390603916039260393603946039560396603976039860399604006040160402604036040460405604066040760408604096041060411604126041360414604156041660417604186041960420604216042260423604246042560426604276042860429604306043160432604336043460435604366043760438604396044060441604426044360444604456044660447604486044960450604516045260453604546045560456604576045860459604606046160462604636046460465604666046760468604696047060471604726047360474604756047660477604786047960480604816048260483604846048560486604876048860489604906049160492604936049460495604966049760498604996050060501605026050360504605056050660507605086050960510605116051260513605146051560516605176051860519605206052160522605236052460525605266052760528605296053060531605326053360534605356053660537605386053960540605416054260543605446054560546605476054860549605506055160552605536055460555605566055760558605596056060561605626056360564605656056660567605686056960570605716057260573605746057560576605776057860579605806058160582605836058460585605866058760588605896059060591605926059360594605956059660597605986059960600606016060260603606046060560606606076060860609606106061160612606136061460615606166061760618606196062060621606226062360624606256062660627606286062960630606316063260633606346063560636606376063860639606406064160642606436064460645606466064760648606496065060651606526065360654606556065660657606586065960660606616066260663606646066560666606676066860669606706067160672606736067460675606766067760678606796068060681606826068360684606856068660687606886068960690606916069260693606946069560696606976069860699607006070160702607036070460705607066070760708607096071060711607126071360714607156071660717607186071960720607216072260723607246072560726607276072860729607306073160732607336073460735607366073760738607396074060741607426074360744607456074660747607486074960750607516075260753607546075560756607576075860759607606076160762607636076460765607666076760768607696077060771607726077360774607756077660777607786077960780607816078260783607846078560786607876078860789607906079160792607936079460795607966079760798607996080060801608026080360804608056080660807608086080960810608116081260813608146081560816608176081860819608206082160822608236082460825608266082760828608296083060831608326083360834608356083660837608386083960840608416084260843608446084560846608476084860849608506085160852608536085460855608566085760858608596086060861608626086360864608656086660867608686086960870608716087260873608746087560876608776087860879608806088160882608836088460885608866088760888608896089060891608926089360894608956089660897608986089960900609016090260903609046090560906609076090860909609106091160912609136091460915609166091760918609196092060921609226092360924609256092660927609286092960930609316093260933609346093560936609376093860939609406094160942609436094460945609466094760948609496095060951609526095360954609556095660957609586095960960609616096260963609646096560966609676096860969609706097160972609736097460975609766097760978609796098060981609826098360984609856098660987609886098960990609916099260993609946099560996609976099860999610006100161002610036100461005610066100761008610096101061011610126101361014610156101661017610186101961020610216102261023610246102561026610276102861029610306103161032610336103461035610366103761038610396104061041610426104361044610456104661047610486104961050610516105261053610546105561056610576105861059610606106161062610636106461065610666106761068610696107061071610726107361074610756107661077610786107961080610816108261083610846108561086610876108861089610906109161092610936109461095610966109761098610996110061101611026110361104611056110661107611086110961110611116111261113611146111561116611176111861119611206112161122611236112461125611266112761128611296113061131611326113361134611356113661137611386113961140611416114261143611446114561146611476114861149611506115161152611536115461155611566115761158611596116061161611626116361164611656116661167611686116961170611716117261173611746117561176611776117861179611806118161182611836118461185611866118761188611896119061191611926119361194611956119661197611986119961200612016120261203612046120561206612076120861209612106121161212612136121461215612166121761218612196122061221612226122361224612256122661227612286122961230612316123261233612346123561236612376123861239612406124161242612436124461245612466124761248612496125061251612526125361254612556125661257612586125961260612616126261263612646126561266612676126861269612706127161272612736127461275612766127761278612796128061281612826128361284612856128661287612886128961290612916129261293612946129561296612976129861299613006130161302613036130461305613066130761308613096131061311613126131361314613156131661317613186131961320613216132261323613246132561326613276132861329613306133161332613336133461335613366133761338613396134061341613426134361344613456134661347613486134961350613516135261353613546135561356613576135861359613606136161362613636136461365613666136761368613696137061371613726137361374613756137661377613786137961380613816138261383613846138561386613876138861389613906139161392613936139461395613966139761398613996140061401614026140361404614056140661407614086140961410614116141261413614146141561416614176141861419614206142161422614236142461425614266142761428614296143061431614326143361434614356143661437614386143961440614416144261443614446144561446614476144861449614506145161452614536145461455614566145761458614596146061461614626146361464614656146661467614686146961470614716147261473614746147561476614776147861479614806148161482614836148461485614866148761488614896149061491614926149361494614956149661497614986149961500615016150261503615046150561506615076150861509615106151161512615136151461515615166151761518615196152061521615226152361524615256152661527615286152961530615316153261533615346153561536615376153861539615406154161542615436154461545615466154761548615496155061551615526155361554615556155661557615586155961560615616156261563615646156561566615676156861569615706157161572615736157461575615766157761578615796158061581615826158361584615856158661587615886158961590615916159261593615946159561596615976159861599616006160161602616036160461605616066160761608616096161061611616126161361614616156161661617616186161961620616216162261623616246162561626616276162861629616306163161632616336163461635616366163761638616396164061641616426164361644616456164661647616486164961650616516165261653616546165561656616576165861659616606166161662616636166461665616666166761668616696167061671616726167361674616756167661677616786167961680616816168261683616846168561686616876168861689616906169161692616936169461695616966169761698616996170061701617026170361704617056170661707617086170961710617116171261713617146171561716617176171861719617206172161722617236172461725617266172761728617296173061731617326173361734617356173661737617386173961740617416174261743617446174561746617476174861749617506175161752617536175461755617566175761758617596176061761617626176361764617656176661767617686176961770617716177261773617746177561776617776177861779617806178161782617836178461785617866178761788617896179061791617926179361794617956179661797617986179961800618016180261803618046180561806618076180861809618106181161812618136181461815618166181761818618196182061821618226182361824618256182661827618286182961830618316183261833618346183561836618376183861839618406184161842618436184461845618466184761848618496185061851618526185361854618556185661857618586185961860618616186261863618646186561866618676186861869618706187161872618736187461875618766187761878618796188061881618826188361884618856188661887618886188961890618916189261893618946189561896618976189861899619006190161902619036190461905619066190761908619096191061911619126191361914619156191661917619186191961920619216192261923619246192561926619276192861929619306193161932619336193461935619366193761938619396194061941619426194361944619456194661947619486194961950619516195261953619546195561956619576195861959619606196161962619636196461965619666196761968619696197061971619726197361974619756197661977619786197961980619816198261983619846198561986619876198861989619906199161992619936199461995619966199761998619996200062001620026200362004620056200662007620086200962010620116201262013620146201562016620176201862019620206202162022620236202462025620266202762028620296203062031620326203362034620356203662037620386203962040620416204262043620446204562046620476204862049620506205162052620536205462055620566205762058620596206062061620626206362064620656206662067620686206962070620716207262073620746207562076620776207862079620806208162082620836208462085620866208762088620896209062091620926209362094620956209662097620986209962100621016210262103621046210562106621076210862109621106211162112621136211462115621166211762118621196212062121621226212362124621256212662127621286212962130621316213262133621346213562136621376213862139621406214162142621436214462145621466214762148621496215062151621526215362154621556215662157621586215962160621616216262163621646216562166621676216862169621706217162172621736217462175621766217762178621796218062181621826218362184621856218662187621886218962190621916219262193621946219562196621976219862199622006220162202622036220462205622066220762208622096221062211622126221362214622156221662217622186221962220622216222262223622246222562226622276222862229622306223162232622336223462235622366223762238622396224062241622426224362244622456224662247622486224962250622516225262253622546225562256622576225862259622606226162262622636226462265622666226762268622696227062271622726227362274622756227662277622786227962280622816228262283622846228562286622876228862289622906229162292622936229462295622966229762298622996230062301623026230362304623056230662307623086230962310623116231262313623146231562316623176231862319623206232162322623236232462325623266232762328623296233062331623326233362334623356233662337623386233962340623416234262343623446234562346623476234862349623506235162352623536235462355623566235762358623596236062361623626236362364623656236662367623686236962370623716237262373623746237562376623776237862379623806238162382623836238462385623866238762388623896239062391623926239362394623956239662397623986239962400624016240262403624046240562406624076240862409624106241162412624136241462415624166241762418624196242062421624226242362424624256242662427624286242962430624316243262433624346243562436624376243862439624406244162442624436244462445624466244762448624496245062451624526245362454624556245662457624586245962460624616246262463624646246562466624676246862469624706247162472624736247462475624766247762478624796248062481624826248362484624856248662487624886248962490624916249262493624946249562496624976249862499625006250162502625036250462505625066250762508625096251062511625126251362514625156251662517625186251962520625216252262523625246252562526625276252862529625306253162532625336253462535625366253762538625396254062541625426254362544625456254662547625486254962550625516255262553625546255562556625576255862559625606256162562625636256462565625666256762568625696257062571625726257362574625756257662577625786257962580625816258262583625846258562586625876258862589625906259162592625936259462595625966259762598625996260062601626026260362604626056260662607626086260962610626116261262613626146261562616626176261862619626206262162622626236262462625626266262762628626296263062631626326263362634626356263662637626386263962640626416264262643626446264562646626476264862649626506265162652626536265462655626566265762658626596266062661626626266362664626656266662667626686266962670626716267262673626746267562676626776267862679626806268162682626836268462685626866268762688626896269062691626926269362694626956269662697626986269962700627016270262703627046270562706627076270862709627106271162712627136271462715627166271762718627196272062721627226272362724627256272662727627286272962730627316273262733627346273562736627376273862739627406274162742627436274462745627466274762748627496275062751627526275362754627556275662757627586275962760627616276262763627646276562766627676276862769627706277162772627736277462775627766277762778627796278062781627826278362784627856278662787627886278962790627916279262793627946279562796627976279862799628006280162802628036280462805628066280762808628096281062811628126281362814628156281662817628186281962820628216282262823628246282562826628276282862829628306283162832628336283462835628366283762838628396284062841628426284362844628456284662847628486284962850628516285262853628546285562856628576285862859628606286162862628636286462865628666286762868628696287062871628726287362874628756287662877628786287962880628816288262883628846288562886628876288862889628906289162892628936289462895628966289762898628996290062901629026290362904629056290662907629086290962910629116291262913629146291562916629176291862919629206292162922629236292462925629266292762928629296293062931629326293362934629356293662937629386293962940629416294262943629446294562946629476294862949629506295162952629536295462955629566295762958629596296062961629626296362964629656296662967629686296962970629716297262973629746297562976629776297862979629806298162982629836298462985629866298762988629896299062991629926299362994629956299662997629986299963000630016300263003630046300563006630076300863009630106301163012630136301463015630166301763018630196302063021630226302363024630256302663027630286302963030630316303263033630346303563036630376303863039630406304163042630436304463045630466304763048630496305063051630526305363054630556305663057630586305963060630616306263063630646306563066630676306863069630706307163072630736307463075630766307763078630796308063081630826308363084630856308663087630886308963090630916309263093630946309563096630976309863099631006310163102631036310463105631066310763108631096311063111631126311363114631156311663117631186311963120631216312263123631246312563126631276312863129631306313163132631336313463135631366313763138631396314063141631426314363144631456314663147631486314963150631516315263153631546315563156631576315863159631606316163162631636316463165631666316763168631696317063171631726317363174631756317663177631786317963180631816318263183631846318563186631876318863189631906319163192631936319463195631966319763198631996320063201632026320363204632056320663207632086320963210632116321263213632146321563216632176321863219632206322163222632236322463225632266322763228632296323063231632326323363234632356323663237632386323963240632416324263243632446324563246632476324863249632506325163252632536325463255632566325763258632596326063261632626326363264632656326663267632686326963270632716327263273632746327563276632776327863279632806328163282632836328463285632866328763288632896329063291632926329363294632956329663297632986329963300633016330263303633046330563306633076330863309633106331163312633136331463315633166331763318633196332063321633226332363324633256332663327633286332963330633316333263333633346333563336633376333863339633406334163342633436334463345633466334763348633496335063351633526335363354633556335663357633586335963360633616336263363633646336563366633676336863369633706337163372633736337463375633766337763378633796338063381633826338363384633856338663387633886338963390633916339263393633946339563396633976339863399634006340163402634036340463405634066340763408634096341063411634126341363414634156341663417634186341963420634216342263423634246342563426634276342863429634306343163432634336343463435634366343763438634396344063441634426344363444634456344663447634486344963450634516345263453634546345563456634576345863459634606346163462634636346463465634666346763468634696347063471634726347363474634756347663477634786347963480634816348263483634846348563486634876348863489634906349163492634936349463495634966349763498634996350063501635026350363504635056350663507635086350963510635116351263513635146351563516635176351863519635206352163522635236352463525635266352763528635296353063531635326353363534635356353663537635386353963540635416354263543635446354563546635476354863549635506355163552635536355463555635566355763558635596356063561635626356363564635656356663567635686356963570635716357263573635746357563576635776357863579635806358163582635836358463585635866358763588635896359063591635926359363594635956359663597635986359963600636016360263603636046360563606636076360863609636106361163612636136361463615636166361763618636196362063621636226362363624636256362663627636286362963630636316363263633636346363563636636376363863639636406364163642636436364463645636466364763648636496365063651636526365363654636556365663657636586365963660636616366263663636646366563666636676366863669636706367163672636736367463675636766367763678636796368063681636826368363684636856368663687636886368963690636916369263693636946369563696636976369863699637006370163702637036370463705637066370763708637096371063711637126371363714637156371663717637186371963720637216372263723637246372563726637276372863729637306373163732637336373463735637366373763738637396374063741637426374363744637456374663747637486374963750637516375263753637546375563756637576375863759637606376163762637636376463765637666376763768637696377063771637726377363774637756377663777637786377963780637816378263783637846378563786637876378863789637906379163792637936379463795637966379763798637996380063801638026380363804638056380663807638086380963810638116381263813638146381563816638176381863819638206382163822638236382463825638266382763828638296383063831638326383363834638356383663837638386383963840638416384263843638446384563846638476384863849638506385163852638536385463855638566385763858638596386063861638626386363864638656386663867638686386963870638716387263873638746387563876638776387863879638806388163882638836388463885638866388763888638896389063891638926389363894638956389663897638986389963900639016390263903639046390563906639076390863909639106391163912639136391463915639166391763918639196392063921639226392363924639256392663927639286392963930639316393263933639346393563936639376393863939639406394163942639436394463945639466394763948639496395063951639526395363954639556395663957639586395963960639616396263963639646396563966639676396863969639706397163972639736397463975639766397763978639796398063981639826398363984639856398663987639886398963990639916399263993639946399563996639976399863999640006400164002640036400464005640066400764008640096401064011640126401364014640156401664017640186401964020640216402264023640246402564026640276402864029640306403164032640336403464035640366403764038640396404064041640426404364044640456404664047640486404964050640516405264053640546405564056640576405864059640606406164062640636406464065640666406764068640696407064071640726407364074640756407664077640786407964080640816408264083640846408564086640876408864089640906409164092640936409464095640966409764098640996410064101641026410364104641056410664107641086410964110641116411264113641146411564116641176411864119641206412164122641236412464125641266412764128641296413064131641326413364134641356413664137641386413964140641416414264143641446414564146641476414864149641506415164152641536415464155641566415764158641596416064161641626416364164641656416664167641686416964170641716417264173641746417564176641776417864179641806418164182641836418464185641866418764188641896419064191641926419364194641956419664197641986419964200642016420264203642046420564206642076420864209642106421164212642136421464215642166421764218642196422064221642226422364224642256422664227642286422964230642316423264233642346423564236642376423864239642406424164242642436424464245642466424764248642496425064251642526425364254642556425664257642586425964260642616426264263642646426564266642676426864269642706427164272642736427464275642766427764278642796428064281642826428364284642856428664287642886428964290642916429264293642946429564296642976429864299643006430164302643036430464305643066430764308643096431064311643126431364314643156431664317643186431964320643216432264323643246432564326643276432864329643306433164332643336433464335643366433764338643396434064341643426434364344643456434664347643486434964350643516435264353643546435564356643576435864359643606436164362643636436464365643666436764368643696437064371643726437364374643756437664377643786437964380643816438264383643846438564386643876438864389643906439164392643936439464395643966439764398643996440064401644026440364404644056440664407644086440964410644116441264413644146441564416644176441864419644206442164422644236442464425644266442764428644296443064431644326443364434644356443664437644386443964440644416444264443644446444564446644476444864449644506445164452644536445464455644566445764458644596446064461644626446364464644656446664467644686446964470644716447264473644746447564476644776447864479644806448164482644836448464485644866448764488644896449064491644926449364494644956449664497644986449964500645016450264503645046450564506645076450864509645106451164512645136451464515645166451764518645196452064521645226452364524645256452664527645286452964530645316453264533645346453564536645376453864539645406454164542645436454464545645466454764548645496455064551645526455364554645556455664557645586455964560645616456264563645646456564566645676456864569645706457164572645736457464575645766457764578645796458064581645826458364584645856458664587645886458964590645916459264593645946459564596645976459864599646006460164602646036460464605646066460764608646096461064611646126461364614646156461664617646186461964620646216462264623646246462564626646276462864629646306463164632646336463464635646366463764638646396464064641646426464364644646456464664647646486464964650646516465264653646546465564656646576465864659646606466164662646636466464665646666466764668646696467064671646726467364674646756467664677646786467964680646816468264683646846468564686646876468864689646906469164692646936469464695646966469764698646996470064701647026470364704647056470664707647086470964710647116471264713647146471564716647176471864719647206472164722647236472464725647266472764728647296473064731647326473364734647356473664737647386473964740647416474264743647446474564746647476474864749647506475164752647536475464755647566475764758647596476064761647626476364764647656476664767647686476964770647716477264773647746477564776647776477864779647806478164782647836478464785647866478764788647896479064791647926479364794647956479664797647986479964800648016480264803648046480564806648076480864809648106481164812648136481464815648166481764818648196482064821648226482364824648256482664827648286482964830648316483264833648346483564836648376483864839648406484164842648436484464845648466484764848648496485064851648526485364854648556485664857648586485964860648616486264863648646486564866648676486864869648706487164872648736487464875648766487764878648796488064881648826488364884648856488664887648886488964890648916489264893648946489564896648976489864899649006490164902649036490464905649066490764908649096491064911649126491364914649156491664917649186491964920649216492264923649246492564926649276492864929649306493164932649336493464935649366493764938649396494064941649426494364944649456494664947649486494964950649516495264953649546495564956649576495864959649606496164962649636496464965649666496764968649696497064971649726497364974649756497664977649786497964980649816498264983649846498564986649876498864989649906499164992649936499464995649966499764998649996500065001650026500365004650056500665007650086500965010650116501265013650146501565016650176501865019650206502165022650236502465025650266502765028650296503065031650326503365034650356503665037650386503965040650416504265043650446504565046650476504865049650506505165052650536505465055650566505765058650596506065061650626506365064650656506665067650686506965070650716507265073650746507565076650776507865079650806508165082650836508465085650866508765088650896509065091650926509365094650956509665097650986509965100651016510265103651046510565106651076510865109651106511165112651136511465115651166511765118651196512065121651226512365124651256512665127651286512965130651316513265133651346513565136651376513865139651406514165142651436514465145651466514765148651496515065151651526515365154651556515665157651586515965160651616516265163651646516565166651676516865169651706517165172651736517465175651766517765178651796518065181651826518365184651856518665187651886518965190651916519265193651946519565196651976519865199652006520165202652036520465205652066520765208652096521065211652126521365214652156521665217652186521965220652216522265223652246522565226652276522865229652306523165232652336523465235652366523765238652396524065241652426524365244652456524665247652486524965250652516525265253652546525565256652576525865259652606526165262652636526465265652666526765268652696527065271652726527365274652756527665277652786527965280652816528265283652846528565286652876528865289652906529165292652936529465295652966529765298652996530065301653026530365304653056530665307653086530965310653116531265313653146531565316653176531865319653206532165322653236532465325653266532765328653296533065331653326533365334653356533665337653386533965340653416534265343653446534565346653476534865349653506535165352653536535465355653566535765358653596536065361653626536365364653656536665367653686536965370653716537265373653746537565376653776537865379653806538165382653836538465385653866538765388653896539065391653926539365394653956539665397653986539965400654016540265403654046540565406654076540865409654106541165412654136541465415654166541765418654196542065421654226542365424654256542665427654286542965430654316543265433654346543565436654376543865439654406544165442654436544465445654466544765448654496545065451654526545365454654556545665457654586545965460654616546265463654646546565466654676546865469654706547165472654736547465475654766547765478654796548065481654826548365484654856548665487654886548965490654916549265493654946549565496654976549865499655006550165502655036550465505655066550765508655096551065511655126551365514655156551665517655186551965520655216552265523655246552565526655276552865529655306553165532655336553465535655366553765538655396554065541655426554365544655456554665547655486554965550655516555265553655546555565556655576555865559655606556165562655636556465565655666556765568655696557065571655726557365574655756557665577655786557965580655816558265583655846558565586655876558865589655906559165592655936559465595655966559765598655996560065601656026560365604656056560665607656086560965610656116561265613656146561565616656176561865619656206562165622656236562465625656266562765628656296563065631656326563365634656356563665637656386563965640656416564265643656446564565646656476564865649656506565165652656536565465655656566565765658656596566065661656626566365664656656566665667656686566965670656716567265673656746567565676656776567865679656806568165682656836568465685656866568765688656896569065691656926569365694656956569665697656986569965700657016570265703657046570565706657076570865709657106571165712657136571465715657166571765718657196572065721657226572365724657256572665727657286572965730657316573265733657346573565736657376573865739657406574165742657436574465745657466574765748657496575065751657526575365754657556575665757657586575965760657616576265763657646576565766657676576865769657706577165772657736577465775657766577765778657796578065781657826578365784657856578665787657886578965790657916579265793657946579565796657976579865799658006580165802658036580465805658066580765808658096581065811658126581365814658156581665817658186581965820658216582265823658246582565826658276582865829658306583165832658336583465835658366583765838658396584065841658426584365844658456584665847658486584965850658516585265853658546585565856658576585865859658606586165862658636586465865658666586765868658696587065871658726587365874658756587665877658786587965880658816588265883658846588565886658876588865889658906589165892658936589465895658966589765898658996590065901659026590365904659056590665907659086590965910659116591265913659146591565916659176591865919659206592165922659236592465925659266592765928659296593065931659326593365934659356593665937659386593965940659416594265943659446594565946659476594865949659506595165952659536595465955659566595765958659596596065961659626596365964659656596665967659686596965970659716597265973659746597565976659776597865979659806598165982659836598465985659866598765988659896599065991659926599365994659956599665997659986599966000660016600266003660046600566006660076600866009660106601166012660136601466015660166601766018660196602066021660226602366024660256602666027660286602966030660316603266033660346603566036660376603866039660406604166042660436604466045660466604766048660496605066051660526605366054660556605666057660586605966060660616606266063660646606566066660676606866069660706607166072660736607466075660766607766078660796608066081660826608366084660856608666087660886608966090660916609266093660946609566096660976609866099661006610166102661036610466105661066610766108661096611066111661126611366114661156611666117661186611966120661216612266123661246612566126661276612866129661306613166132661336613466135661366613766138661396614066141661426614366144661456614666147661486614966150661516615266153661546615566156661576615866159661606616166162661636616466165661666616766168661696617066171661726617366174661756617666177661786617966180661816618266183661846618566186661876618866189661906619166192661936619466195661966619766198661996620066201662026620366204662056620666207662086620966210662116621266213662146621566216662176621866219662206622166222662236622466225662266622766228662296623066231662326623366234662356623666237662386623966240662416624266243662446624566246662476624866249662506625166252662536625466255662566625766258662596626066261662626626366264662656626666267662686626966270662716627266273662746627566276662776627866279662806628166282662836628466285662866628766288662896629066291662926629366294662956629666297662986629966300663016630266303663046630566306663076630866309663106631166312663136631466315663166631766318663196632066321663226632366324663256632666327663286632966330663316633266333663346633566336663376633866339663406634166342663436634466345663466634766348663496635066351663526635366354663556635666357663586635966360663616636266363663646636566366663676636866369663706637166372663736637466375663766637766378663796638066381663826638366384663856638666387663886638966390663916639266393663946639566396663976639866399664006640166402664036640466405664066640766408664096641066411664126641366414664156641666417664186641966420664216642266423664246642566426664276642866429664306643166432664336643466435664366643766438664396644066441664426644366444664456644666447664486644966450664516645266453664546645566456664576645866459664606646166462664636646466465664666646766468664696647066471664726647366474664756647666477664786647966480664816648266483664846648566486664876648866489664906649166492664936649466495664966649766498664996650066501665026650366504665056650666507665086650966510665116651266513665146651566516665176651866519665206652166522665236652466525665266652766528665296653066531665326653366534665356653666537665386653966540665416654266543665446654566546665476654866549665506655166552665536655466555665566655766558665596656066561665626656366564665656656666567665686656966570665716657266573665746657566576665776657866579665806658166582665836658466585665866658766588665896659066591665926659366594665956659666597665986659966600666016660266603666046660566606666076660866609666106661166612666136661466615666166661766618666196662066621666226662366624666256662666627666286662966630666316663266633666346663566636666376663866639666406664166642666436664466645666466664766648666496665066651666526665366654666556665666657666586665966660666616666266663666646666566666666676666866669666706667166672666736667466675666766667766678666796668066681666826668366684666856668666687666886668966690666916669266693666946669566696666976669866699667006670166702667036670466705667066670766708667096671066711667126671366714667156671666717667186671966720667216672266723667246672566726667276672866729667306673166732667336673466735667366673766738667396674066741667426674366744667456674666747667486674966750667516675266753667546675566756667576675866759667606676166762667636676466765667666676766768667696677066771667726677366774667756677666777667786677966780667816678266783667846678566786667876678866789667906679166792667936679466795667966679766798667996680066801668026680366804668056680666807668086680966810668116681266813668146681566816668176681866819668206682166822668236682466825668266682766828668296683066831668326683366834668356683666837668386683966840668416684266843668446684566846668476684866849668506685166852668536685466855668566685766858668596686066861668626686366864668656686666867668686686966870668716687266873668746687566876668776687866879668806688166882668836688466885668866688766888668896689066891668926689366894668956689666897668986689966900669016690266903669046690566906669076690866909669106691166912669136691466915669166691766918669196692066921669226692366924669256692666927669286692966930669316693266933669346693566936669376693866939669406694166942669436694466945669466694766948669496695066951669526695366954669556695666957669586695966960669616696266963669646696566966669676696866969669706697166972669736697466975669766697766978669796698066981669826698366984669856698666987669886698966990669916699266993669946699566996669976699866999670006700167002670036700467005670066700767008670096701067011670126701367014670156701667017670186701967020670216702267023670246702567026670276702867029670306703167032670336703467035670366703767038670396704067041670426704367044670456704667047670486704967050670516705267053670546705567056670576705867059670606706167062670636706467065670666706767068670696707067071670726707367074670756707667077670786707967080670816708267083670846708567086670876708867089670906709167092670936709467095670966709767098670996710067101671026710367104671056710667107671086710967110671116711267113671146711567116671176711867119671206712167122671236712467125671266712767128671296713067131671326713367134671356713667137671386713967140671416714267143671446714567146671476714867149671506715167152671536715467155671566715767158671596716067161671626716367164671656716667167671686716967170671716717267173671746717567176671776717867179671806718167182671836718467185671866718767188671896719067191671926719367194671956719667197671986719967200672016720267203672046720567206672076720867209672106721167212672136721467215672166721767218672196722067221672226722367224672256722667227672286722967230672316723267233672346723567236672376723867239672406724167242672436724467245672466724767248672496725067251672526725367254672556725667257672586725967260672616726267263672646726567266672676726867269672706727167272672736727467275672766727767278672796728067281672826728367284672856728667287672886728967290672916729267293672946729567296672976729867299673006730167302673036730467305673066730767308673096731067311673126731367314673156731667317673186731967320673216732267323673246732567326673276732867329673306733167332673336733467335673366733767338673396734067341673426734367344673456734667347673486734967350673516735267353673546735567356673576735867359673606736167362673636736467365673666736767368673696737067371673726737367374673756737667377673786737967380673816738267383673846738567386673876738867389673906739167392673936739467395673966739767398673996740067401674026740367404674056740667407674086740967410674116741267413674146741567416674176741867419674206742167422674236742467425674266742767428674296743067431674326743367434674356743667437674386743967440674416744267443674446744567446674476744867449674506745167452674536745467455674566745767458674596746067461674626746367464674656746667467674686746967470674716747267473674746747567476674776747867479674806748167482674836748467485674866748767488674896749067491674926749367494674956749667497674986749967500675016750267503675046750567506675076750867509675106751167512675136751467515675166751767518675196752067521675226752367524675256752667527675286752967530675316753267533675346753567536675376753867539675406754167542675436754467545675466754767548675496755067551675526755367554675556755667557675586755967560675616756267563675646756567566675676756867569675706757167572675736757467575675766757767578675796758067581675826758367584675856758667587675886758967590675916759267593675946759567596675976759867599676006760167602676036760467605676066760767608676096761067611676126761367614676156761667617676186761967620676216762267623676246762567626676276762867629676306763167632676336763467635676366763767638676396764067641676426764367644676456764667647676486764967650676516765267653676546765567656676576765867659676606766167662676636766467665676666766767668676696767067671676726767367674676756767667677676786767967680676816768267683676846768567686676876768867689676906769167692676936769467695676966769767698676996770067701677026770367704677056770667707677086770967710677116771267713677146771567716677176771867719677206772167722677236772467725677266772767728677296773067731677326773367734677356773667737677386773967740677416774267743677446774567746677476774867749677506775167752677536775467755677566775767758677596776067761677626776367764677656776667767677686776967770677716777267773677746777567776677776777867779677806778167782677836778467785677866778767788677896779067791677926779367794677956779667797677986779967800678016780267803678046780567806678076780867809678106781167812678136781467815678166781767818678196782067821678226782367824678256782667827678286782967830678316783267833678346783567836678376783867839678406784167842678436784467845678466784767848678496785067851678526785367854678556785667857678586785967860678616786267863678646786567866678676786867869678706787167872678736787467875678766787767878678796788067881678826788367884678856788667887678886788967890678916789267893678946789567896678976789867899679006790167902679036790467905679066790767908679096791067911679126791367914679156791667917679186791967920679216792267923679246792567926679276792867929679306793167932679336793467935679366793767938679396794067941679426794367944679456794667947679486794967950679516795267953679546795567956679576795867959679606796167962679636796467965679666796767968679696797067971679726797367974679756797667977679786797967980679816798267983679846798567986679876798867989679906799167992679936799467995679966799767998679996800068001680026800368004680056800668007680086800968010680116801268013680146801568016680176801868019680206802168022680236802468025680266802768028680296803068031680326803368034680356803668037680386803968040680416804268043680446804568046680476804868049680506805168052680536805468055680566805768058680596806068061680626806368064680656806668067680686806968070680716807268073680746807568076680776807868079680806808168082680836808468085680866808768088680896809068091680926809368094680956809668097680986809968100681016810268103681046810568106681076810868109681106811168112681136811468115681166811768118681196812068121681226812368124681256812668127681286812968130681316813268133681346813568136681376813868139681406814168142681436814468145681466814768148681496815068151681526815368154681556815668157681586815968160681616816268163681646816568166681676816868169681706817168172681736817468175681766817768178681796818068181681826818368184681856818668187681886818968190681916819268193681946819568196681976819868199682006820168202682036820468205682066820768208682096821068211682126821368214682156821668217682186821968220682216822268223682246822568226682276822868229682306823168232682336823468235682366823768238682396824068241682426824368244682456824668247682486824968250682516825268253682546825568256682576825868259682606826168262682636826468265682666826768268682696827068271682726827368274682756827668277682786827968280682816828268283682846828568286682876828868289682906829168292682936829468295682966829768298682996830068301683026830368304683056830668307683086830968310683116831268313683146831568316683176831868319683206832168322683236832468325683266832768328683296833068331683326833368334683356833668337683386833968340683416834268343683446834568346683476834868349683506835168352683536835468355683566835768358683596836068361683626836368364683656836668367683686836968370683716837268373683746837568376683776837868379683806838168382683836838468385683866838768388683896839068391683926839368394683956839668397683986839968400684016840268403684046840568406684076840868409684106841168412684136841468415684166841768418684196842068421684226842368424684256842668427684286842968430684316843268433684346843568436684376843868439684406844168442684436844468445684466844768448684496845068451684526845368454684556845668457684586845968460684616846268463684646846568466684676846868469684706847168472684736847468475684766847768478684796848068481684826848368484684856848668487684886848968490684916849268493684946849568496684976849868499685006850168502685036850468505685066850768508685096851068511685126851368514685156851668517685186851968520685216852268523685246852568526685276852868529685306853168532685336853468535685366853768538685396854068541685426854368544685456854668547685486854968550685516855268553685546855568556685576855868559685606856168562685636856468565685666856768568685696857068571685726857368574685756857668577685786857968580685816858268583685846858568586685876858868589685906859168592685936859468595685966859768598685996860068601686026860368604686056860668607686086860968610686116861268613686146861568616686176861868619686206862168622686236862468625686266862768628686296863068631686326863368634686356863668637686386863968640686416864268643686446864568646686476864868649686506865168652686536865468655686566865768658686596866068661686626866368664686656866668667686686866968670686716867268673686746867568676686776867868679686806868168682686836868468685686866868768688686896869068691686926869368694686956869668697686986869968700687016870268703687046870568706687076870868709687106871168712687136871468715687166871768718687196872068721687226872368724687256872668727687286872968730687316873268733687346873568736687376873868739687406874168742687436874468745687466874768748687496875068751687526875368754687556875668757687586875968760687616876268763687646876568766687676876868769687706877168772687736877468775687766877768778687796878068781687826878368784687856878668787687886878968790687916879268793687946879568796687976879868799688006880168802688036880468805688066880768808688096881068811688126881368814688156881668817688186881968820688216882268823688246882568826688276882868829688306883168832688336883468835688366883768838688396884068841688426884368844688456884668847688486884968850688516885268853688546885568856688576885868859688606886168862688636886468865688666886768868688696887068871688726887368874688756887668877688786887968880688816888268883688846888568886688876888868889688906889168892688936889468895688966889768898688996890068901689026890368904689056890668907689086890968910689116891268913689146891568916689176891868919689206892168922689236892468925689266892768928689296893068931689326893368934689356893668937689386893968940689416894268943689446894568946689476894868949689506895168952689536895468955689566895768958689596896068961689626896368964689656896668967689686896968970689716897268973689746897568976689776897868979689806898168982689836898468985689866898768988689896899068991689926899368994689956899668997689986899969000690016900269003690046900569006690076900869009690106901169012690136901469015690166901769018690196902069021690226902369024690256902669027690286902969030690316903269033690346903569036690376903869039690406904169042690436904469045690466904769048690496905069051690526905369054690556905669057690586905969060690616906269063690646906569066690676906869069690706907169072690736907469075690766907769078690796908069081690826908369084690856908669087690886908969090690916909269093690946909569096690976909869099691006910169102691036910469105691066910769108691096911069111691126911369114691156911669117691186911969120691216912269123691246912569126691276912869129691306913169132691336913469135691366913769138691396914069141691426914369144691456914669147691486914969150691516915269153691546915569156691576915869159691606916169162691636916469165691666916769168691696917069171691726917369174691756917669177691786917969180691816918269183691846918569186691876918869189691906919169192691936919469195691966919769198691996920069201692026920369204692056920669207692086920969210692116921269213692146921569216692176921869219692206922169222692236922469225692266922769228692296923069231692326923369234692356923669237692386923969240692416924269243692446924569246692476924869249692506925169252692536925469255692566925769258692596926069261692626926369264692656926669267692686926969270692716927269273692746927569276692776927869279692806928169282692836928469285692866928769288692896929069291692926929369294692956929669297692986929969300693016930269303693046930569306693076930869309693106931169312693136931469315693166931769318693196932069321693226932369324693256932669327693286932969330693316933269333693346933569336693376933869339693406934169342693436934469345693466934769348693496935069351693526935369354693556935669357693586935969360693616936269363693646936569366693676936869369693706937169372693736937469375693766937769378693796938069381693826938369384693856938669387693886938969390693916939269393693946939569396693976939869399694006940169402694036940469405694066940769408694096941069411694126941369414694156941669417694186941969420694216942269423694246942569426694276942869429694306943169432694336943469435694366943769438694396944069441694426944369444694456944669447694486944969450694516945269453694546945569456694576945869459694606946169462694636946469465694666946769468694696947069471694726947369474694756947669477694786947969480694816948269483694846948569486694876948869489694906949169492694936949469495694966949769498694996950069501695026950369504695056950669507695086950969510695116951269513695146951569516695176951869519695206952169522695236952469525695266952769528695296953069531695326953369534695356953669537695386953969540695416954269543695446954569546695476954869549695506955169552695536955469555695566955769558695596956069561695626956369564695656956669567695686956969570695716957269573695746957569576695776957869579695806958169582695836958469585695866958769588695896959069591695926959369594695956959669597695986959969600696016960269603696046960569606696076960869609696106961169612696136961469615696166961769618696196962069621696226962369624696256962669627696286962969630696316963269633696346963569636696376963869639696406964169642696436964469645696466964769648696496965069651696526965369654696556965669657696586965969660696616966269663696646966569666696676966869669696706967169672696736967469675696766967769678696796968069681696826968369684696856968669687696886968969690696916969269693696946969569696696976969869699697006970169702697036970469705697066970769708697096971069711697126971369714697156971669717697186971969720697216972269723697246972569726697276972869729697306973169732697336973469735697366973769738697396974069741697426974369744697456974669747697486974969750697516975269753697546975569756697576975869759697606976169762697636976469765697666976769768697696977069771697726977369774697756977669777697786977969780697816978269783697846978569786697876978869789697906979169792697936979469795697966979769798697996980069801698026980369804698056980669807698086980969810698116981269813698146981569816698176981869819698206982169822698236982469825698266982769828698296983069831698326983369834698356983669837698386983969840698416984269843698446984569846698476984869849698506985169852698536985469855698566985769858698596986069861698626986369864698656986669867698686986969870698716987269873698746987569876698776987869879698806988169882698836988469885698866988769888698896989069891698926989369894698956989669897698986989969900699016990269903699046990569906699076990869909699106991169912699136991469915699166991769918699196992069921699226992369924699256992669927699286992969930699316993269933699346993569936699376993869939699406994169942699436994469945699466994769948699496995069951699526995369954699556995669957699586995969960699616996269963699646996569966699676996869969699706997169972699736997469975699766997769978699796998069981699826998369984699856998669987699886998969990699916999269993699946999569996699976999869999700007000170002700037000470005700067000770008700097001070011700127001370014700157001670017700187001970020700217002270023700247002570026700277002870029700307003170032700337003470035700367003770038700397004070041700427004370044700457004670047700487004970050700517005270053700547005570056700577005870059700607006170062700637006470065700667006770068700697007070071700727007370074700757007670077700787007970080700817008270083700847008570086700877008870089700907009170092700937009470095700967009770098700997010070101701027010370104701057010670107701087010970110701117011270113701147011570116701177011870119701207012170122701237012470125701267012770128701297013070131701327013370134701357013670137701387013970140701417014270143701447014570146701477014870149701507015170152701537015470155701567015770158701597016070161701627016370164701657016670167701687016970170701717017270173701747017570176701777017870179701807018170182701837018470185701867018770188701897019070191701927019370194701957019670197701987019970200702017020270203702047020570206702077020870209702107021170212702137021470215702167021770218702197022070221702227022370224702257022670227702287022970230702317023270233702347023570236702377023870239702407024170242702437024470245702467024770248702497025070251702527025370254702557025670257702587025970260702617026270263702647026570266702677026870269702707027170272702737027470275702767027770278702797028070281702827028370284702857028670287702887028970290702917029270293702947029570296702977029870299703007030170302703037030470305703067030770308703097031070311703127031370314703157031670317703187031970320703217032270323703247032570326703277032870329703307033170332703337033470335703367033770338703397034070341703427034370344703457034670347703487034970350703517035270353703547035570356703577035870359703607036170362703637036470365703667036770368703697037070371703727037370374703757037670377703787037970380703817038270383703847038570386703877038870389703907039170392703937039470395703967039770398703997040070401704027040370404704057040670407704087040970410704117041270413704147041570416704177041870419704207042170422704237042470425704267042770428704297043070431704327043370434704357043670437704387043970440704417044270443704447044570446704477044870449704507045170452704537045470455704567045770458704597046070461704627046370464704657046670467704687046970470704717047270473704747047570476704777047870479704807048170482704837048470485704867048770488704897049070491704927049370494704957049670497704987049970500705017050270503705047050570506705077050870509705107051170512705137051470515705167051770518705197052070521705227052370524705257052670527705287052970530705317053270533705347053570536705377053870539705407054170542705437054470545705467054770548705497055070551705527055370554705557055670557705587055970560705617056270563705647056570566705677056870569705707057170572705737057470575705767057770578705797058070581705827058370584705857058670587705887058970590705917059270593705947059570596705977059870599706007060170602706037060470605706067060770608706097061070611706127061370614706157061670617706187061970620706217062270623706247062570626706277062870629706307063170632706337063470635706367063770638706397064070641706427064370644706457064670647706487064970650706517065270653706547065570656706577065870659706607066170662706637066470665706667066770668706697067070671706727067370674706757067670677706787067970680706817068270683706847068570686706877068870689706907069170692706937069470695706967069770698706997070070701707027070370704707057070670707707087070970710707117071270713707147071570716707177071870719707207072170722707237072470725707267072770728707297073070731707327073370734707357073670737707387073970740707417074270743707447074570746707477074870749707507075170752707537075470755707567075770758707597076070761707627076370764707657076670767707687076970770707717077270773707747077570776707777077870779707807078170782707837078470785707867078770788707897079070791707927079370794707957079670797707987079970800708017080270803708047080570806708077080870809708107081170812708137081470815708167081770818708197082070821708227082370824708257082670827708287082970830708317083270833708347083570836708377083870839708407084170842708437084470845708467084770848708497085070851708527085370854708557085670857708587085970860708617086270863708647086570866708677086870869708707087170872708737087470875708767087770878708797088070881708827088370884708857088670887708887088970890708917089270893708947089570896708977089870899709007090170902709037090470905709067090770908709097091070911709127091370914709157091670917709187091970920709217092270923709247092570926709277092870929709307093170932709337093470935709367093770938709397094070941709427094370944709457094670947709487094970950709517095270953709547095570956709577095870959709607096170962709637096470965709667096770968709697097070971709727097370974709757097670977709787097970980709817098270983709847098570986709877098870989709907099170992709937099470995709967099770998709997100071001710027100371004710057100671007710087100971010710117101271013710147101571016710177101871019710207102171022710237102471025710267102771028710297103071031710327103371034710357103671037710387103971040710417104271043710447104571046710477104871049710507105171052710537105471055710567105771058710597106071061710627106371064710657106671067710687106971070710717107271073710747107571076710777107871079710807108171082710837108471085710867108771088710897109071091710927109371094710957109671097710987109971100711017110271103711047110571106711077110871109711107111171112711137111471115711167111771118711197112071121711227112371124711257112671127711287112971130711317113271133711347113571136711377113871139711407114171142711437114471145711467114771148711497115071151711527115371154711557115671157711587115971160711617116271163711647116571166711677116871169711707117171172711737117471175711767117771178711797118071181711827118371184711857118671187711887118971190711917119271193711947119571196711977119871199712007120171202712037120471205712067120771208712097121071211712127121371214712157121671217712187121971220712217122271223712247122571226712277122871229712307123171232712337123471235712367123771238712397124071241712427124371244712457124671247712487124971250712517125271253712547125571256712577125871259712607126171262712637126471265712667126771268712697127071271712727127371274712757127671277712787127971280712817128271283712847128571286712877128871289712907129171292712937129471295712967129771298712997130071301713027130371304713057130671307713087130971310713117131271313713147131571316713177131871319713207132171322713237132471325713267132771328713297133071331713327133371334713357133671337713387133971340713417134271343713447134571346713477134871349713507135171352713537135471355713567135771358713597136071361713627136371364713657136671367713687136971370713717137271373713747137571376713777137871379713807138171382713837138471385713867138771388713897139071391713927139371394713957139671397713987139971400714017140271403714047140571406714077140871409714107141171412714137141471415714167141771418714197142071421714227142371424714257142671427714287142971430714317143271433714347143571436714377143871439714407144171442714437144471445714467144771448714497145071451714527145371454714557145671457714587145971460714617146271463714647146571466714677146871469714707147171472714737147471475714767147771478714797148071481714827148371484714857148671487714887148971490714917149271493714947149571496714977149871499715007150171502715037150471505715067150771508715097151071511715127151371514715157151671517715187151971520715217152271523715247152571526715277152871529715307153171532715337153471535715367153771538715397154071541715427154371544715457154671547715487154971550715517155271553715547155571556715577155871559715607156171562715637156471565715667156771568715697157071571715727157371574715757157671577715787157971580715817158271583715847158571586715877158871589715907159171592715937159471595715967159771598715997160071601716027160371604716057160671607716087160971610716117161271613716147161571616716177161871619716207162171622716237162471625716267162771628716297163071631716327163371634716357163671637716387163971640716417164271643716447164571646716477164871649716507165171652716537165471655716567165771658716597166071661716627166371664716657166671667716687166971670716717167271673716747167571676716777167871679716807168171682716837168471685716867168771688716897169071691716927169371694716957169671697716987169971700717017170271703717047170571706717077170871709717107171171712717137171471715717167171771718717197172071721717227172371724717257172671727717287172971730717317173271733717347173571736717377173871739717407174171742717437174471745717467174771748717497175071751717527175371754717557175671757717587175971760717617176271763717647176571766717677176871769717707177171772717737177471775717767177771778717797178071781717827178371784717857178671787717887178971790717917179271793717947179571796717977179871799718007180171802718037180471805718067180771808718097181071811718127181371814718157181671817718187181971820718217182271823718247182571826718277182871829718307183171832718337183471835718367183771838718397184071841718427184371844718457184671847718487184971850718517185271853718547185571856718577185871859718607186171862718637186471865718667186771868718697187071871718727187371874718757187671877718787187971880718817188271883718847188571886718877188871889718907189171892718937189471895718967189771898718997190071901719027190371904719057190671907719087190971910719117191271913719147191571916719177191871919719207192171922719237192471925719267192771928719297193071931719327193371934719357193671937719387193971940719417194271943719447194571946719477194871949719507195171952719537195471955719567195771958719597196071961719627196371964719657196671967719687196971970719717197271973719747197571976719777197871979719807198171982719837198471985719867198771988719897199071991719927199371994719957199671997719987199972000720017200272003720047200572006720077200872009720107201172012720137201472015720167201772018720197202072021720227202372024720257202672027720287202972030720317203272033720347203572036720377203872039720407204172042720437204472045720467204772048720497205072051720527205372054720557205672057720587205972060720617206272063720647206572066720677206872069720707207172072720737207472075720767207772078720797208072081720827208372084720857208672087720887208972090720917209272093720947209572096720977209872099721007210172102721037210472105721067210772108721097211072111721127211372114721157211672117721187211972120721217212272123721247212572126721277212872129721307213172132721337213472135721367213772138721397214072141721427214372144721457214672147721487214972150721517215272153721547215572156721577215872159721607216172162721637216472165721667216772168721697217072171721727217372174721757217672177721787217972180721817218272183721847218572186721877218872189721907219172192721937219472195721967219772198721997220072201722027220372204722057220672207722087220972210722117221272213722147221572216722177221872219722207222172222722237222472225722267222772228722297223072231722327223372234722357223672237722387223972240722417224272243722447224572246722477224872249722507225172252722537225472255722567225772258722597226072261722627226372264722657226672267722687226972270722717227272273722747227572276722777227872279722807228172282722837228472285722867228772288722897229072291722927229372294722957229672297722987229972300723017230272303723047230572306723077230872309723107231172312723137231472315723167231772318723197232072321723227232372324723257232672327723287232972330723317233272333723347233572336723377233872339723407234172342723437234472345723467234772348723497235072351723527235372354723557235672357723587235972360723617236272363723647236572366723677236872369723707237172372723737237472375723767237772378723797238072381723827238372384723857238672387723887238972390723917239272393723947239572396723977239872399724007240172402724037240472405724067240772408724097241072411724127241372414724157241672417724187241972420724217242272423724247242572426724277242872429724307243172432724337243472435724367243772438724397244072441724427244372444724457244672447724487244972450724517245272453724547245572456724577245872459724607246172462724637246472465724667246772468724697247072471724727247372474724757247672477724787247972480724817248272483724847248572486724877248872489724907249172492724937249472495724967249772498724997250072501725027250372504725057250672507725087250972510725117251272513725147251572516725177251872519725207252172522725237252472525725267252772528725297253072531725327253372534725357253672537725387253972540725417254272543725447254572546725477254872549725507255172552725537255472555725567255772558725597256072561725627256372564725657256672567725687256972570725717257272573725747257572576725777257872579725807258172582725837258472585725867258772588725897259072591725927259372594725957259672597725987259972600726017260272603726047260572606726077260872609726107261172612726137261472615726167261772618726197262072621726227262372624726257262672627726287262972630726317263272633726347263572636726377263872639726407264172642726437264472645726467264772648726497265072651726527265372654726557265672657726587265972660726617266272663726647266572666726677266872669726707267172672726737267472675726767267772678726797268072681726827268372684726857268672687726887268972690726917269272693726947269572696726977269872699727007270172702727037270472705727067270772708727097271072711727127271372714727157271672717727187271972720727217272272723727247272572726727277272872729727307273172732727337273472735727367273772738727397274072741727427274372744727457274672747727487274972750727517275272753727547275572756727577275872759727607276172762727637276472765727667276772768727697277072771727727277372774727757277672777727787277972780727817278272783727847278572786727877278872789727907279172792727937279472795727967279772798727997280072801728027280372804728057280672807728087280972810728117281272813728147281572816728177281872819728207282172822728237282472825728267282772828728297283072831728327283372834728357283672837728387283972840728417284272843728447284572846728477284872849728507285172852728537285472855728567285772858728597286072861728627286372864728657286672867728687286972870728717287272873728747287572876728777287872879728807288172882728837288472885728867288772888728897289072891728927289372894728957289672897728987289972900729017290272903729047290572906729077290872909729107291172912729137291472915729167291772918729197292072921729227292372924729257292672927729287292972930729317293272933729347293572936729377293872939729407294172942729437294472945729467294772948729497295072951729527295372954729557295672957729587295972960729617296272963729647296572966729677296872969729707297172972729737297472975729767297772978729797298072981729827298372984729857298672987729887298972990729917299272993729947299572996729977299872999730007300173002730037300473005730067300773008730097301073011730127301373014730157301673017730187301973020730217302273023730247302573026730277302873029730307303173032730337303473035730367303773038730397304073041730427304373044730457304673047730487304973050730517305273053730547305573056730577305873059730607306173062730637306473065730667306773068730697307073071730727307373074730757307673077730787307973080730817308273083730847308573086730877308873089730907309173092730937309473095730967309773098730997310073101731027310373104731057310673107731087310973110731117311273113731147311573116731177311873119731207312173122731237312473125731267312773128731297313073131731327313373134731357313673137731387313973140731417314273143731447314573146731477314873149731507315173152731537315473155731567315773158731597316073161731627316373164731657316673167731687316973170731717317273173731747317573176731777317873179731807318173182731837318473185731867318773188731897319073191731927319373194731957319673197731987319973200732017320273203732047320573206732077320873209732107321173212732137321473215732167321773218732197322073221732227322373224732257322673227732287322973230732317323273233732347323573236732377323873239732407324173242732437324473245732467324773248732497325073251732527325373254732557325673257732587325973260732617326273263732647326573266732677326873269732707327173272732737327473275732767327773278732797328073281732827328373284732857328673287732887328973290732917329273293732947329573296732977329873299733007330173302733037330473305733067330773308733097331073311733127331373314733157331673317733187331973320733217332273323733247332573326733277332873329733307333173332733337333473335733367333773338733397334073341733427334373344733457334673347733487334973350733517335273353733547335573356733577335873359733607336173362733637336473365733667336773368733697337073371733727337373374733757337673377733787337973380733817338273383733847338573386733877338873389733907339173392733937339473395733967339773398733997340073401734027340373404734057340673407734087340973410734117341273413734147341573416734177341873419734207342173422734237342473425734267342773428734297343073431734327343373434734357343673437734387343973440734417344273443734447344573446734477344873449734507345173452734537345473455734567345773458734597346073461734627346373464734657346673467734687346973470734717347273473734747347573476734777347873479734807348173482734837348473485734867348773488734897349073491734927349373494734957349673497734987349973500735017350273503735047350573506735077350873509735107351173512735137351473515735167351773518735197352073521735227352373524735257352673527735287352973530735317353273533735347353573536735377353873539735407354173542735437354473545735467354773548735497355073551735527355373554735557355673557735587355973560735617356273563735647356573566735677356873569735707357173572735737357473575735767357773578735797358073581735827358373584735857358673587735887358973590735917359273593735947359573596735977359873599736007360173602736037360473605736067360773608736097361073611736127361373614736157361673617736187361973620736217362273623736247362573626736277362873629736307363173632736337363473635736367363773638736397364073641736427364373644736457364673647736487364973650736517365273653736547365573656736577365873659736607366173662736637366473665736667366773668736697367073671736727367373674736757367673677736787367973680736817368273683736847368573686736877368873689736907369173692736937369473695736967369773698736997370073701737027370373704737057370673707737087370973710737117371273713737147371573716737177371873719737207372173722737237372473725737267372773728737297373073731737327373373734737357373673737737387373973740737417374273743737447374573746737477374873749737507375173752737537375473755737567375773758737597376073761737627376373764737657376673767737687376973770737717377273773737747377573776737777377873779737807378173782737837378473785737867378773788737897379073791737927379373794737957379673797737987379973800738017380273803738047380573806738077380873809738107381173812738137381473815738167381773818738197382073821738227382373824738257382673827738287382973830738317383273833738347383573836738377383873839738407384173842738437384473845738467384773848738497385073851738527385373854738557385673857738587385973860738617386273863738647386573866738677386873869738707387173872738737387473875738767387773878738797388073881738827388373884738857388673887738887388973890738917389273893738947389573896738977389873899739007390173902739037390473905739067390773908739097391073911739127391373914739157391673917739187391973920739217392273923739247392573926739277392873929739307393173932739337393473935739367393773938739397394073941739427394373944739457394673947739487394973950739517395273953739547395573956739577395873959739607396173962739637396473965739667396773968739697397073971739727397373974739757397673977739787397973980739817398273983739847398573986739877398873989739907399173992739937399473995739967399773998739997400074001740027400374004740057400674007740087400974010740117401274013740147401574016740177401874019740207402174022740237402474025740267402774028740297403074031740327403374034740357403674037740387403974040740417404274043740447404574046740477404874049740507405174052740537405474055740567405774058740597406074061740627406374064740657406674067740687406974070740717407274073740747407574076740777407874079740807408174082740837408474085740867408774088740897409074091740927409374094740957409674097740987409974100741017410274103741047410574106741077410874109741107411174112741137411474115741167411774118741197412074121741227412374124741257412674127741287412974130741317413274133741347413574136741377413874139741407414174142741437414474145741467414774148741497415074151741527415374154741557415674157741587415974160741617416274163741647416574166741677416874169741707417174172741737417474175741767417774178741797418074181741827418374184741857418674187741887418974190741917419274193741947419574196741977419874199742007420174202742037420474205742067420774208742097421074211742127421374214742157421674217742187421974220742217422274223742247422574226742277422874229742307423174232742337423474235742367423774238742397424074241742427424374244742457424674247742487424974250742517425274253742547425574256742577425874259742607426174262742637426474265742667426774268742697427074271742727427374274742757427674277742787427974280742817428274283742847428574286742877428874289742907429174292742937429474295742967429774298742997430074301743027430374304743057430674307743087430974310743117431274313743147431574316743177431874319743207432174322743237432474325743267432774328743297433074331743327433374334743357433674337743387433974340743417434274343743447434574346743477434874349743507435174352743537435474355743567435774358743597436074361743627436374364743657436674367743687436974370743717437274373743747437574376743777437874379743807438174382743837438474385743867438774388743897439074391743927439374394743957439674397743987439974400744017440274403744047440574406744077440874409744107441174412744137441474415744167441774418744197442074421744227442374424744257442674427744287442974430744317443274433744347443574436744377443874439744407444174442744437444474445744467444774448744497445074451744527445374454744557445674457744587445974460744617446274463744647446574466744677446874469744707447174472744737447474475744767447774478744797448074481744827448374484744857448674487744887448974490744917449274493744947449574496744977449874499745007450174502745037450474505745067450774508745097451074511745127451374514745157451674517745187451974520745217452274523745247452574526745277452874529745307453174532745337453474535745367453774538745397454074541745427454374544745457454674547745487454974550745517455274553745547455574556745577455874559745607456174562745637456474565745667456774568745697457074571745727457374574745757457674577745787457974580745817458274583745847458574586745877458874589745907459174592745937459474595745967459774598745997460074601746027460374604746057460674607746087460974610746117461274613746147461574616746177461874619746207462174622746237462474625746267462774628746297463074631746327463374634746357463674637746387463974640746417464274643746447464574646746477464874649746507465174652746537465474655746567465774658746597466074661746627466374664746657466674667746687466974670746717467274673746747467574676746777467874679746807468174682746837468474685746867468774688746897469074691746927469374694746957469674697746987469974700747017470274703747047470574706747077470874709747107471174712747137471474715747167471774718747197472074721747227472374724747257472674727747287472974730747317473274733747347473574736747377473874739747407474174742747437474474745747467474774748747497475074751747527475374754747557475674757747587475974760747617476274763747647476574766747677476874769747707477174772747737477474775747767477774778747797478074781747827478374784747857478674787747887478974790747917479274793747947479574796747977479874799748007480174802748037480474805748067480774808748097481074811748127481374814748157481674817748187481974820748217482274823748247482574826748277482874829748307483174832748337483474835748367483774838748397484074841748427484374844748457484674847748487484974850748517485274853748547485574856748577485874859748607486174862748637486474865748667486774868748697487074871748727487374874748757487674877748787487974880748817488274883748847488574886748877488874889748907489174892748937489474895748967489774898748997490074901749027490374904749057490674907749087490974910749117491274913749147491574916749177491874919749207492174922749237492474925749267492774928749297493074931749327493374934749357493674937749387493974940749417494274943749447494574946749477494874949749507495174952749537495474955749567495774958749597496074961749627496374964749657496674967749687496974970749717497274973749747497574976749777497874979749807498174982749837498474985749867498774988749897499074991749927499374994749957499674997749987499975000750017500275003750047500575006750077500875009750107501175012750137501475015750167501775018750197502075021750227502375024750257502675027750287502975030750317503275033750347503575036750377503875039750407504175042750437504475045750467504775048750497505075051750527505375054750557505675057750587505975060750617506275063750647506575066750677506875069750707507175072750737507475075750767507775078750797508075081750827508375084750857508675087750887508975090750917509275093750947509575096750977509875099751007510175102751037510475105751067510775108751097511075111751127511375114751157511675117751187511975120751217512275123751247512575126751277512875129751307513175132751337513475135751367513775138751397514075141751427514375144751457514675147751487514975150751517515275153751547515575156751577515875159751607516175162751637516475165751667516775168751697517075171751727517375174751757517675177751787517975180751817518275183751847518575186751877518875189751907519175192751937519475195751967519775198751997520075201752027520375204752057520675207752087520975210752117521275213752147521575216752177521875219752207522175222752237522475225752267522775228752297523075231752327523375234752357523675237752387523975240752417524275243752447524575246752477524875249752507525175252752537525475255752567525775258752597526075261752627526375264752657526675267752687526975270752717527275273752747527575276752777527875279752807528175282752837528475285752867528775288752897529075291752927529375294752957529675297752987529975300753017530275303753047530575306753077530875309753107531175312753137531475315753167531775318753197532075321753227532375324753257532675327753287532975330753317533275333753347533575336753377533875339753407534175342753437534475345753467534775348753497535075351753527535375354753557535675357753587535975360753617536275363753647536575366753677536875369753707537175372753737537475375753767537775378753797538075381753827538375384753857538675387753887538975390753917539275393753947539575396753977539875399754007540175402754037540475405754067540775408754097541075411754127541375414754157541675417754187541975420754217542275423754247542575426754277542875429754307543175432754337543475435754367543775438754397544075441754427544375444754457544675447754487544975450754517545275453754547545575456754577545875459754607546175462754637546475465754667546775468754697547075471754727547375474754757547675477754787547975480754817548275483754847548575486754877548875489754907549175492754937549475495754967549775498754997550075501755027550375504755057550675507755087550975510755117551275513755147551575516755177551875519755207552175522755237552475525755267552775528755297553075531755327553375534755357553675537755387553975540755417554275543755447554575546755477554875549755507555175552755537555475555755567555775558755597556075561755627556375564755657556675567755687556975570755717557275573755747557575576755777557875579755807558175582755837558475585755867558775588755897559075591755927559375594755957559675597755987559975600756017560275603756047560575606756077560875609756107561175612756137561475615756167561775618756197562075621756227562375624756257562675627756287562975630756317563275633756347563575636756377563875639756407564175642756437564475645756467564775648756497565075651756527565375654756557565675657756587565975660756617566275663756647566575666756677566875669756707567175672756737567475675756767567775678756797568075681756827568375684756857568675687756887568975690756917569275693756947569575696756977569875699757007570175702757037570475705757067570775708757097571075711757127571375714757157571675717757187571975720757217572275723757247572575726757277572875729757307573175732757337573475735757367573775738757397574075741757427574375744757457574675747757487574975750757517575275753757547575575756757577575875759757607576175762757637576475765757667576775768757697577075771757727577375774757757577675777757787577975780757817578275783757847578575786757877578875789757907579175792757937579475795757967579775798757997580075801758027580375804758057580675807758087580975810758117581275813758147581575816758177581875819758207582175822758237582475825758267582775828758297583075831758327583375834758357583675837758387583975840758417584275843758447584575846758477584875849758507585175852758537585475855758567585775858758597586075861758627586375864758657586675867758687586975870758717587275873758747587575876758777587875879758807588175882758837588475885758867588775888758897589075891758927589375894758957589675897758987589975900759017590275903759047590575906759077590875909759107591175912759137591475915759167591775918759197592075921759227592375924759257592675927759287592975930759317593275933759347593575936759377593875939759407594175942759437594475945759467594775948759497595075951759527595375954759557595675957759587595975960759617596275963759647596575966759677596875969759707597175972759737597475975759767597775978759797598075981759827598375984759857598675987759887598975990759917599275993759947599575996759977599875999760007600176002760037600476005760067600776008760097601076011760127601376014760157601676017760187601976020760217602276023760247602576026760277602876029760307603176032760337603476035760367603776038760397604076041760427604376044760457604676047760487604976050760517605276053760547605576056760577605876059760607606176062760637606476065760667606776068760697607076071760727607376074760757607676077760787607976080760817608276083760847608576086760877608876089760907609176092760937609476095760967609776098760997610076101761027610376104761057610676107761087610976110761117611276113761147611576116761177611876119761207612176122761237612476125761267612776128761297613076131761327613376134761357613676137761387613976140761417614276143761447614576146761477614876149761507615176152761537615476155761567615776158761597616076161761627616376164761657616676167761687616976170761717617276173761747617576176761777617876179761807618176182761837618476185761867618776188761897619076191761927619376194761957619676197761987619976200762017620276203762047620576206762077620876209762107621176212762137621476215762167621776218762197622076221762227622376224762257622676227762287622976230762317623276233762347623576236762377623876239762407624176242762437624476245762467624776248762497625076251762527625376254762557625676257762587625976260762617626276263762647626576266762677626876269762707627176272762737627476275762767627776278762797628076281762827628376284762857628676287762887628976290762917629276293762947629576296762977629876299763007630176302763037630476305763067630776308763097631076311763127631376314763157631676317763187631976320763217632276323763247632576326763277632876329763307633176332763337633476335763367633776338763397634076341763427634376344763457634676347763487634976350763517635276353763547635576356763577635876359763607636176362763637636476365763667636776368763697637076371763727637376374763757637676377763787637976380763817638276383763847638576386763877638876389763907639176392763937639476395763967639776398763997640076401764027640376404764057640676407764087640976410764117641276413764147641576416764177641876419764207642176422764237642476425764267642776428764297643076431764327643376434764357643676437764387643976440764417644276443764447644576446764477644876449764507645176452764537645476455764567645776458764597646076461764627646376464764657646676467764687646976470764717647276473764747647576476764777647876479764807648176482764837648476485764867648776488764897649076491764927649376494764957649676497764987649976500765017650276503765047650576506765077650876509765107651176512765137651476515765167651776518765197652076521765227652376524765257652676527765287652976530765317653276533765347653576536765377653876539765407654176542765437654476545765467654776548765497655076551765527655376554765557655676557765587655976560765617656276563765647656576566765677656876569765707657176572765737657476575765767657776578765797658076581765827658376584765857658676587765887658976590765917659276593765947659576596765977659876599766007660176602766037660476605766067660776608766097661076611766127661376614766157661676617766187661976620766217662276623766247662576626766277662876629766307663176632766337663476635766367663776638766397664076641766427664376644766457664676647766487664976650766517665276653766547665576656766577665876659766607666176662766637666476665766667666776668766697667076671766727667376674766757667676677766787667976680766817668276683766847668576686766877668876689766907669176692766937669476695766967669776698766997670076701767027670376704767057670676707767087670976710767117671276713767147671576716767177671876719767207672176722767237672476725767267672776728767297673076731767327673376734767357673676737767387673976740767417674276743767447674576746767477674876749767507675176752767537675476755767567675776758767597676076761767627676376764767657676676767767687676976770767717677276773767747677576776767777677876779767807678176782767837678476785767867678776788767897679076791767927679376794767957679676797767987679976800768017680276803768047680576806768077680876809768107681176812768137681476815768167681776818768197682076821768227682376824768257682676827768287682976830768317683276833768347683576836768377683876839768407684176842768437684476845768467684776848768497685076851768527685376854768557685676857768587685976860768617686276863768647686576866768677686876869768707687176872768737687476875768767687776878768797688076881768827688376884768857688676887768887688976890768917689276893768947689576896768977689876899769007690176902769037690476905769067690776908769097691076911769127691376914769157691676917769187691976920769217692276923769247692576926769277692876929769307693176932769337693476935769367693776938769397694076941769427694376944769457694676947769487694976950769517695276953769547695576956769577695876959769607696176962769637696476965769667696776968769697697076971769727697376974769757697676977769787697976980769817698276983769847698576986769877698876989769907699176992769937699476995769967699776998769997700077001770027700377004770057700677007770087700977010770117701277013770147701577016770177701877019770207702177022770237702477025770267702777028770297703077031770327703377034770357703677037770387703977040770417704277043770447704577046770477704877049770507705177052770537705477055770567705777058770597706077061770627706377064770657706677067770687706977070770717707277073770747707577076770777707877079770807708177082770837708477085770867708777088770897709077091770927709377094770957709677097770987709977100771017710277103771047710577106771077710877109771107711177112771137711477115771167711777118771197712077121771227712377124771257712677127771287712977130771317713277133771347713577136771377713877139771407714177142771437714477145771467714777148771497715077151771527715377154771557715677157771587715977160771617716277163771647716577166771677716877169771707717177172771737717477175771767717777178771797718077181771827718377184771857718677187771887718977190771917719277193771947719577196771977719877199772007720177202772037720477205772067720777208772097721077211772127721377214772157721677217772187721977220772217722277223772247722577226772277722877229772307723177232772337723477235772367723777238772397724077241772427724377244772457724677247772487724977250772517725277253772547725577256772577725877259772607726177262772637726477265772667726777268772697727077271772727727377274772757727677277772787727977280772817728277283772847728577286772877728877289772907729177292772937729477295772967729777298772997730077301773027730377304773057730677307773087730977310773117731277313773147731577316773177731877319773207732177322773237732477325773267732777328773297733077331773327733377334773357733677337773387733977340773417734277343773447734577346773477734877349773507735177352773537735477355773567735777358773597736077361773627736377364773657736677367773687736977370773717737277373773747737577376773777737877379773807738177382773837738477385773867738777388773897739077391773927739377394773957739677397773987739977400774017740277403774047740577406774077740877409774107741177412774137741477415774167741777418774197742077421774227742377424774257742677427774287742977430774317743277433774347743577436774377743877439774407744177442774437744477445774467744777448774497745077451774527745377454774557745677457774587745977460774617746277463774647746577466774677746877469774707747177472774737747477475774767747777478774797748077481774827748377484774857748677487774887748977490774917749277493774947749577496774977749877499775007750177502775037750477505775067750777508775097751077511775127751377514775157751677517775187751977520775217752277523775247752577526775277752877529775307753177532775337753477535775367753777538775397754077541775427754377544775457754677547775487754977550775517755277553775547755577556775577755877559775607756177562775637756477565775667756777568775697757077571775727757377574775757757677577775787757977580775817758277583775847758577586775877758877589775907759177592775937759477595775967759777598775997760077601776027760377604776057760677607776087760977610776117761277613776147761577616776177761877619776207762177622776237762477625776267762777628776297763077631776327763377634776357763677637776387763977640776417764277643776447764577646776477764877649776507765177652776537765477655776567765777658776597766077661776627766377664776657766677667776687766977670776717767277673776747767577676776777767877679776807768177682776837768477685776867768777688776897769077691776927769377694776957769677697776987769977700777017770277703777047770577706777077770877709777107771177712777137771477715777167771777718777197772077721777227772377724777257772677727777287772977730777317773277733777347773577736777377773877739777407774177742777437774477745777467774777748777497775077751777527775377754777557775677757777587775977760777617776277763777647776577766777677776877769777707777177772777737777477775777767777777778777797778077781777827778377784777857778677787777887778977790777917779277793777947779577796777977779877799778007780177802778037780477805778067780777808778097781077811778127781377814778157781677817778187781977820778217782277823778247782577826778277782877829778307783177832778337783477835778367783777838778397784077841778427784377844778457784677847778487784977850778517785277853778547785577856778577785877859778607786177862778637786477865778667786777868778697787077871778727787377874778757787677877778787787977880778817788277883778847788577886778877788877889778907789177892778937789477895778967789777898778997790077901779027790377904779057790677907779087790977910779117791277913779147791577916779177791877919779207792177922779237792477925779267792777928779297793077931779327793377934779357793677937779387793977940779417794277943779447794577946779477794877949779507795177952779537795477955779567795777958779597796077961779627796377964779657796677967779687796977970779717797277973779747797577976779777797877979779807798177982779837798477985779867798777988779897799077991779927799377994779957799677997779987799978000780017800278003780047800578006780077800878009780107801178012780137801478015780167801778018780197802078021780227802378024780257802678027780287802978030780317803278033780347803578036780377803878039780407804178042780437804478045780467804778048780497805078051780527805378054780557805678057780587805978060780617806278063780647806578066780677806878069780707807178072780737807478075780767807778078780797808078081780827808378084780857808678087780887808978090780917809278093780947809578096780977809878099781007810178102781037810478105781067810778108781097811078111781127811378114781157811678117781187811978120781217812278123781247812578126781277812878129781307813178132781337813478135781367813778138781397814078141781427814378144781457814678147781487814978150781517815278153781547815578156781577815878159781607816178162781637816478165781667816778168781697817078171781727817378174781757817678177781787817978180781817818278183781847818578186781877818878189781907819178192781937819478195781967819778198781997820078201782027820378204782057820678207782087820978210782117821278213782147821578216782177821878219782207822178222782237822478225782267822778228782297823078231782327823378234782357823678237782387823978240782417824278243782447824578246782477824878249782507825178252782537825478255782567825778258782597826078261782627826378264782657826678267782687826978270782717827278273782747827578276782777827878279782807828178282782837828478285782867828778288782897829078291782927829378294782957829678297782987829978300783017830278303783047830578306783077830878309783107831178312783137831478315783167831778318783197832078321783227832378324783257832678327783287832978330783317833278333783347833578336783377833878339783407834178342783437834478345783467834778348783497835078351783527835378354783557835678357783587835978360783617836278363783647836578366783677836878369783707837178372783737837478375783767837778378783797838078381783827838378384783857838678387783887838978390783917839278393783947839578396783977839878399784007840178402784037840478405784067840778408784097841078411784127841378414784157841678417784187841978420784217842278423784247842578426784277842878429784307843178432784337843478435784367843778438784397844078441784427844378444784457844678447784487844978450784517845278453784547845578456784577845878459784607846178462784637846478465784667846778468784697847078471784727847378474784757847678477784787847978480784817848278483784847848578486784877848878489784907849178492784937849478495784967849778498784997850078501785027850378504785057850678507785087850978510785117851278513785147851578516785177851878519785207852178522785237852478525785267852778528785297853078531785327853378534785357853678537785387853978540785417854278543785447854578546785477854878549785507855178552785537855478555785567855778558785597856078561785627856378564785657856678567785687856978570785717857278573785747857578576785777857878579785807858178582785837858478585785867858778588785897859078591785927859378594785957859678597785987859978600786017860278603786047860578606786077860878609786107861178612786137861478615786167861778618786197862078621786227862378624786257862678627786287862978630786317863278633786347863578636786377863878639786407864178642786437864478645786467864778648786497865078651786527865378654786557865678657786587865978660786617866278663786647866578666786677866878669786707867178672786737867478675786767867778678786797868078681786827868378684786857868678687786887868978690786917869278693786947869578696786977869878699787007870178702787037870478705787067870778708787097871078711787127871378714787157871678717787187871978720787217872278723787247872578726787277872878729787307873178732787337873478735787367873778738787397874078741787427874378744787457874678747787487874978750787517875278753787547875578756787577875878759787607876178762787637876478765787667876778768787697877078771787727877378774787757877678777787787877978780787817878278783787847878578786787877878878789787907879178792787937879478795787967879778798787997880078801788027880378804788057880678807788087880978810788117881278813788147881578816788177881878819788207882178822788237882478825788267882778828788297883078831788327883378834788357883678837788387883978840788417884278843788447884578846788477884878849788507885178852788537885478855788567885778858788597886078861788627886378864788657886678867788687886978870788717887278873788747887578876788777887878879788807888178882788837888478885788867888778888788897889078891788927889378894788957889678897788987889978900789017890278903789047890578906789077890878909789107891178912789137891478915789167891778918789197892078921789227892378924789257892678927789287892978930789317893278933789347893578936789377893878939789407894178942789437894478945789467894778948789497895078951789527895378954789557895678957789587895978960789617896278963789647896578966789677896878969789707897178972789737897478975789767897778978789797898078981789827898378984789857898678987789887898978990789917899278993789947899578996789977899878999790007900179002790037900479005790067900779008790097901079011790127901379014790157901679017790187901979020790217902279023790247902579026790277902879029790307903179032790337903479035790367903779038790397904079041790427904379044790457904679047790487904979050790517905279053790547905579056790577905879059790607906179062790637906479065790667906779068790697907079071790727907379074790757907679077790787907979080790817908279083790847908579086790877908879089790907909179092790937909479095790967909779098790997910079101791027910379104791057910679107791087910979110791117911279113791147911579116791177911879119791207912179122791237912479125791267912779128791297913079131791327913379134791357913679137791387913979140791417914279143791447914579146791477914879149791507915179152791537915479155791567915779158791597916079161791627916379164791657916679167791687916979170791717917279173791747917579176791777917879179791807918179182791837918479185791867918779188791897919079191791927919379194791957919679197791987919979200792017920279203792047920579206792077920879209792107921179212792137921479215792167921779218792197922079221792227922379224792257922679227792287922979230792317923279233792347923579236792377923879239792407924179242792437924479245792467924779248792497925079251792527925379254792557925679257792587925979260792617926279263792647926579266792677926879269792707927179272792737927479275792767927779278792797928079281792827928379284792857928679287792887928979290792917929279293792947929579296792977929879299793007930179302793037930479305793067930779308793097931079311793127931379314793157931679317793187931979320793217932279323793247932579326793277932879329793307933179332793337933479335793367933779338793397934079341793427934379344793457934679347793487934979350793517935279353793547935579356793577935879359793607936179362793637936479365793667936779368793697937079371793727937379374793757937679377793787937979380793817938279383793847938579386793877938879389793907939179392793937939479395793967939779398793997940079401794027940379404794057940679407794087940979410794117941279413794147941579416794177941879419794207942179422794237942479425794267942779428794297943079431794327943379434794357943679437794387943979440794417944279443794447944579446794477944879449794507945179452794537945479455794567945779458794597946079461794627946379464794657946679467794687946979470794717947279473794747947579476794777947879479794807948179482794837948479485794867948779488794897949079491794927949379494794957949679497794987949979500795017950279503795047950579506795077950879509795107951179512795137951479515795167951779518795197952079521795227952379524795257952679527795287952979530795317953279533795347953579536795377953879539795407954179542795437954479545795467954779548795497955079551795527955379554795557955679557795587955979560795617956279563795647956579566795677956879569795707957179572795737957479575795767957779578795797958079581795827958379584795857958679587795887958979590795917959279593795947959579596795977959879599796007960179602796037960479605796067960779608796097961079611796127961379614796157961679617796187961979620796217962279623796247962579626796277962879629796307963179632796337963479635796367963779638796397964079641796427964379644796457964679647796487964979650796517965279653796547965579656796577965879659796607966179662796637966479665796667966779668796697967079671796727967379674796757967679677796787967979680796817968279683796847968579686796877968879689796907969179692796937969479695796967969779698796997970079701797027970379704797057970679707797087970979710797117971279713797147971579716797177971879719797207972179722797237972479725797267972779728797297973079731797327973379734797357973679737797387973979740797417974279743797447974579746797477974879749797507975179752797537975479755797567975779758797597976079761797627976379764797657976679767797687976979770797717977279773797747977579776797777977879779797807978179782797837978479785797867978779788797897979079791797927979379794797957979679797797987979979800798017980279803798047980579806798077980879809798107981179812798137981479815798167981779818798197982079821798227982379824798257982679827798287982979830798317983279833798347983579836798377983879839798407984179842798437984479845798467984779848798497985079851798527985379854798557985679857798587985979860798617986279863798647986579866798677986879869798707987179872798737987479875798767987779878798797988079881798827988379884798857988679887798887988979890798917989279893798947989579896798977989879899799007990179902799037990479905799067990779908799097991079911799127991379914799157991679917799187991979920799217992279923799247992579926799277992879929799307993179932799337993479935799367993779938799397994079941799427994379944799457994679947799487994979950799517995279953799547995579956799577995879959799607996179962799637996479965799667996779968799697997079971799727997379974799757997679977799787997979980799817998279983799847998579986799877998879989799907999179992799937999479995799967999779998799998000080001800028000380004800058000680007800088000980010800118001280013800148001580016800178001880019800208002180022800238002480025800268002780028800298003080031800328003380034800358003680037800388003980040800418004280043800448004580046800478004880049800508005180052800538005480055800568005780058800598006080061800628006380064800658006680067800688006980070800718007280073800748007580076800778007880079800808008180082800838008480085800868008780088800898009080091800928009380094800958009680097800988009980100801018010280103801048010580106801078010880109801108011180112801138011480115801168011780118801198012080121801228012380124801258012680127801288012980130801318013280133801348013580136801378013880139801408014180142801438014480145801468014780148801498015080151801528015380154801558015680157801588015980160801618016280163801648016580166801678016880169801708017180172801738017480175801768017780178801798018080181801828018380184801858018680187801888018980190801918019280193801948019580196801978019880199802008020180202802038020480205802068020780208802098021080211802128021380214802158021680217802188021980220802218022280223802248022580226802278022880229802308023180232802338023480235802368023780238802398024080241802428024380244802458024680247802488024980250802518025280253802548025580256802578025880259802608026180262802638026480265802668026780268802698027080271802728027380274802758027680277802788027980280802818028280283802848028580286802878028880289802908029180292802938029480295802968029780298802998030080301803028030380304803058030680307803088030980310803118031280313803148031580316803178031880319803208032180322803238032480325803268032780328803298033080331803328033380334803358033680337803388033980340803418034280343803448034580346803478034880349803508035180352803538035480355803568035780358803598036080361803628036380364803658036680367803688036980370803718037280373803748037580376803778037880379803808038180382803838038480385803868038780388803898039080391803928039380394803958039680397803988039980400804018040280403804048040580406804078040880409804108041180412804138041480415804168041780418804198042080421804228042380424804258042680427804288042980430804318043280433804348043580436804378043880439804408044180442804438044480445804468044780448804498045080451804528045380454804558045680457804588045980460804618046280463804648046580466804678046880469804708047180472804738047480475804768047780478804798048080481804828048380484804858048680487804888048980490804918049280493804948049580496804978049880499805008050180502805038050480505805068050780508805098051080511805128051380514805158051680517805188051980520805218052280523805248052580526805278052880529805308053180532805338053480535805368053780538805398054080541805428054380544805458054680547805488054980550805518055280553805548055580556805578055880559805608056180562805638056480565805668056780568805698057080571805728057380574805758057680577805788057980580805818058280583805848058580586805878058880589805908059180592805938059480595805968059780598805998060080601806028060380604806058060680607806088060980610806118061280613806148061580616806178061880619806208062180622806238062480625806268062780628806298063080631806328063380634806358063680637806388063980640806418064280643806448064580646806478064880649806508065180652806538065480655806568065780658806598066080661806628066380664806658066680667806688066980670806718067280673806748067580676806778067880679806808068180682806838068480685806868068780688806898069080691806928069380694806958069680697806988069980700807018070280703807048070580706807078070880709807108071180712807138071480715807168071780718807198072080721807228072380724807258072680727807288072980730807318073280733807348073580736807378073880739807408074180742807438074480745807468074780748807498075080751807528075380754807558075680757807588075980760807618076280763807648076580766807678076880769807708077180772807738077480775807768077780778807798078080781807828078380784807858078680787807888078980790807918079280793807948079580796807978079880799808008080180802808038080480805808068080780808808098081080811808128081380814808158081680817808188081980820808218082280823808248082580826808278082880829808308083180832808338083480835808368083780838808398084080841808428084380844808458084680847808488084980850808518085280853808548085580856808578085880859808608086180862808638086480865808668086780868808698087080871808728087380874808758087680877808788087980880808818088280883808848088580886808878088880889808908089180892808938089480895808968089780898808998090080901809028090380904809058090680907809088090980910809118091280913809148091580916809178091880919809208092180922809238092480925809268092780928809298093080931809328093380934809358093680937809388093980940809418094280943809448094580946809478094880949809508095180952809538095480955809568095780958809598096080961809628096380964809658096680967809688096980970809718097280973809748097580976809778097880979809808098180982809838098480985809868098780988809898099080991809928099380994809958099680997809988099981000810018100281003810048100581006810078100881009810108101181012810138101481015810168101781018810198102081021810228102381024810258102681027810288102981030810318103281033810348103581036810378103881039810408104181042810438104481045810468104781048810498105081051810528105381054810558105681057810588105981060810618106281063810648106581066810678106881069810708107181072810738107481075810768107781078810798108081081810828108381084810858108681087810888108981090810918109281093810948109581096810978109881099811008110181102811038110481105811068110781108811098111081111811128111381114811158111681117811188111981120811218112281123811248112581126811278112881129811308113181132811338113481135811368113781138811398114081141811428114381144811458114681147811488114981150811518115281153811548115581156811578115881159811608116181162811638116481165811668116781168811698117081171811728117381174811758117681177811788117981180811818118281183811848118581186811878118881189811908119181192811938119481195811968119781198811998120081201812028120381204812058120681207812088120981210812118121281213812148121581216812178121881219812208122181222812238122481225812268122781228812298123081231812328123381234812358123681237812388123981240812418124281243812448124581246812478124881249812508125181252812538125481255812568125781258812598126081261812628126381264812658126681267812688126981270812718127281273812748127581276812778127881279812808128181282812838128481285812868128781288812898129081291812928129381294812958129681297812988129981300813018130281303813048130581306813078130881309813108131181312813138131481315813168131781318813198132081321813228132381324813258132681327813288132981330813318133281333813348133581336813378133881339813408134181342813438134481345813468134781348813498135081351813528135381354813558135681357813588135981360813618136281363813648136581366813678136881369813708137181372813738137481375813768137781378813798138081381813828138381384813858138681387813888138981390813918139281393813948139581396813978139881399814008140181402814038140481405814068140781408814098141081411814128141381414814158141681417814188141981420814218142281423814248142581426814278142881429814308143181432814338143481435814368143781438814398144081441814428144381444814458144681447814488144981450814518145281453814548145581456814578145881459814608146181462814638146481465814668146781468814698147081471814728147381474814758147681477814788147981480814818148281483814848148581486814878148881489814908149181492814938149481495814968149781498814998150081501815028150381504815058150681507815088150981510815118151281513815148151581516815178151881519815208152181522815238152481525815268152781528815298153081531815328153381534815358153681537815388153981540815418154281543815448154581546815478154881549
  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, NoNormalPacking, NormalRGPacking, NormalGAPacking, ObjectSpaceNormalMap, RGFormat, RED_GREEN_RGTC2_Format, RG11_EAC_Format, 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, 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, CubeDepthTexture, 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, R11_EAC_Format, SIGNED_R11_EAC_Format, SIGNED_RG11_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, SIGNED_RED_GREEN_RGTC2_Format, MirroredRepeatWrapping, RepeatWrapping, NearestMipmapNearestFilter, NotEqualCompare, GreaterCompare, GreaterEqualCompare, EqualCompare, LessEqualCompare, AlwaysCompare, NeverCompare, LinearTransfer, getByteLength, isTypedArray, 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.context.modelViewMatrix || builder.context.modelNormalViewMatrix || builder.context.getAO || builder.context.getShadow )
  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 alignment requirement for the given data type.
  551. *
  552. * @private
  553. * @method
  554. * @param {string} type - The data type.
  555. * @return {number} The alignment requirement in bytes.
  556. */
  557. function getAlignmentFromType( 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 16;
  564. if ( /mat4/.test( type ) ) return 16;
  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. getAlignmentFromType: getAlignmentFromType,
  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 scopeData = builder.getDataFromNode( scope );
  3645. scopeData.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. *\// or
  5468. *material.contextNode = context( { getUV: () => customCoord } );
  5469. *\// or
  5470. *renderer.contextNode = context( { getUV: () => customCoord } );
  5471. *\// or
  5472. *scenePass.contextNode = context( { getUV: () => customCoord } );
  5473. *```
  5474. * @augments Node
  5475. */
  5476. class ContextNode extends Node {
  5477. static get type() {
  5478. return 'ContextNode';
  5479. }
  5480. /**
  5481. * Constructs a new context node.
  5482. *
  5483. * @param {Node} node - The node whose context should be modified.
  5484. * @param {Object} [value={}] - The modified context data.
  5485. */
  5486. constructor( node = null, value = {} ) {
  5487. super();
  5488. /**
  5489. * This flag can be used for type testing.
  5490. *
  5491. * @type {boolean}
  5492. * @readonly
  5493. * @default true
  5494. */
  5495. this.isContextNode = true;
  5496. /**
  5497. * The node whose context should be modified.
  5498. *
  5499. * @type {Node}
  5500. */
  5501. this.node = node;
  5502. /**
  5503. * The modified context data.
  5504. *
  5505. * @type {Object}
  5506. * @default {}
  5507. */
  5508. this.value = value;
  5509. }
  5510. /**
  5511. * This method is overwritten to ensure it returns the reference to {@link ContextNode#node}.
  5512. *
  5513. * @return {Node} A reference to {@link ContextNode#node}.
  5514. */
  5515. getScope() {
  5516. return this.node.getScope();
  5517. }
  5518. /**
  5519. * This method is overwritten to ensure it returns the type of {@link ContextNode#node}.
  5520. *
  5521. * @param {NodeBuilder} builder - The current node builder.
  5522. * @return {string} The node type.
  5523. */
  5524. getNodeType( builder ) {
  5525. return this.node.getNodeType( builder );
  5526. }
  5527. /**
  5528. * Gathers the context data from all parent context nodes.
  5529. *
  5530. * @return {Object} The gathered context data.
  5531. */
  5532. getFlowContextData() {
  5533. const children = [];
  5534. this.traverse( ( node ) => {
  5535. if ( node.isContextNode === true ) {
  5536. children.push( node.value );
  5537. }
  5538. } );
  5539. return Object.assign( {}, ...children );
  5540. }
  5541. /**
  5542. * This method is overwritten to ensure it returns the member type of {@link ContextNode#node}.
  5543. *
  5544. * @param {NodeBuilder} builder - The current node builder.
  5545. * @param {string} name - The member name.
  5546. * @returns {string} The member type.
  5547. */
  5548. getMemberType( builder, name ) {
  5549. return this.node.getMemberType( builder, name );
  5550. }
  5551. analyze( builder ) {
  5552. const previousContext = builder.addContext( this.value );
  5553. this.node.build( builder );
  5554. builder.setContext( previousContext );
  5555. }
  5556. setup( builder ) {
  5557. const previousContext = builder.addContext( this.value );
  5558. this.node.build( builder );
  5559. builder.setContext( previousContext );
  5560. }
  5561. generate( builder, output ) {
  5562. const previousContext = builder.addContext( this.value );
  5563. const snippet = this.node.build( builder, output );
  5564. builder.setContext( previousContext );
  5565. return snippet;
  5566. }
  5567. }
  5568. /**
  5569. * TSL function for creating a context node.
  5570. *
  5571. * @tsl
  5572. * @function
  5573. * @param {Node|Object} [nodeOrValue={}] - The node whose context should be modified or the modified context data.
  5574. * @param {Object} [value={}] - The modified context data.
  5575. * @returns {ContextNode}
  5576. */
  5577. const context = ( nodeOrValue = null, value = {} ) => {
  5578. let node = nodeOrValue;
  5579. if ( node === null || node.isNode !== true ) {
  5580. value = node || value;
  5581. node = null;
  5582. }
  5583. return new ContextNode( node, value );
  5584. };
  5585. /**
  5586. * TSL function for defining a uniformFlow context value for a given node.
  5587. *
  5588. * @tsl
  5589. * @function
  5590. * @param {Node} node - The node whose dependencies should all execute within a uniform control-flow path.
  5591. * @returns {ContextNode}
  5592. */
  5593. const uniformFlow = ( node ) => context( node, { uniformFlow: true } );
  5594. /**
  5595. * TSL function for defining a name for the context value for a given node.
  5596. *
  5597. * @tsl
  5598. * @function
  5599. * @param {Node} node - The node whose context should be modified.
  5600. * @param {string} name - The name to set.
  5601. * @returns {ContextNode}
  5602. */
  5603. const setName = ( node, name ) => context( node, { nodeName: name } );
  5604. /**
  5605. * TSL function for defining a built-in shadow context for a given node.
  5606. *
  5607. * @tsl
  5608. * @function
  5609. * @param {ShadowNode} shadowNode - The shadow node representing the light's shadow.
  5610. * @param {Light} light - The light associated with the shadow.
  5611. * @param {Node} [node=null] - The node whose context should be modified.
  5612. * @returns {ContextNode}
  5613. */
  5614. function builtinShadowContext( shadowNode, light, node = null ) {
  5615. return context( node, {
  5616. getShadow: ( { light: shadowLight, shadowColorNode } ) => {
  5617. if ( light === shadowLight ) {
  5618. return shadowColorNode.mul( shadowNode );
  5619. }
  5620. return shadowColorNode;
  5621. }
  5622. } );
  5623. }
  5624. /**
  5625. * TSL function for defining a built-in ambient occlusion context for a given node.
  5626. *
  5627. * @tsl
  5628. * @function
  5629. * @param {Node} aoNode - The ambient occlusion value node to apply.
  5630. * @param {Node} [node=null] - The node whose context should be modified.
  5631. * @returns {ContextNode}
  5632. */
  5633. function builtinAOContext( aoNode, node = null ) {
  5634. return context( node, {
  5635. getAO: ( inputNode, { material } ) => {
  5636. if ( material.transparent === true ) return inputNode;
  5637. return inputNode !== null ? inputNode.mul( aoNode ) : aoNode;
  5638. }
  5639. } );
  5640. }
  5641. /**
  5642. * TSL function for defining a label context value for a given node.
  5643. *
  5644. * @tsl
  5645. * @function
  5646. * @deprecated
  5647. * @param {Node} node - The node whose context should be modified.
  5648. * @param {string} name - The name/label to set.
  5649. * @returns {ContextNode}
  5650. */
  5651. function label( node, name ) {
  5652. warn( 'TSL: "label()" has been deprecated. Use "setName()" instead.' ); // @deprecated r179
  5653. return setName( node, name );
  5654. }
  5655. addMethodChaining( 'context', context );
  5656. addMethodChaining( 'label', label );
  5657. addMethodChaining( 'uniformFlow', uniformFlow );
  5658. addMethodChaining( 'setName', setName );
  5659. addMethodChaining( 'builtinShadowContext', ( node, shadowNode, light ) => builtinShadowContext( shadowNode, light, node ) );
  5660. addMethodChaining( 'builtinAOContext', ( node, aoValue ) => builtinAOContext( aoValue, node ) );
  5661. /**
  5662. * Class for representing shader variables as nodes. Variables are created from
  5663. * existing nodes like the following:
  5664. *
  5665. * ```js
  5666. * const depth = sampleDepth( uvNode ).toVar( 'depth' );
  5667. * ```
  5668. *
  5669. * @augments Node
  5670. */
  5671. class VarNode extends Node {
  5672. static get type() {
  5673. return 'VarNode';
  5674. }
  5675. /**
  5676. * Constructs a new variable node.
  5677. *
  5678. * @param {Node} node - The node for which a variable should be created.
  5679. * @param {?string} [name=null] - The name of the variable in the shader.
  5680. * @param {boolean} [readOnly=false] - The read-only flag.
  5681. */
  5682. constructor( node, name = null, readOnly = false ) {
  5683. super();
  5684. /**
  5685. * The node for which a variable should be created.
  5686. *
  5687. * @type {Node}
  5688. */
  5689. this.node = node;
  5690. /**
  5691. * The name of the variable in the shader. If no name is defined,
  5692. * the node system auto-generates one.
  5693. *
  5694. * @type {?string}
  5695. * @default null
  5696. */
  5697. this.name = name;
  5698. /**
  5699. * `VarNode` sets this property to `true` by default.
  5700. *
  5701. * @type {boolean}
  5702. * @default true
  5703. */
  5704. this.global = true;
  5705. /**
  5706. * This flag can be used for type testing.
  5707. *
  5708. * @type {boolean}
  5709. * @readonly
  5710. * @default true
  5711. */
  5712. this.isVarNode = true;
  5713. /**
  5714. *
  5715. * The read-only flag.
  5716. *
  5717. * @type {boolean}
  5718. * @default false
  5719. */
  5720. this.readOnly = readOnly;
  5721. /**
  5722. *
  5723. * Add this flag to the node system to indicate that this node require parents.
  5724. *
  5725. * @type {boolean}
  5726. * @default true
  5727. */
  5728. this.parents = true;
  5729. /**
  5730. * This flag is used to indicate that this node is used for intent.
  5731. *
  5732. * @type {boolean}
  5733. * @default false
  5734. */
  5735. this.intent = false;
  5736. }
  5737. /**
  5738. * Sets the intent flag for this node.
  5739. *
  5740. * This flag is used to indicate that this node is used for intent
  5741. * and should not be built directly. Instead, it is used to indicate that
  5742. * the node should be treated as a variable intent.
  5743. *
  5744. * It's useful for assigning variables without needing creating a new variable node.
  5745. *
  5746. * @param {boolean} value - The value to set for the intent flag.
  5747. * @returns {VarNode} This node.
  5748. */
  5749. setIntent( value ) {
  5750. this.intent = value;
  5751. return this;
  5752. }
  5753. /**
  5754. * Checks if this node is used for intent.
  5755. *
  5756. * @param {NodeBuilder} builder - The node builder.
  5757. * @returns {boolean} Whether this node is used for intent.
  5758. */
  5759. isIntent( builder ) {
  5760. const data = builder.getDataFromNode( this );
  5761. if ( data.forceDeclaration === true ) return false;
  5762. return this.intent;
  5763. }
  5764. /**
  5765. * Returns the intent flag of this node.
  5766. *
  5767. * @return {boolean} The intent flag.
  5768. */
  5769. getIntent() {
  5770. return this.intent;
  5771. }
  5772. getMemberType( builder, name ) {
  5773. return this.node.getMemberType( builder, name );
  5774. }
  5775. getElementType( builder ) {
  5776. return this.node.getElementType( builder );
  5777. }
  5778. getNodeType( builder ) {
  5779. return this.node.getNodeType( builder );
  5780. }
  5781. getArrayCount( builder ) {
  5782. return this.node.getArrayCount( builder );
  5783. }
  5784. isAssign( builder ) {
  5785. const data = builder.getDataFromNode( this );
  5786. return data.assign;
  5787. }
  5788. build( ...params ) {
  5789. const builder = params[ 0 ];
  5790. if ( this._hasStack( builder ) === false && builder.buildStage === 'setup' ) {
  5791. if ( builder.context.nodeLoop || builder.context.nodeBlock ) {
  5792. let addBefore = false;
  5793. if ( this.node.isShaderCallNodeInternal && this.node.shaderNode.getLayout() === null ) {
  5794. if ( builder.fnCall && builder.fnCall.shaderNode ) {
  5795. const shaderNodeData = builder.getDataFromNode( this.node.shaderNode );
  5796. if ( shaderNodeData.hasLoop ) {
  5797. const data = builder.getDataFromNode( this );
  5798. data.forceDeclaration = true;
  5799. addBefore = true;
  5800. }
  5801. }
  5802. }
  5803. const baseStack = builder.getBaseStack();
  5804. if ( addBefore ) {
  5805. baseStack.addToStackBefore( this );
  5806. } else {
  5807. baseStack.addToStack( this );
  5808. }
  5809. }
  5810. }
  5811. if ( this.isIntent( builder ) ) {
  5812. if ( this.isAssign( builder ) !== true ) {
  5813. return this.node.build( ...params );
  5814. }
  5815. }
  5816. return super.build( ...params );
  5817. }
  5818. generate( builder ) {
  5819. const { node, name, readOnly } = this;
  5820. const { renderer } = builder;
  5821. const isWebGPUBackend = renderer.backend.isWebGPUBackend === true;
  5822. let isDeterministic = false;
  5823. let shouldTreatAsReadOnly = false;
  5824. if ( readOnly ) {
  5825. isDeterministic = builder.isDeterministic( node );
  5826. shouldTreatAsReadOnly = isWebGPUBackend ? readOnly : isDeterministic;
  5827. }
  5828. const nodeType = this.getNodeType( builder );
  5829. if ( nodeType == 'void' ) {
  5830. if ( this.isIntent( builder ) !== true ) {
  5831. error( 'TSL: ".toVar()" can not be used with void type.' );
  5832. }
  5833. const snippet = node.build( builder );
  5834. return snippet;
  5835. }
  5836. const vectorType = builder.getVectorType( nodeType );
  5837. const snippet = node.build( builder, vectorType );
  5838. const nodeVar = builder.getVarFromNode( this, name, vectorType, undefined, shouldTreatAsReadOnly );
  5839. const propertyName = builder.getPropertyName( nodeVar );
  5840. let declarationPrefix = propertyName;
  5841. if ( shouldTreatAsReadOnly ) {
  5842. if ( isWebGPUBackend ) {
  5843. declarationPrefix = isDeterministic
  5844. ? `const ${ propertyName }`
  5845. : `let ${ propertyName }`;
  5846. } else {
  5847. const count = node.getArrayCount( builder );
  5848. declarationPrefix = `const ${ builder.getVar( nodeVar.type, propertyName, count ) }`;
  5849. }
  5850. }
  5851. builder.addLineFlowCode( `${ declarationPrefix } = ${ snippet }`, this );
  5852. return propertyName;
  5853. }
  5854. _hasStack( builder ) {
  5855. const nodeData = builder.getDataFromNode( this );
  5856. return nodeData.stack !== undefined;
  5857. }
  5858. }
  5859. /**
  5860. * TSL function for creating a var node.
  5861. *
  5862. * @tsl
  5863. * @function
  5864. * @param {Node} node - The node for which a variable should be created.
  5865. * @param {?string} name - The name of the variable in the shader.
  5866. * @returns {VarNode}
  5867. */
  5868. const createVar = /*@__PURE__*/ nodeProxy( VarNode );
  5869. /**
  5870. * TSL function for creating a var node.
  5871. *
  5872. * @tsl
  5873. * @function
  5874. * @param {Node} node - The node for which a variable should be created.
  5875. * @param {?string} name - The name of the variable in the shader.
  5876. * @returns {VarNode}
  5877. */
  5878. const Var = ( node, name = null ) => createVar( node, name ).toStack();
  5879. /**
  5880. * TSL function for creating a const node.
  5881. *
  5882. * @tsl
  5883. * @function
  5884. * @param {Node} node - The node for which a constant should be created.
  5885. * @param {?string} name - The name of the constant in the shader.
  5886. * @returns {VarNode}
  5887. */
  5888. const Const = ( node, name = null ) => createVar( node, name, true ).toStack();
  5889. //
  5890. //
  5891. /**
  5892. * TSL function for creating a var intent node.
  5893. *
  5894. * @tsl
  5895. * @function
  5896. * @param {Node} node - The node for which a variable should be created.
  5897. * @param {?string} name - The name of the variable in the shader.
  5898. * @returns {VarNode}
  5899. */
  5900. const VarIntent = ( node ) => {
  5901. return createVar( node ).setIntent( true ).toStack();
  5902. };
  5903. // Method chaining
  5904. addMethodChaining( 'toVar', Var );
  5905. addMethodChaining( 'toConst', Const );
  5906. addMethodChaining( 'toVarIntent', VarIntent );
  5907. /**
  5908. * This node is used to build a sub-build in the node system.
  5909. *
  5910. * @augments Node
  5911. * @param {Node} node - The node to be built in the sub-build.
  5912. * @param {string} name - The name of the sub-build.
  5913. * @param {?string} [nodeType=null] - The type of the node, if known.
  5914. */
  5915. class SubBuildNode extends Node {
  5916. static get type() {
  5917. return 'SubBuild';
  5918. }
  5919. constructor( node, name, nodeType = null ) {
  5920. super( nodeType );
  5921. /**
  5922. * The node to be built in the sub-build.
  5923. *
  5924. * @type {Node}
  5925. */
  5926. this.node = node;
  5927. /**
  5928. * The name of the sub-build.
  5929. *
  5930. * @type {string}
  5931. */
  5932. this.name = name;
  5933. /**
  5934. * This flag can be used for type testing.
  5935. *
  5936. * @type {boolean}
  5937. * @readonly
  5938. * @default true
  5939. */
  5940. this.isSubBuildNode = true;
  5941. }
  5942. getNodeType( builder ) {
  5943. if ( this.nodeType !== null ) return this.nodeType;
  5944. builder.addSubBuild( this.name );
  5945. const nodeType = this.node.getNodeType( builder );
  5946. builder.removeSubBuild();
  5947. return nodeType;
  5948. }
  5949. build( builder, ...params ) {
  5950. builder.addSubBuild( this.name );
  5951. const data = this.node.build( builder, ...params );
  5952. builder.removeSubBuild();
  5953. return data;
  5954. }
  5955. }
  5956. /**
  5957. * Creates a new sub-build node.
  5958. *
  5959. * @tsl
  5960. * @function
  5961. * @param {Node} node - The node to be built in the sub-build.
  5962. * @param {string} name - The name of the sub-build.
  5963. * @param {?string} [type=null] - The type of the node, if known.
  5964. * @returns {Node} A node object wrapping the SubBuildNode instance.
  5965. */
  5966. const subBuild = ( node, name, type = null ) => nodeObject( new SubBuildNode( nodeObject( node ), name, type ) );
  5967. /**
  5968. * Class for representing shader varyings as nodes. Varyings are create from
  5969. * existing nodes like the following:
  5970. *
  5971. * ```js
  5972. * const positionLocal = positionGeometry.toVarying( 'vPositionLocal' );
  5973. * ```
  5974. *
  5975. * @augments Node
  5976. */
  5977. class VaryingNode extends Node {
  5978. static get type() {
  5979. return 'VaryingNode';
  5980. }
  5981. /**
  5982. * Constructs a new varying node.
  5983. *
  5984. * @param {Node} node - The node for which a varying should be created.
  5985. * @param {?string} name - The name of the varying in the shader.
  5986. */
  5987. constructor( node, name = null ) {
  5988. super();
  5989. /**
  5990. * The node for which a varying should be created.
  5991. *
  5992. * @type {Node}
  5993. */
  5994. this.node = node;
  5995. /**
  5996. * The name of the varying in the shader. If no name is defined,
  5997. * the node system auto-generates one.
  5998. *
  5999. * @type {?string}
  6000. * @default null
  6001. */
  6002. this.name = name;
  6003. /**
  6004. * This flag can be used for type testing.
  6005. *
  6006. * @type {boolean}
  6007. * @readonly
  6008. * @default true
  6009. */
  6010. this.isVaryingNode = true;
  6011. /**
  6012. * The interpolation type of the varying data.
  6013. *
  6014. * @type {?string}
  6015. * @default null
  6016. */
  6017. this.interpolationType = null;
  6018. /**
  6019. * The interpolation sampling type of varying data.
  6020. *
  6021. * @type {?string}
  6022. * @default null
  6023. */
  6024. this.interpolationSampling = null;
  6025. /**
  6026. * This flag is used for global cache.
  6027. *
  6028. * @type {boolean}
  6029. * @default true
  6030. */
  6031. this.global = true;
  6032. }
  6033. /**
  6034. * Defines the interpolation type of the varying.
  6035. *
  6036. * @param {string} type - The interpolation type.
  6037. * @param {?string} sampling - The interpolation sampling type
  6038. * @return {VaryingNode} A reference to this node.
  6039. */
  6040. setInterpolation( type, sampling = null ) {
  6041. this.interpolationType = type;
  6042. this.interpolationSampling = sampling;
  6043. return this;
  6044. }
  6045. getHash( builder ) {
  6046. return this.name || super.getHash( builder );
  6047. }
  6048. getNodeType( builder ) {
  6049. // VaryingNode is auto type
  6050. return this.node.getNodeType( builder );
  6051. }
  6052. /**
  6053. * This method performs the setup of a varying node with the current node builder.
  6054. *
  6055. * @param {NodeBuilder} builder - The current node builder.
  6056. * @return {NodeVarying} The node varying from the node builder.
  6057. */
  6058. setupVarying( builder ) {
  6059. const properties = builder.getNodeProperties( this );
  6060. let varying = properties.varying;
  6061. if ( varying === undefined ) {
  6062. const name = this.name;
  6063. const type = this.getNodeType( builder );
  6064. const interpolationType = this.interpolationType;
  6065. const interpolationSampling = this.interpolationSampling;
  6066. properties.varying = varying = builder.getVaryingFromNode( this, name, type, interpolationType, interpolationSampling );
  6067. properties.node = subBuild( this.node, 'VERTEX' );
  6068. }
  6069. // this property can be used to check if the varying can be optimized for a variable
  6070. varying.needsInterpolation || ( varying.needsInterpolation = ( builder.shaderStage === 'fragment' ) );
  6071. return varying;
  6072. }
  6073. setup( builder ) {
  6074. this.setupVarying( builder );
  6075. builder.flowNodeFromShaderStage( NodeShaderStage.VERTEX, this.node );
  6076. }
  6077. analyze( builder ) {
  6078. this.setupVarying( builder );
  6079. builder.flowNodeFromShaderStage( NodeShaderStage.VERTEX, this.node );
  6080. }
  6081. generate( builder ) {
  6082. const propertyKey = builder.getSubBuildProperty( 'property', builder.currentStack );
  6083. const properties = builder.getNodeProperties( this );
  6084. const varying = this.setupVarying( builder );
  6085. if ( properties[ propertyKey ] === undefined ) {
  6086. const type = this.getNodeType( builder );
  6087. const propertyName = builder.getPropertyName( varying, NodeShaderStage.VERTEX );
  6088. // force node run in vertex stage
  6089. builder.flowNodeFromShaderStage( NodeShaderStage.VERTEX, properties.node, type, propertyName );
  6090. properties[ propertyKey ] = propertyName;
  6091. }
  6092. return builder.getPropertyName( varying );
  6093. }
  6094. }
  6095. /**
  6096. * TSL function for creating a varying node.
  6097. *
  6098. * @tsl
  6099. * @function
  6100. * @param {Node} node - The node for which a varying should be created.
  6101. * @param {?string} name - The name of the varying in the shader.
  6102. * @returns {VaryingNode}
  6103. */
  6104. const varying = /*@__PURE__*/ nodeProxy( VaryingNode ).setParameterLength( 1, 2 );
  6105. /**
  6106. * Computes a node in the vertex stage.
  6107. *
  6108. * @tsl
  6109. * @function
  6110. * @param {Node} node - The node which should be executed in the vertex stage.
  6111. * @returns {VaryingNode}
  6112. */
  6113. const vertexStage = ( node ) => varying( node );
  6114. addMethodChaining( 'toVarying', varying );
  6115. addMethodChaining( 'toVertexStage', vertexStage );
  6116. // Deprecated
  6117. addMethodChaining( 'varying', ( ...params ) => { // @deprecated, r173
  6118. warn( 'TSL: .varying() has been renamed to .toVarying().' );
  6119. return varying( ...params );
  6120. } );
  6121. addMethodChaining( 'vertexStage', ( ...params ) => { // @deprecated, r173
  6122. warn( 'TSL: .vertexStage() has been renamed to .toVertexStage().' );
  6123. return varying( ...params );
  6124. } );
  6125. /**
  6126. * Converts the given color value from sRGB to linear-sRGB color space.
  6127. *
  6128. * @tsl
  6129. * @function
  6130. * @param {Node<vec3>} color - The sRGB color.
  6131. * @return {Node<vec3>} The linear-sRGB color.
  6132. */
  6133. const sRGBTransferEOTF = /*@__PURE__*/ Fn( ( [ color ] ) => {
  6134. const a = color.mul( 0.9478672986 ).add( 0.0521327014 ).pow( 2.4 );
  6135. const b = color.mul( 0.0773993808 );
  6136. const factor = color.lessThanEqual( 0.04045 );
  6137. const rgbResult = mix( a, b, factor );
  6138. return rgbResult;
  6139. } ).setLayout( {
  6140. name: 'sRGBTransferEOTF',
  6141. type: 'vec3',
  6142. inputs: [
  6143. { name: 'color', type: 'vec3' }
  6144. ]
  6145. } );
  6146. /**
  6147. * Converts the given color value from linear-sRGB to sRGB color space.
  6148. *
  6149. * @tsl
  6150. * @function
  6151. * @param {Node<vec3>} color - The linear-sRGB color.
  6152. * @return {Node<vec3>} The sRGB color.
  6153. */
  6154. const sRGBTransferOETF = /*@__PURE__*/ Fn( ( [ color ] ) => {
  6155. const a = color.pow( 0.41666 ).mul( 1.055 ).sub( 0.055 );
  6156. const b = color.mul( 12.92 );
  6157. const factor = color.lessThanEqual( 0.0031308 );
  6158. const rgbResult = mix( a, b, factor );
  6159. return rgbResult;
  6160. } ).setLayout( {
  6161. name: 'sRGBTransferOETF',
  6162. type: 'vec3',
  6163. inputs: [
  6164. { name: 'color', type: 'vec3' }
  6165. ]
  6166. } );
  6167. const WORKING_COLOR_SPACE = 'WorkingColorSpace';
  6168. const OUTPUT_COLOR_SPACE = 'OutputColorSpace';
  6169. /**
  6170. * This node represents a color space conversion. Meaning it converts
  6171. * a color value from a source to a target color space.
  6172. *
  6173. * @augments TempNode
  6174. */
  6175. class ColorSpaceNode extends TempNode {
  6176. static get type() {
  6177. return 'ColorSpaceNode';
  6178. }
  6179. /**
  6180. * Constructs a new color space node.
  6181. *
  6182. * @param {Node} colorNode - Represents the color to convert.
  6183. * @param {string} source - The source color space.
  6184. * @param {string} target - The target color space.
  6185. */
  6186. constructor( colorNode, source, target ) {
  6187. super( 'vec4' );
  6188. /**
  6189. * Represents the color to convert.
  6190. *
  6191. * @type {Node}
  6192. */
  6193. this.colorNode = colorNode;
  6194. /**
  6195. * The source color space.
  6196. *
  6197. * @type {string}
  6198. */
  6199. this.source = source;
  6200. /**
  6201. * The target color space.
  6202. *
  6203. * @type {string}
  6204. */
  6205. this.target = target;
  6206. }
  6207. /**
  6208. * This method resolves the constants `WORKING_COLOR_SPACE` and
  6209. * `OUTPUT_COLOR_SPACE` based on the current configuration of the
  6210. * color management and renderer.
  6211. *
  6212. * @param {NodeBuilder} builder - The current node builder.
  6213. * @param {string} colorSpace - The color space to resolve.
  6214. * @return {string} The resolved color space.
  6215. */
  6216. resolveColorSpace( builder, colorSpace ) {
  6217. if ( colorSpace === WORKING_COLOR_SPACE ) {
  6218. return ColorManagement.workingColorSpace;
  6219. } else if ( colorSpace === OUTPUT_COLOR_SPACE ) {
  6220. return builder.context.outputColorSpace || builder.renderer.outputColorSpace;
  6221. }
  6222. return colorSpace;
  6223. }
  6224. setup( builder ) {
  6225. const { colorNode } = this;
  6226. const source = this.resolveColorSpace( builder, this.source );
  6227. const target = this.resolveColorSpace( builder, this.target );
  6228. let outputNode = colorNode;
  6229. if ( ColorManagement.enabled === false || source === target || ! source || ! target ) {
  6230. return outputNode;
  6231. }
  6232. if ( ColorManagement.getTransfer( source ) === SRGBTransfer ) {
  6233. outputNode = vec4( sRGBTransferEOTF( outputNode.rgb ), outputNode.a );
  6234. }
  6235. if ( ColorManagement.getPrimaries( source ) !== ColorManagement.getPrimaries( target ) ) {
  6236. outputNode = vec4(
  6237. mat3( ColorManagement._getMatrix( new Matrix3(), source, target ) ).mul( outputNode.rgb ),
  6238. outputNode.a
  6239. );
  6240. }
  6241. if ( ColorManagement.getTransfer( target ) === SRGBTransfer ) {
  6242. outputNode = vec4( sRGBTransferOETF( outputNode.rgb ), outputNode.a );
  6243. }
  6244. return outputNode;
  6245. }
  6246. }
  6247. /**
  6248. * TSL function for converting a given color node from the current working color space to the given color space.
  6249. *
  6250. * @tsl
  6251. * @function
  6252. * @param {Node} node - Represents the node to convert.
  6253. * @param {string} targetColorSpace - The target color space.
  6254. * @returns {ColorSpaceNode}
  6255. */
  6256. const workingToColorSpace = ( node, targetColorSpace ) => nodeObject( new ColorSpaceNode( nodeObject( node ), WORKING_COLOR_SPACE, targetColorSpace ) );
  6257. /**
  6258. * TSL function for converting a given color node from the given color space to the current working color space.
  6259. *
  6260. * @tsl
  6261. * @function
  6262. * @param {Node} node - Represents the node to convert.
  6263. * @param {string} sourceColorSpace - The source color space.
  6264. * @returns {ColorSpaceNode}
  6265. */
  6266. const colorSpaceToWorking = ( node, sourceColorSpace ) => nodeObject( new ColorSpaceNode( nodeObject( node ), sourceColorSpace, WORKING_COLOR_SPACE ) );
  6267. /**
  6268. * TSL function for converting a given color node from one color space to another one.
  6269. *
  6270. * @tsl
  6271. * @function
  6272. * @param {Node} node - Represents the node to convert.
  6273. * @param {string} sourceColorSpace - The source color space.
  6274. * @param {string} targetColorSpace - The target color space.
  6275. * @returns {ColorSpaceNode}
  6276. */
  6277. const convertColorSpace = ( node, sourceColorSpace, targetColorSpace ) => nodeObject( new ColorSpaceNode( nodeObject( node ), sourceColorSpace, targetColorSpace ) );
  6278. addMethodChaining( 'workingToColorSpace', workingToColorSpace );
  6279. addMethodChaining( 'colorSpaceToWorking', colorSpaceToWorking );
  6280. // TODO: Avoid duplicated code and use only ReferenceBaseNode or ReferenceNode
  6281. /**
  6282. * This class is only relevant if the referenced property is array-like.
  6283. * In this case, `ReferenceElementNode` allows to refer to a specific
  6284. * element inside the data structure via an index.
  6285. *
  6286. * @augments ArrayElementNode
  6287. */
  6288. let ReferenceElementNode$1 = class ReferenceElementNode extends ArrayElementNode {
  6289. static get type() {
  6290. return 'ReferenceElementNode';
  6291. }
  6292. /**
  6293. * Constructs a new reference element node.
  6294. *
  6295. * @param {ReferenceBaseNode} referenceNode - The reference node.
  6296. * @param {Node} indexNode - The index node that defines the element access.
  6297. */
  6298. constructor( referenceNode, indexNode ) {
  6299. super( referenceNode, indexNode );
  6300. /**
  6301. * Similar to {@link ReferenceBaseNode#reference}, an additional
  6302. * property references to the current node.
  6303. *
  6304. * @type {?ReferenceBaseNode}
  6305. * @default null
  6306. */
  6307. this.referenceNode = referenceNode;
  6308. /**
  6309. * This flag can be used for type testing.
  6310. *
  6311. * @type {boolean}
  6312. * @readonly
  6313. * @default true
  6314. */
  6315. this.isReferenceElementNode = true;
  6316. }
  6317. /**
  6318. * This method is overwritten since the node type is inferred from
  6319. * the uniform type of the reference node.
  6320. *
  6321. * @return {string} The node type.
  6322. */
  6323. getNodeType() {
  6324. return this.referenceNode.uniformType;
  6325. }
  6326. generate( builder ) {
  6327. const snippet = super.generate( builder );
  6328. const arrayType = this.referenceNode.getNodeType();
  6329. const elementType = this.getNodeType();
  6330. return builder.format( snippet, arrayType, elementType );
  6331. }
  6332. };
  6333. /**
  6334. * Base class for nodes which establishes a reference to a property of another object.
  6335. * In this way, the value of the node is automatically linked to the value of
  6336. * referenced object. Reference nodes internally represent the linked value
  6337. * as a uniform.
  6338. *
  6339. * @augments Node
  6340. */
  6341. class ReferenceBaseNode extends Node {
  6342. static get type() {
  6343. return 'ReferenceBaseNode';
  6344. }
  6345. /**
  6346. * Constructs a new reference base node.
  6347. *
  6348. * @param {string} property - The name of the property the node refers to.
  6349. * @param {string} uniformType - The uniform type that should be used to represent the property value.
  6350. * @param {?Object} [object=null] - The object the property belongs to.
  6351. * @param {?number} [count=null] - When the linked property is an array-like, this parameter defines its length.
  6352. */
  6353. constructor( property, uniformType, object = null, count = null ) {
  6354. super();
  6355. /**
  6356. * The name of the property the node refers to.
  6357. *
  6358. * @type {string}
  6359. */
  6360. this.property = property;
  6361. /**
  6362. * The uniform type that should be used to represent the property value.
  6363. *
  6364. * @type {string}
  6365. */
  6366. this.uniformType = uniformType;
  6367. /**
  6368. * The object the property belongs to.
  6369. *
  6370. * @type {?Object}
  6371. * @default null
  6372. */
  6373. this.object = object;
  6374. /**
  6375. * When the linked property is an array, this parameter defines its length.
  6376. *
  6377. * @type {?number}
  6378. * @default null
  6379. */
  6380. this.count = count;
  6381. /**
  6382. * The property name might have dots so nested properties can be referred.
  6383. * The hierarchy of the names is stored inside this array.
  6384. *
  6385. * @type {Array<string>}
  6386. */
  6387. this.properties = property.split( '.' );
  6388. /**
  6389. * Points to the current referred object. This property exists next to {@link ReferenceNode#object}
  6390. * since the final reference might be updated from calling code.
  6391. *
  6392. * @type {?Object}
  6393. * @default null
  6394. */
  6395. this.reference = object;
  6396. /**
  6397. * The uniform node that holds the value of the reference node.
  6398. *
  6399. * @type {UniformNode}
  6400. * @default null
  6401. */
  6402. this.node = null;
  6403. /**
  6404. * The uniform group of the internal uniform.
  6405. *
  6406. * @type {UniformGroupNode}
  6407. * @default null
  6408. */
  6409. this.group = null;
  6410. /**
  6411. * Overwritten since reference nodes are updated per object.
  6412. *
  6413. * @type {string}
  6414. * @default 'object'
  6415. */
  6416. this.updateType = NodeUpdateType.OBJECT;
  6417. }
  6418. /**
  6419. * Sets the uniform group for this reference node.
  6420. *
  6421. * @param {UniformGroupNode} group - The uniform group to set.
  6422. * @return {ReferenceBaseNode} A reference to this node.
  6423. */
  6424. setGroup( group ) {
  6425. this.group = group;
  6426. return this;
  6427. }
  6428. /**
  6429. * When the referred property is array-like, this method can be used
  6430. * to access elements via an index node.
  6431. *
  6432. * @param {IndexNode} indexNode - indexNode.
  6433. * @return {ReferenceElementNode} A reference to an element.
  6434. */
  6435. element( indexNode ) {
  6436. return nodeObject( new ReferenceElementNode$1( this, nodeObject( indexNode ) ) );
  6437. }
  6438. /**
  6439. * Sets the node type which automatically defines the internal
  6440. * uniform type.
  6441. *
  6442. * @param {string} uniformType - The type to set.
  6443. */
  6444. setNodeType( uniformType ) {
  6445. const node = uniform( null, uniformType );
  6446. if ( this.group !== null ) {
  6447. node.setGroup( this.group );
  6448. }
  6449. this.node = node;
  6450. }
  6451. /**
  6452. * This method is overwritten since the node type is inferred from
  6453. * the type of the reference node.
  6454. *
  6455. * @param {NodeBuilder} builder - The current node builder.
  6456. * @return {string} The node type.
  6457. */
  6458. getNodeType( builder ) {
  6459. if ( this.node === null ) {
  6460. this.updateReference( builder );
  6461. this.updateValue();
  6462. }
  6463. return this.node.getNodeType( builder );
  6464. }
  6465. /**
  6466. * Returns the property value from the given referred object.
  6467. *
  6468. * @param {Object} [object=this.reference] - The object to retrieve the property value from.
  6469. * @return {any} The value.
  6470. */
  6471. getValueFromReference( object = this.reference ) {
  6472. const { properties } = this;
  6473. let value = object[ properties[ 0 ] ];
  6474. for ( let i = 1; i < properties.length; i ++ ) {
  6475. value = value[ properties[ i ] ];
  6476. }
  6477. return value;
  6478. }
  6479. /**
  6480. * Allows to update the reference based on the given state. The state is only
  6481. * evaluated {@link ReferenceBaseNode#object} is not set.
  6482. *
  6483. * @param {(NodeFrame|NodeBuilder)} state - The current state.
  6484. * @return {Object} The updated reference.
  6485. */
  6486. updateReference( state ) {
  6487. this.reference = this.object !== null ? this.object : state.object;
  6488. return this.reference;
  6489. }
  6490. /**
  6491. * The output of the reference node is the internal uniform node.
  6492. *
  6493. * @return {UniformNode} The output node.
  6494. */
  6495. setup() {
  6496. this.updateValue();
  6497. return this.node;
  6498. }
  6499. /**
  6500. * Overwritten to update the internal uniform value.
  6501. *
  6502. * @param {NodeFrame} frame - A reference to the current node frame.
  6503. */
  6504. update( /*frame*/ ) {
  6505. this.updateValue();
  6506. }
  6507. /**
  6508. * Retrieves the value from the referred object property and uses it
  6509. * to updated the internal uniform.
  6510. */
  6511. updateValue() {
  6512. if ( this.node === null ) this.setNodeType( this.uniformType );
  6513. const value = this.getValueFromReference();
  6514. if ( Array.isArray( value ) ) {
  6515. this.node.array = value;
  6516. } else {
  6517. this.node.value = value;
  6518. }
  6519. }
  6520. }
  6521. /**
  6522. * TSL function for creating a reference base node.
  6523. *
  6524. * @tsl
  6525. * @function
  6526. * @param {string} name - The name of the property the node refers to.
  6527. * @param {string} type - The uniform type that should be used to represent the property value.
  6528. * @param {Object} object - The object the property belongs to.
  6529. * @returns {ReferenceBaseNode}
  6530. */
  6531. const reference$1 = ( name, type, object ) => nodeObject( new ReferenceBaseNode( name, type, object ) );
  6532. /**
  6533. * This node is a special type of reference node which is intended
  6534. * for linking renderer properties with node values.
  6535. * ```js
  6536. * const exposureNode = rendererReference( 'toneMappingExposure', 'float', renderer );
  6537. * ```
  6538. * When changing `renderer.toneMappingExposure`, the node value of `exposureNode` will
  6539. * automatically be updated.
  6540. *
  6541. * @augments ReferenceBaseNode
  6542. */
  6543. class RendererReferenceNode extends ReferenceBaseNode {
  6544. static get type() {
  6545. return 'RendererReferenceNode';
  6546. }
  6547. /**
  6548. * Constructs a new renderer reference node.
  6549. *
  6550. * @param {string} property - The name of the property the node refers to.
  6551. * @param {string} inputType - The uniform type that should be used to represent the property value.
  6552. * @param {?Renderer} [renderer=null] - The renderer the property belongs to. When no renderer is set,
  6553. * the node refers to the renderer of the current state.
  6554. */
  6555. constructor( property, inputType, renderer = null ) {
  6556. super( property, inputType, renderer );
  6557. /**
  6558. * The renderer the property belongs to. When no renderer is set,
  6559. * the node refers to the renderer of the current state.
  6560. *
  6561. * @type {?Renderer}
  6562. * @default null
  6563. */
  6564. this.renderer = renderer;
  6565. this.setGroup( renderGroup );
  6566. }
  6567. /**
  6568. * Updates the reference based on the given state. The state is only evaluated
  6569. * {@link RendererReferenceNode#renderer} is not set.
  6570. *
  6571. * @param {(NodeFrame|NodeBuilder)} state - The current state.
  6572. * @return {Object} The updated reference.
  6573. */
  6574. updateReference( state ) {
  6575. this.reference = this.renderer !== null ? this.renderer : state.renderer;
  6576. return this.reference;
  6577. }
  6578. }
  6579. /**
  6580. * TSL function for creating a renderer reference node.
  6581. *
  6582. * @tsl
  6583. * @function
  6584. * @param {string} name - The name of the property the node refers to.
  6585. * @param {string} type - The uniform type that should be used to represent the property value.
  6586. * @param {?Renderer} [renderer=null] - The renderer the property belongs to. When no renderer is set,
  6587. * the node refers to the renderer of the current state.
  6588. * @returns {RendererReferenceNode}
  6589. */
  6590. const rendererReference = ( name, type, renderer = null ) => nodeObject( new RendererReferenceNode( name, type, renderer ) );
  6591. /**
  6592. * This node represents a tone mapping operation.
  6593. *
  6594. * @augments TempNode
  6595. */
  6596. class ToneMappingNode extends TempNode {
  6597. static get type() {
  6598. return 'ToneMappingNode';
  6599. }
  6600. /**
  6601. * Constructs a new tone mapping node.
  6602. *
  6603. * @param {number} toneMapping - The tone mapping type.
  6604. * @param {Node} exposureNode - The tone mapping exposure.
  6605. * @param {Node} [colorNode=null] - The color node to process.
  6606. */
  6607. constructor( toneMapping, exposureNode = toneMappingExposure, colorNode = null ) {
  6608. super( 'vec3' );
  6609. /**
  6610. * The tone mapping type.
  6611. *
  6612. * @private
  6613. * @type {number}
  6614. */
  6615. this._toneMapping = toneMapping;
  6616. /**
  6617. * The tone mapping exposure.
  6618. *
  6619. * @type {Node}
  6620. * @default null
  6621. */
  6622. this.exposureNode = exposureNode;
  6623. /**
  6624. * Represents the color to process.
  6625. *
  6626. * @type {?Node}
  6627. * @default null
  6628. */
  6629. this.colorNode = colorNode;
  6630. }
  6631. /**
  6632. * Overwrites the default `customCacheKey()` implementation by including the tone
  6633. * mapping type into the cache key.
  6634. *
  6635. * @return {number} The hash.
  6636. */
  6637. customCacheKey() {
  6638. return hash$1( this._toneMapping );
  6639. }
  6640. /**
  6641. * Sets the tone mapping type.
  6642. *
  6643. * @param {number} value - The tone mapping type.
  6644. * @return {ToneMappingNode} A reference to this node.
  6645. */
  6646. setToneMapping( value ) {
  6647. this._toneMapping = value;
  6648. return this;
  6649. }
  6650. /**
  6651. * Gets the tone mapping type.
  6652. *
  6653. * @returns {number} The tone mapping type.
  6654. */
  6655. getToneMapping() {
  6656. return this._toneMapping;
  6657. }
  6658. setup( builder ) {
  6659. const colorNode = this.colorNode || builder.context.color;
  6660. const toneMapping = this._toneMapping;
  6661. if ( toneMapping === NoToneMapping ) return colorNode;
  6662. let outputNode = null;
  6663. const toneMappingFn = builder.renderer.library.getToneMappingFunction( toneMapping );
  6664. if ( toneMappingFn !== null ) {
  6665. outputNode = vec4( toneMappingFn( colorNode.rgb, this.exposureNode ), colorNode.a );
  6666. } else {
  6667. error( 'ToneMappingNode: Unsupported Tone Mapping configuration.', toneMapping );
  6668. outputNode = colorNode;
  6669. }
  6670. return outputNode;
  6671. }
  6672. }
  6673. /**
  6674. * TSL function for creating a tone mapping node.
  6675. *
  6676. * @tsl
  6677. * @function
  6678. * @param {number} mapping - The tone mapping type.
  6679. * @param {Node<float> | number} exposure - The tone mapping exposure.
  6680. * @param {Node<vec3> | Color} color - The color node to process.
  6681. * @returns {ToneMappingNode<vec3>}
  6682. */
  6683. const toneMapping = ( mapping, exposure, color ) => nodeObject( new ToneMappingNode( mapping, nodeObject( exposure ), nodeObject( color ) ) );
  6684. /**
  6685. * TSL object that represents the global tone mapping exposure of the renderer.
  6686. *
  6687. * @tsl
  6688. * @type {RendererReferenceNode<vec3>}
  6689. */
  6690. const toneMappingExposure = /*@__PURE__*/ rendererReference( 'toneMappingExposure', 'float' );
  6691. addMethodChaining( 'toneMapping', ( color, mapping, exposure ) => toneMapping( mapping, exposure, color ) );
  6692. /**
  6693. * Internal buffer attribute library.
  6694. *
  6695. * @private
  6696. * @type {WeakMap<TypedArray, InterleavedBuffer>}
  6697. */
  6698. const _bufferLib = new WeakMap();
  6699. /**
  6700. * Internal method for retrieving or creating interleaved buffers.
  6701. *
  6702. * @private
  6703. * @param {TypedArray} value - The attribute data.
  6704. * @param {number} itemSize - The attribute item size.
  6705. * @returns {InterleavedBuffer} The interleaved buffer.
  6706. */
  6707. function _getBufferAttribute( value, itemSize ) {
  6708. let buffer = _bufferLib.get( value );
  6709. if ( buffer === undefined ) {
  6710. buffer = new InterleavedBuffer( value, itemSize );
  6711. _bufferLib.set( value, buffer );
  6712. }
  6713. return buffer;
  6714. }
  6715. /**
  6716. * In earlier `three.js` versions it was only possible to define attribute data
  6717. * on geometry level. With `BufferAttributeNode`, it is also possible to do this
  6718. * on the node level.
  6719. * ```js
  6720. * const geometry = new THREE.PlaneGeometry();
  6721. * const positionAttribute = geometry.getAttribute( 'position' );
  6722. *
  6723. * const colors = [];
  6724. * for ( let i = 0; i < position.count; i ++ ) {
  6725. * colors.push( 1, 0, 0 );
  6726. * }
  6727. *
  6728. * material.colorNode = bufferAttribute( new THREE.Float32BufferAttribute( colors, 3 ) );
  6729. * ```
  6730. * This new approach is especially interesting when geometry data are generated via
  6731. * compute shaders. The below line converts a storage buffer into an attribute node.
  6732. * ```js
  6733. * material.positionNode = positionBuffer.toAttribute();
  6734. * ```
  6735. * @augments InputNode
  6736. */
  6737. class BufferAttributeNode extends InputNode {
  6738. static get type() {
  6739. return 'BufferAttributeNode';
  6740. }
  6741. /**
  6742. * Constructs a new buffer attribute node.
  6743. *
  6744. * @param {BufferAttribute|InterleavedBuffer|TypedArray} value - The attribute data.
  6745. * @param {?string} [bufferType=null] - The buffer type (e.g. `'vec3'`).
  6746. * @param {number} [bufferStride=0] - The buffer stride.
  6747. * @param {number} [bufferOffset=0] - The buffer offset.
  6748. */
  6749. constructor( value, bufferType = null, bufferStride = 0, bufferOffset = 0 ) {
  6750. super( value, bufferType );
  6751. /**
  6752. * This flag can be used for type testing.
  6753. *
  6754. * @type {boolean}
  6755. * @readonly
  6756. * @default true
  6757. */
  6758. this.isBufferNode = true;
  6759. /**
  6760. * The buffer type (e.g. `'vec3'`).
  6761. *
  6762. * @type {?string}
  6763. * @default null
  6764. */
  6765. this.bufferType = bufferType;
  6766. /**
  6767. * The buffer stride.
  6768. *
  6769. * @type {number}
  6770. * @default 0
  6771. */
  6772. this.bufferStride = bufferStride;
  6773. /**
  6774. * The buffer offset.
  6775. *
  6776. * @type {number}
  6777. * @default 0
  6778. */
  6779. this.bufferOffset = bufferOffset;
  6780. /**
  6781. * The usage property. Set this to `THREE.DynamicDrawUsage` via `.setUsage()`,
  6782. * if you are planning to update the attribute data per frame.
  6783. *
  6784. * @type {number}
  6785. * @default StaticDrawUsage
  6786. */
  6787. this.usage = StaticDrawUsage;
  6788. /**
  6789. * Whether the attribute is instanced or not.
  6790. *
  6791. * @type {boolean}
  6792. * @default false
  6793. */
  6794. this.instanced = false;
  6795. /**
  6796. * A reference to the buffer attribute.
  6797. *
  6798. * @type {?BufferAttribute}
  6799. * @default null
  6800. */
  6801. this.attribute = null;
  6802. /**
  6803. * `BufferAttributeNode` sets this property to `true` by default.
  6804. *
  6805. * @type {boolean}
  6806. * @default true
  6807. */
  6808. this.global = true;
  6809. if ( value && value.isBufferAttribute === true && value.itemSize <= 4 ) {
  6810. this.attribute = value;
  6811. this.usage = value.usage;
  6812. this.instanced = value.isInstancedBufferAttribute;
  6813. }
  6814. }
  6815. /**
  6816. * This method is overwritten since the attribute data might be shared
  6817. * and thus the hash should be shared as well.
  6818. *
  6819. * @param {NodeBuilder} builder - The current node builder.
  6820. * @return {string} The hash.
  6821. */
  6822. getHash( builder ) {
  6823. if ( this.bufferStride === 0 && this.bufferOffset === 0 ) {
  6824. let bufferData = builder.globalCache.getData( this.value );
  6825. if ( bufferData === undefined ) {
  6826. bufferData = {
  6827. node: this
  6828. };
  6829. builder.globalCache.setData( this.value, bufferData );
  6830. }
  6831. return bufferData.node.uuid;
  6832. }
  6833. return this.uuid;
  6834. }
  6835. /**
  6836. * This method is overwritten since the node type is inferred from
  6837. * the buffer attribute.
  6838. *
  6839. * @param {NodeBuilder} builder - The current node builder.
  6840. * @return {string} The node type.
  6841. */
  6842. getNodeType( builder ) {
  6843. if ( this.bufferType === null ) {
  6844. this.bufferType = builder.getTypeFromAttribute( this.attribute );
  6845. }
  6846. return this.bufferType;
  6847. }
  6848. /**
  6849. * Depending on which value was passed to the node, `setup()` behaves
  6850. * differently. If no instance of `BufferAttribute` was passed, the method
  6851. * creates an internal attribute and configures it respectively.
  6852. *
  6853. * @param {NodeBuilder} builder - The current node builder.
  6854. */
  6855. setup( builder ) {
  6856. if ( this.attribute !== null ) return;
  6857. //
  6858. const type = this.getNodeType( builder );
  6859. const itemSize = builder.getTypeLength( type );
  6860. const value = this.value;
  6861. const stride = this.bufferStride || itemSize;
  6862. const offset = this.bufferOffset;
  6863. let buffer;
  6864. if ( value.isInterleavedBuffer === true ) {
  6865. buffer = value;
  6866. } else if ( value.isBufferAttribute === true ) {
  6867. buffer = _getBufferAttribute( value.array, stride );
  6868. } else {
  6869. buffer = _getBufferAttribute( value, stride );
  6870. }
  6871. const bufferAttribute = new InterleavedBufferAttribute( buffer, itemSize, offset );
  6872. buffer.setUsage( this.usage );
  6873. this.attribute = bufferAttribute;
  6874. this.attribute.isInstancedBufferAttribute = this.instanced; // @TODO: Add a possible: InstancedInterleavedBufferAttribute
  6875. }
  6876. /**
  6877. * Generates the code snippet of the buffer attribute node.
  6878. *
  6879. * @param {NodeBuilder} builder - The current node builder.
  6880. * @return {string} The generated code snippet.
  6881. */
  6882. generate( builder ) {
  6883. const nodeType = this.getNodeType( builder );
  6884. const nodeAttribute = builder.getBufferAttributeFromNode( this, nodeType );
  6885. const propertyName = builder.getPropertyName( nodeAttribute );
  6886. let output = null;
  6887. if ( builder.shaderStage === 'vertex' || builder.shaderStage === 'compute' ) {
  6888. this.name = propertyName;
  6889. output = propertyName;
  6890. } else {
  6891. const nodeVarying = varying( this );
  6892. output = nodeVarying.build( builder, nodeType );
  6893. }
  6894. return output;
  6895. }
  6896. /**
  6897. * Overwrites the default implementation to return a fixed value `'bufferAttribute'`.
  6898. *
  6899. * @param {NodeBuilder} builder - The current node builder.
  6900. * @return {string} The input type.
  6901. */
  6902. getInputType( /*builder*/ ) {
  6903. return 'bufferAttribute';
  6904. }
  6905. /**
  6906. * Sets the `usage` property to the given value.
  6907. *
  6908. * @param {number} value - The usage to set.
  6909. * @return {BufferAttributeNode} A reference to this node.
  6910. */
  6911. setUsage( value ) {
  6912. this.usage = value;
  6913. if ( this.attribute && this.attribute.isBufferAttribute === true ) {
  6914. this.attribute.usage = value;
  6915. }
  6916. return this;
  6917. }
  6918. /**
  6919. * Sets the `instanced` property to the given value.
  6920. *
  6921. * @param {boolean} value - The value to set.
  6922. * @return {BufferAttributeNode} A reference to this node.
  6923. */
  6924. setInstanced( value ) {
  6925. this.instanced = value;
  6926. return this;
  6927. }
  6928. }
  6929. /**
  6930. * Internal method for creating buffer attribute nodes.
  6931. *
  6932. * @private
  6933. * @param {BufferAttribute|InterleavedBuffer|TypedArray} array - The attribute data.
  6934. * @param {?string} [type=null] - The buffer type (e.g. `'vec3'`).
  6935. * @param {number} [stride=0] - The buffer stride.
  6936. * @param {number} [offset=0] - The buffer offset.
  6937. * @param {number} [usage=StaticDrawUsage] - The buffer usage.
  6938. * @param {boolean} [instanced=false] - Whether the buffer is instanced.
  6939. * @returns {BufferAttributeNode|Node} The buffer attribute node.
  6940. */
  6941. function createBufferAttribute( array, type = null, stride = 0, offset = 0, usage = StaticDrawUsage, instanced = false ) {
  6942. if ( type === 'mat3' || ( type === null && array.itemSize === 9 ) ) {
  6943. return mat3(
  6944. new BufferAttributeNode( array, 'vec3', 9, 0 ).setUsage( usage ).setInstanced( instanced ),
  6945. new BufferAttributeNode( array, 'vec3', 9, 3 ).setUsage( usage ).setInstanced( instanced ),
  6946. new BufferAttributeNode( array, 'vec3', 9, 6 ).setUsage( usage ).setInstanced( instanced )
  6947. );
  6948. } else if ( type === 'mat4' || ( type === null && array.itemSize === 16 ) ) {
  6949. return mat4(
  6950. new BufferAttributeNode( array, 'vec4', 16, 0 ).setUsage( usage ).setInstanced( instanced ),
  6951. new BufferAttributeNode( array, 'vec4', 16, 4 ).setUsage( usage ).setInstanced( instanced ),
  6952. new BufferAttributeNode( array, 'vec4', 16, 8 ).setUsage( usage ).setInstanced( instanced ),
  6953. new BufferAttributeNode( array, 'vec4', 16, 12 ).setUsage( usage ).setInstanced( instanced )
  6954. );
  6955. }
  6956. return new BufferAttributeNode( array, type, stride, offset );
  6957. }
  6958. /**
  6959. * TSL function for creating a buffer attribute node.
  6960. *
  6961. * @tsl
  6962. * @function
  6963. * @param {BufferAttribute|InterleavedBuffer|TypedArray} array - The attribute data.
  6964. * @param {?string} [type=null] - The buffer type (e.g. `'vec3'`).
  6965. * @param {number} [stride=0] - The buffer stride.
  6966. * @param {number} [offset=0] - The buffer offset.
  6967. * @returns {BufferAttributeNode|Node}
  6968. */
  6969. const bufferAttribute = ( array, type = null, stride = 0, offset = 0 ) => createBufferAttribute( array, type, stride, offset );
  6970. /**
  6971. * TSL function for creating a buffer attribute node but with dynamic draw usage.
  6972. * Use this function if attribute data are updated per frame.
  6973. *
  6974. * @tsl
  6975. * @function
  6976. * @param {BufferAttribute|InterleavedBuffer|TypedArray} array - The attribute data.
  6977. * @param {?string} [type=null] - The buffer type (e.g. `'vec3'`).
  6978. * @param {number} [stride=0] - The buffer stride.
  6979. * @param {number} [offset=0] - The buffer offset.
  6980. * @returns {BufferAttributeNode|Node}
  6981. */
  6982. const dynamicBufferAttribute = ( array, type = null, stride = 0, offset = 0 ) => createBufferAttribute( array, type, stride, offset, DynamicDrawUsage );
  6983. /**
  6984. * TSL function for creating a buffer attribute node but with enabled instancing
  6985. *
  6986. * @tsl
  6987. * @function
  6988. * @param {BufferAttribute|InterleavedBuffer|TypedArray} array - The attribute data.
  6989. * @param {?string} [type=null] - The buffer type (e.g. `'vec3'`).
  6990. * @param {number} [stride=0] - The buffer stride.
  6991. * @param {number} [offset=0] - The buffer offset.
  6992. * @returns {BufferAttributeNode|Node}
  6993. */
  6994. const instancedBufferAttribute = ( array, type = null, stride = 0, offset = 0 ) => createBufferAttribute( array, type, stride, offset, StaticDrawUsage, true );
  6995. /**
  6996. * TSL function for creating a buffer attribute node but with dynamic draw usage and enabled instancing
  6997. *
  6998. * @tsl
  6999. * @function
  7000. * @param {BufferAttribute|InterleavedBuffer|TypedArray} array - The attribute data.
  7001. * @param {?string} [type=null] - The buffer type (e.g. `'vec3'`).
  7002. * @param {number} [stride=0] - The buffer stride.
  7003. * @param {number} [offset=0] - The buffer offset.
  7004. * @returns {BufferAttributeNode|Node}
  7005. */
  7006. const instancedDynamicBufferAttribute = ( array, type = null, stride = 0, offset = 0 ) => createBufferAttribute( array, type, stride, offset, DynamicDrawUsage, true );
  7007. addMethodChaining( 'toAttribute', ( bufferNode ) => bufferAttribute( bufferNode.value ) );
  7008. /**
  7009. * TODO
  7010. *
  7011. * @augments Node
  7012. */
  7013. class ComputeNode extends Node {
  7014. static get type() {
  7015. return 'ComputeNode';
  7016. }
  7017. /**
  7018. * Constructs a new compute node.
  7019. *
  7020. * @param {Node} computeNode - TODO
  7021. * @param {Array<number>} workgroupSize - TODO.
  7022. */
  7023. constructor( computeNode, workgroupSize ) {
  7024. super( 'void' );
  7025. /**
  7026. * This flag can be used for type testing.
  7027. *
  7028. * @type {boolean}
  7029. * @readonly
  7030. * @default true
  7031. */
  7032. this.isComputeNode = true;
  7033. /**
  7034. * TODO
  7035. *
  7036. * @type {Node}
  7037. */
  7038. this.computeNode = computeNode;
  7039. /**
  7040. * TODO
  7041. *
  7042. * @type {Array<number>}
  7043. * @default [ 64 ]
  7044. */
  7045. this.workgroupSize = workgroupSize;
  7046. /**
  7047. * TODO
  7048. *
  7049. * @type {number|Array<number>}
  7050. */
  7051. this.count = null;
  7052. /**
  7053. * TODO
  7054. *
  7055. * @type {number}
  7056. */
  7057. this.version = 1;
  7058. /**
  7059. * The name or label of the uniform.
  7060. *
  7061. * @type {string}
  7062. * @default ''
  7063. */
  7064. this.name = '';
  7065. /**
  7066. * The `updateBeforeType` is set to `NodeUpdateType.OBJECT` since {@link ComputeNode#updateBefore}
  7067. * is executed once per object by default.
  7068. *
  7069. * @type {string}
  7070. * @default 'object'
  7071. */
  7072. this.updateBeforeType = NodeUpdateType.OBJECT;
  7073. /**
  7074. * TODO
  7075. *
  7076. * @type {?Function}
  7077. */
  7078. this.onInitFunction = null;
  7079. }
  7080. /**
  7081. * TODO
  7082. *
  7083. * @param {number|Array<number>} count - Array with [ x, y, z ] values for dispatch or a single number for the count
  7084. * @return {ComputeNode}
  7085. */
  7086. setCount( count ) {
  7087. this.count = count;
  7088. return this;
  7089. }
  7090. /**
  7091. * TODO
  7092. *
  7093. * @return {number|Array<number>}
  7094. */
  7095. getCount() {
  7096. return this.count;
  7097. }
  7098. /**
  7099. * Executes the `dispose` event for this node.
  7100. */
  7101. dispose() {
  7102. this.dispatchEvent( { type: 'dispose' } );
  7103. }
  7104. /**
  7105. * Sets the {@link ComputeNode#name} property.
  7106. *
  7107. * @param {string} name - The name of the uniform.
  7108. * @return {ComputeNode} A reference to this node.
  7109. */
  7110. setName( name ) {
  7111. this.name = name;
  7112. return this;
  7113. }
  7114. /**
  7115. * Sets the {@link ComputeNode#name} property.
  7116. *
  7117. * @deprecated
  7118. * @param {string} name - The name of the uniform.
  7119. * @return {ComputeNode} A reference to this node.
  7120. */
  7121. label( name ) {
  7122. warn( 'TSL: "label()" has been deprecated. Use "setName()" instead.' ); // @deprecated r179
  7123. return this.setName( name );
  7124. }
  7125. /**
  7126. * TODO
  7127. *
  7128. * @param {Function} callback - TODO.
  7129. * @return {ComputeNode} A reference to this node.
  7130. */
  7131. onInit( callback ) {
  7132. this.onInitFunction = callback;
  7133. return this;
  7134. }
  7135. /**
  7136. * The method execute the compute for this node.
  7137. *
  7138. * @param {NodeFrame} frame - A reference to the current node frame.
  7139. */
  7140. updateBefore( { renderer } ) {
  7141. renderer.compute( this );
  7142. }
  7143. setup( builder ) {
  7144. const result = this.computeNode.build( builder );
  7145. if ( result ) {
  7146. const properties = builder.getNodeProperties( this );
  7147. properties.outputComputeNode = result.outputNode;
  7148. result.outputNode = null;
  7149. }
  7150. return result;
  7151. }
  7152. generate( builder, output ) {
  7153. const { shaderStage } = builder;
  7154. if ( shaderStage === 'compute' ) {
  7155. const snippet = this.computeNode.build( builder, 'void' );
  7156. if ( snippet !== '' ) {
  7157. builder.addLineFlowCode( snippet, this );
  7158. }
  7159. } else {
  7160. const properties = builder.getNodeProperties( this );
  7161. const outputComputeNode = properties.outputComputeNode;
  7162. if ( outputComputeNode ) {
  7163. return outputComputeNode.build( builder, output );
  7164. }
  7165. }
  7166. }
  7167. }
  7168. /**
  7169. * TSL function for creating a compute kernel node.
  7170. *
  7171. * @tsl
  7172. * @function
  7173. * @param {Node} node - TODO
  7174. * @param {Array<number>} [workgroupSize=[64]] - TODO.
  7175. * @returns {AtomicFunctionNode}
  7176. */
  7177. const computeKernel = ( node, workgroupSize = [ 64 ] ) => {
  7178. if ( workgroupSize.length === 0 || workgroupSize.length > 3 ) {
  7179. error( 'TSL: compute() workgroupSize must have 1, 2, or 3 elements' );
  7180. }
  7181. for ( let i = 0; i < workgroupSize.length; i ++ ) {
  7182. const val = workgroupSize[ i ];
  7183. if ( typeof val !== 'number' || val <= 0 || ! Number.isInteger( val ) ) {
  7184. error( `TSL: compute() workgroupSize element at index [ ${ i } ] must be a positive integer` );
  7185. }
  7186. }
  7187. // Implicit fill-up to [ x, y, z ] with 1s, just like WGSL treats @workgroup_size when fewer dimensions are specified
  7188. while ( workgroupSize.length < 3 ) workgroupSize.push( 1 );
  7189. //
  7190. return nodeObject( new ComputeNode( nodeObject( node ), workgroupSize ) );
  7191. };
  7192. /**
  7193. * TSL function for creating a compute node.
  7194. *
  7195. * @tsl
  7196. * @function
  7197. * @param {Node} node - TODO
  7198. * @param {number|Array<number>} count - TODO.
  7199. * @param {Array<number>} [workgroupSize=[64]] - TODO.
  7200. * @returns {AtomicFunctionNode}
  7201. */
  7202. const compute = ( node, count, workgroupSize ) => computeKernel( node, workgroupSize ).setCount( count );
  7203. addMethodChaining( 'compute', compute );
  7204. addMethodChaining( 'computeKernel', computeKernel );
  7205. /**
  7206. * This node can be used as a cache management component for another node.
  7207. * Caching is in general used by default in {@link NodeBuilder} but this node
  7208. * allows the usage of a shared parent cache during the build process.
  7209. *
  7210. * @augments Node
  7211. */
  7212. class IsolateNode extends Node {
  7213. static get type() {
  7214. return 'IsolateNode';
  7215. }
  7216. /**
  7217. * Constructs a new cache node.
  7218. *
  7219. * @param {Node} node - The node that should be cached.
  7220. * @param {boolean} [parent=true] - Whether this node refers to a shared parent cache or not.
  7221. */
  7222. constructor( node, parent = true ) {
  7223. super();
  7224. /**
  7225. * The node that should be cached.
  7226. *
  7227. * @type {Node}
  7228. */
  7229. this.node = node;
  7230. /**
  7231. * Whether this node refers to a shared parent cache or not.
  7232. *
  7233. * @type {boolean}
  7234. * @default true
  7235. */
  7236. this.parent = parent;
  7237. /**
  7238. * This flag can be used for type testing.
  7239. *
  7240. * @type {boolean}
  7241. * @readonly
  7242. * @default true
  7243. */
  7244. this.isIsolateNode = true;
  7245. }
  7246. getNodeType( builder ) {
  7247. const previousCache = builder.getCache();
  7248. const cache = builder.getCacheFromNode( this, this.parent );
  7249. builder.setCache( cache );
  7250. const nodeType = this.node.getNodeType( builder );
  7251. builder.setCache( previousCache );
  7252. return nodeType;
  7253. }
  7254. build( builder, ...params ) {
  7255. const previousCache = builder.getCache();
  7256. const cache = builder.getCacheFromNode( this, this.parent );
  7257. builder.setCache( cache );
  7258. const data = this.node.build( builder, ...params );
  7259. builder.setCache( previousCache );
  7260. return data;
  7261. }
  7262. setParent( parent ) {
  7263. this.parent = parent;
  7264. return this;
  7265. }
  7266. getParent() {
  7267. return this.parent;
  7268. }
  7269. }
  7270. /**
  7271. * TSL function for creating a cache node.
  7272. *
  7273. * @tsl
  7274. * @function
  7275. * @param {Node} node - The node that should be cached.
  7276. * @returns {IsolateNode}
  7277. */
  7278. const isolate = ( node ) => new IsolateNode( nodeObject( node ) );
  7279. /**
  7280. * TSL function for creating a cache node.
  7281. *
  7282. * @tsl
  7283. * @function
  7284. * @deprecated
  7285. * @param {Node} node - The node that should be cached.
  7286. * @param {boolean} [parent=true] - Whether this node refers to a shared parent cache or not.
  7287. * @returns {IsolateNode}
  7288. */
  7289. function cache( node, parent = true ) {
  7290. warn( 'TSL: "cache()" has been deprecated. Use "isolate()" instead.' ); // @deprecated r181
  7291. return isolate( node ).setParent( parent );
  7292. }
  7293. addMethodChaining( 'cache', cache );
  7294. addMethodChaining( 'isolate', isolate );
  7295. /**
  7296. * The class generates the code of a given node but returns another node in the output.
  7297. * This can be used to call a method or node that does not return a value, i.e.
  7298. * type `void` on an input where returning a value is required. Example:
  7299. *
  7300. * ```js
  7301. * material.colorNode = myColor.bypass( runVoidFn() )
  7302. *```
  7303. *
  7304. * @augments Node
  7305. */
  7306. class BypassNode extends Node {
  7307. static get type() {
  7308. return 'BypassNode';
  7309. }
  7310. /**
  7311. * Constructs a new bypass node.
  7312. *
  7313. * @param {Node} outputNode - The output node.
  7314. * @param {Node} callNode - The call node.
  7315. */
  7316. constructor( outputNode, callNode ) {
  7317. super();
  7318. /**
  7319. * This flag can be used for type testing.
  7320. *
  7321. * @type {boolean}
  7322. * @readonly
  7323. * @default true
  7324. */
  7325. this.isBypassNode = true;
  7326. /**
  7327. * The output node.
  7328. *
  7329. * @type {Node}
  7330. */
  7331. this.outputNode = outputNode;
  7332. /**
  7333. * The call node.
  7334. *
  7335. * @type {Node}
  7336. */
  7337. this.callNode = callNode;
  7338. }
  7339. getNodeType( builder ) {
  7340. return this.outputNode.getNodeType( builder );
  7341. }
  7342. generate( builder ) {
  7343. const snippet = this.callNode.build( builder, 'void' );
  7344. if ( snippet !== '' ) {
  7345. builder.addLineFlowCode( snippet, this );
  7346. }
  7347. return this.outputNode.build( builder );
  7348. }
  7349. }
  7350. /**
  7351. * TSL function for creating a bypass node.
  7352. *
  7353. * @tsl
  7354. * @function
  7355. * @param {Node} outputNode - The output node.
  7356. * @param {Node} callNode - The call node.
  7357. * @returns {BypassNode}
  7358. */
  7359. const bypass = /*@__PURE__*/ nodeProxy( BypassNode ).setParameterLength( 2 );
  7360. addMethodChaining( 'bypass', bypass );
  7361. /**
  7362. * This node allows to remap a node value from one range into another. E.g a value of
  7363. * `0.4` in the range `[ 0.3, 0.5 ]` should be remapped into the normalized range `[ 0, 1 ]`.
  7364. * `RemapNode` takes care of that and converts the original value of `0.4` to `0.5`.
  7365. *
  7366. * @augments Node
  7367. */
  7368. class RemapNode extends Node {
  7369. static get type() {
  7370. return 'RemapNode';
  7371. }
  7372. /**
  7373. * Constructs a new remap node.
  7374. *
  7375. * @param {Node} node - The node that should be remapped.
  7376. * @param {Node} inLowNode - The source or current lower bound of the range.
  7377. * @param {Node} inHighNode - The source or current upper bound of the range.
  7378. * @param {Node} [outLowNode=float(0)] - The target lower bound of the range.
  7379. * @param {Node} [outHighNode=float(1)] - The target upper bound of the range.
  7380. */
  7381. constructor( node, inLowNode, inHighNode, outLowNode = float( 0 ), outHighNode = float( 1 ) ) {
  7382. super();
  7383. /**
  7384. * The node that should be remapped.
  7385. *
  7386. * @type {Node}
  7387. */
  7388. this.node = node;
  7389. /**
  7390. * The source or current lower bound of the range.
  7391. *
  7392. * @type {Node}
  7393. */
  7394. this.inLowNode = inLowNode;
  7395. /**
  7396. * The source or current upper bound of the range.
  7397. *
  7398. * @type {Node}
  7399. */
  7400. this.inHighNode = inHighNode;
  7401. /**
  7402. * The target lower bound of the range.
  7403. *
  7404. * @type {Node}
  7405. * @default float(0)
  7406. */
  7407. this.outLowNode = outLowNode;
  7408. /**
  7409. * The target upper bound of the range.
  7410. *
  7411. * @type {Node}
  7412. * @default float(1)
  7413. */
  7414. this.outHighNode = outHighNode;
  7415. /**
  7416. * Whether the node value should be clamped before
  7417. * remapping it to the target range.
  7418. *
  7419. * @type {boolean}
  7420. * @default true
  7421. */
  7422. this.doClamp = true;
  7423. }
  7424. setup() {
  7425. const { node, inLowNode, inHighNode, outLowNode, outHighNode, doClamp } = this;
  7426. let t = node.sub( inLowNode ).div( inHighNode.sub( inLowNode ) );
  7427. if ( doClamp === true ) t = t.clamp();
  7428. return t.mul( outHighNode.sub( outLowNode ) ).add( outLowNode );
  7429. }
  7430. }
  7431. /**
  7432. * TSL function for creating a remap node.
  7433. *
  7434. * @tsl
  7435. * @function
  7436. * @param {Node} node - The node that should be remapped.
  7437. * @param {Node} inLowNode - The source or current lower bound of the range.
  7438. * @param {Node} inHighNode - The source or current upper bound of the range.
  7439. * @param {?Node} [outLowNode=float(0)] - The target lower bound of the range.
  7440. * @param {?Node} [outHighNode=float(1)] - The target upper bound of the range.
  7441. * @returns {RemapNode}
  7442. */
  7443. const remap = /*@__PURE__*/ nodeProxy( RemapNode, null, null, { doClamp: false } ).setParameterLength( 3, 5 );
  7444. /**
  7445. * TSL function for creating a remap node, but with enabled clamping.
  7446. *
  7447. * @tsl
  7448. * @function
  7449. * @param {Node} node - The node that should be remapped.
  7450. * @param {Node} inLowNode - The source or current lower bound of the range.
  7451. * @param {Node} inHighNode - The source or current upper bound of the range.
  7452. * @param {?Node} [outLowNode=float(0)] - The target lower bound of the range.
  7453. * @param {?Node} [outHighNode=float(1)] - The target upper bound of the range.
  7454. * @returns {RemapNode}
  7455. */
  7456. const remapClamp = /*@__PURE__*/ nodeProxy( RemapNode ).setParameterLength( 3, 5 );
  7457. addMethodChaining( 'remap', remap );
  7458. addMethodChaining( 'remapClamp', remapClamp );
  7459. /**
  7460. * This class can be used to implement basic expressions in shader code.
  7461. * Basic examples for that are `return`, `continue` or `discard` statements.
  7462. *
  7463. * @augments Node
  7464. */
  7465. class ExpressionNode extends Node {
  7466. static get type() {
  7467. return 'ExpressionNode';
  7468. }
  7469. /**
  7470. * Constructs a new expression node.
  7471. *
  7472. * @param {string} [snippet=''] - The native code snippet.
  7473. * @param {string} [nodeType='void'] - The node type.
  7474. */
  7475. constructor( snippet = '', nodeType = 'void' ) {
  7476. super( nodeType );
  7477. /**
  7478. * The native code snippet.
  7479. *
  7480. * @type {string}
  7481. * @default ''
  7482. */
  7483. this.snippet = snippet;
  7484. }
  7485. generate( builder, output ) {
  7486. const type = this.getNodeType( builder );
  7487. const snippet = this.snippet;
  7488. if ( type === 'void' ) {
  7489. builder.addLineFlowCode( snippet, this );
  7490. } else {
  7491. return builder.format( snippet, type, output );
  7492. }
  7493. }
  7494. }
  7495. /**
  7496. * TSL function for creating an expression node.
  7497. *
  7498. * @tsl
  7499. * @function
  7500. * @param {string} [snippet] - The native code snippet.
  7501. * @param {?string} [nodeType='void'] - The node type.
  7502. * @returns {ExpressionNode}
  7503. */
  7504. const expression = /*@__PURE__*/ nodeProxy( ExpressionNode ).setParameterLength( 1, 2 );
  7505. /**
  7506. * Represents a `discard` shader operation in TSL.
  7507. *
  7508. * @tsl
  7509. * @function
  7510. * @param {?ConditionalNode} conditional - An optional conditional node. It allows to decide whether the discard should be executed or not.
  7511. * @return {Node} The `discard` expression.
  7512. */
  7513. const Discard = ( conditional ) => ( conditional ? select( conditional, expression( 'discard' ) ) : expression( 'discard' ) ).toStack();
  7514. /**
  7515. * Represents a `return` shader operation in TSL.
  7516. *
  7517. * @tsl
  7518. * @function
  7519. * @return {ExpressionNode} The `return` expression.
  7520. */
  7521. const Return = () => expression( 'return' ).toStack();
  7522. addMethodChaining( 'discard', Discard );
  7523. /**
  7524. * Normally, tone mapping and color conversion happens automatically
  7525. * before outputting pixel too the default (screen) framebuffer. In certain
  7526. * post processing setups this happens to late because certain effects
  7527. * require e.g. sRGB input. For such scenarios, `RenderOutputNode` can be used
  7528. * to apply tone mapping and color space conversion at an arbitrary point
  7529. * in the effect chain.
  7530. *
  7531. * When applying tone mapping and color space conversion manually with this node,
  7532. * you have to set {@link PostProcessing#outputColorTransform} to `false`.
  7533. *
  7534. * ```js
  7535. * const postProcessing = new PostProcessing( renderer );
  7536. * postProcessing.outputColorTransform = false;
  7537. *
  7538. * const scenePass = pass( scene, camera );
  7539. * const outputPass = renderOutput( scenePass );
  7540. *
  7541. * postProcessing.outputNode = outputPass;
  7542. * ```
  7543. *
  7544. * @augments TempNode
  7545. */
  7546. class RenderOutputNode extends TempNode {
  7547. static get type() {
  7548. return 'RenderOutputNode';
  7549. }
  7550. /**
  7551. * Constructs a new render output node.
  7552. *
  7553. * @param {Node} colorNode - The color node to process.
  7554. * @param {?number} toneMapping - The tone mapping type.
  7555. * @param {?string} outputColorSpace - The output color space.
  7556. */
  7557. constructor( colorNode, toneMapping, outputColorSpace ) {
  7558. super( 'vec4' );
  7559. /**
  7560. * The color node to process.
  7561. *
  7562. * @type {Node}
  7563. */
  7564. this.colorNode = colorNode;
  7565. /**
  7566. * The tone mapping type.
  7567. *
  7568. * @private
  7569. * @type {?number}
  7570. */
  7571. this._toneMapping = toneMapping;
  7572. /**
  7573. * The output color space.
  7574. *
  7575. * @type {?string}
  7576. */
  7577. this.outputColorSpace = outputColorSpace;
  7578. /**
  7579. * This flag can be used for type testing.
  7580. *
  7581. * @type {boolean}
  7582. * @readonly
  7583. * @default true
  7584. */
  7585. this.isRenderOutputNode = true;
  7586. }
  7587. /**
  7588. * Sets the tone mapping type.
  7589. *
  7590. * @param {number} value - The tone mapping type.
  7591. * @return {ToneMappingNode} A reference to this node.
  7592. */
  7593. setToneMapping( value ) {
  7594. this._toneMapping = value;
  7595. return this;
  7596. }
  7597. /**
  7598. * Gets the tone mapping type.
  7599. *
  7600. * @returns {number} The tone mapping type.
  7601. */
  7602. getToneMapping() {
  7603. return this._toneMapping;
  7604. }
  7605. setup( { context } ) {
  7606. let outputNode = this.colorNode || context.color;
  7607. // tone mapping
  7608. const toneMapping = ( this._toneMapping !== null ? this._toneMapping : context.toneMapping ) || NoToneMapping;
  7609. const outputColorSpace = ( this.outputColorSpace !== null ? this.outputColorSpace : context.outputColorSpace ) || NoColorSpace;
  7610. if ( toneMapping !== NoToneMapping ) {
  7611. outputNode = outputNode.toneMapping( toneMapping );
  7612. }
  7613. // working to output color space
  7614. if ( outputColorSpace !== NoColorSpace && outputColorSpace !== ColorManagement.workingColorSpace ) {
  7615. outputNode = outputNode.workingToColorSpace( outputColorSpace );
  7616. }
  7617. return outputNode;
  7618. }
  7619. }
  7620. /**
  7621. * TSL function for creating a posterize node.
  7622. *
  7623. * @tsl
  7624. * @function
  7625. * @param {Node} color - The color node to process.
  7626. * @param {?number} [toneMapping=null] - The tone mapping type.
  7627. * @param {?string} [outputColorSpace=null] - The output color space.
  7628. * @returns {RenderOutputNode}
  7629. */
  7630. const renderOutput = ( color, toneMapping = null, outputColorSpace = null ) => nodeObject( new RenderOutputNode( nodeObject( color ), toneMapping, outputColorSpace ) );
  7631. addMethodChaining( 'renderOutput', renderOutput );
  7632. class DebugNode extends TempNode {
  7633. static get type() {
  7634. return 'DebugNode';
  7635. }
  7636. constructor( node, callback = null ) {
  7637. super();
  7638. this.node = node;
  7639. this.callback = callback;
  7640. }
  7641. getNodeType( builder ) {
  7642. return this.node.getNodeType( builder );
  7643. }
  7644. setup( builder ) {
  7645. return this.node.build( builder );
  7646. }
  7647. analyze( builder ) {
  7648. return this.node.build( builder );
  7649. }
  7650. generate( builder ) {
  7651. const callback = this.callback;
  7652. const snippet = this.node.build( builder );
  7653. const title = '--- TSL debug - ' + builder.shaderStage + ' shader ---';
  7654. const border = '-'.repeat( title.length );
  7655. let code = '';
  7656. code += '// #' + title + '#\n';
  7657. code += builder.flow.code.replace( /^\t/mg, '' ) + '\n';
  7658. code += '/* ... */ ' + snippet + ' /* ... */\n';
  7659. code += '// #' + border + '#\n';
  7660. if ( callback !== null ) {
  7661. callback( builder, code );
  7662. } else {
  7663. log$1( code );
  7664. }
  7665. return snippet;
  7666. }
  7667. }
  7668. /**
  7669. * TSL function for creating a debug node.
  7670. *
  7671. * @tsl
  7672. * @function
  7673. * @param {Node} node - The node to debug.
  7674. * @param {?Function} [callback=null] - Optional callback function to handle the debug output.
  7675. * @returns {DebugNode}
  7676. */
  7677. const debug = ( node, callback = null ) => nodeObject( new DebugNode( nodeObject( node ), callback ) ).toStack();
  7678. addMethodChaining( 'debug', debug );
  7679. /**
  7680. * InspectorBase is the base class for all inspectors.
  7681. *
  7682. * @class InspectorBase
  7683. */
  7684. class InspectorBase {
  7685. /**
  7686. * Creates a new InspectorBase.
  7687. */
  7688. constructor() {
  7689. /**
  7690. * The renderer associated with this inspector.
  7691. *
  7692. * @type {WebGLRenderer}
  7693. * @private
  7694. */
  7695. this._renderer = null;
  7696. /**
  7697. * The current frame being processed.
  7698. *
  7699. * @type {Object}
  7700. */
  7701. this.currentFrame = null;
  7702. }
  7703. /**
  7704. * Returns the node frame for the current renderer.
  7705. *
  7706. * @return {Object} The node frame.
  7707. */
  7708. get nodeFrame() {
  7709. return this._renderer._nodes.nodeFrame;
  7710. }
  7711. /**
  7712. * Sets the renderer for this inspector.
  7713. *
  7714. * @param {WebGLRenderer} renderer - The renderer to associate with this inspector.
  7715. * @return {InspectorBase} This inspector instance.
  7716. */
  7717. setRenderer( renderer ) {
  7718. this._renderer = renderer;
  7719. return this;
  7720. }
  7721. /**
  7722. * Returns the renderer associated with this inspector.
  7723. *
  7724. * @return {WebGLRenderer} The associated renderer.
  7725. */
  7726. getRenderer() {
  7727. return this._renderer;
  7728. }
  7729. /**
  7730. * Initializes the inspector.
  7731. */
  7732. init() { }
  7733. /**
  7734. * Called when a frame begins.
  7735. */
  7736. begin() { }
  7737. /**
  7738. * Called when a frame ends.
  7739. */
  7740. finish() { }
  7741. /**
  7742. * Inspects a node.
  7743. *
  7744. * @param {Node} node - The node to inspect.
  7745. */
  7746. inspect( /*node*/ ) { }
  7747. /**
  7748. * When a compute operation is performed.
  7749. *
  7750. * @param {ComputeNode} computeNode - The compute node being executed.
  7751. * @param {number|Array<number>} dispatchSizeOrCount - The dispatch size or count.
  7752. */
  7753. computeAsync( /*computeNode, dispatchSizeOrCount*/ ) { }
  7754. /**
  7755. * Called when a compute operation begins.
  7756. *
  7757. * @param {string} uid - A unique identifier for the render context.
  7758. * @param {ComputeNode} computeNode - The compute node being executed.
  7759. */
  7760. beginCompute( /*uid, computeNode*/ ) { }
  7761. /**
  7762. * Called when a compute operation ends.
  7763. *
  7764. * @param {string} uid - A unique identifier for the render context.
  7765. * @param {ComputeNode} computeNode - The compute node being executed.
  7766. */
  7767. finishCompute( /*uid*/ ) { }
  7768. /**
  7769. * Called when a render operation begins.
  7770. *
  7771. * @param {string} uid - A unique identifier for the render context.
  7772. * @param {Scene} scene - The scene being rendered.
  7773. * @param {Camera} camera - The camera being used for rendering.
  7774. * @param {?WebGLRenderTarget} renderTarget - The render target, if any.
  7775. */
  7776. beginRender( /*uid, scene, camera, renderTarget*/ ) { }
  7777. /**
  7778. * Called when an animation loop ends.
  7779. *
  7780. * @param {string} uid - A unique identifier for the render context.
  7781. */
  7782. finishRender( /*uid*/ ) { }
  7783. /**
  7784. * Called when a texture copy operation is performed.
  7785. *
  7786. * @param {Texture} srcTexture - The source texture.
  7787. * @param {Texture} dstTexture - The destination texture.
  7788. */
  7789. copyTextureToTexture( /*srcTexture, dstTexture*/ ) { }
  7790. /**
  7791. * Called when a framebuffer copy operation is performed.
  7792. *
  7793. * @param {Texture} framebufferTexture - The texture associated with the framebuffer.
  7794. */
  7795. copyFramebufferToTexture( /*framebufferTexture*/ ) { }
  7796. }
  7797. /**
  7798. * InspectorNode is a wrapper node that allows inspection of node values during rendering.
  7799. * It can be used to debug or analyze node outputs in the rendering pipeline.
  7800. *
  7801. * @augments Node
  7802. */
  7803. class InspectorNode extends Node {
  7804. /**
  7805. * Returns the type of the node.
  7806. *
  7807. * @returns {string}
  7808. */
  7809. static get type() {
  7810. return 'InspectorNode';
  7811. }
  7812. /**
  7813. * Creates an InspectorNode.
  7814. *
  7815. * @param {Node} node - The node to inspect.
  7816. * @param {string} [name=''] - Optional name for the inspector node.
  7817. * @param {Function|null} [callback=null] - Optional callback to modify the node during setup.
  7818. */
  7819. constructor( node, name = '', callback = null ) {
  7820. super();
  7821. this.node = node;
  7822. this.name = name;
  7823. this.callback = callback;
  7824. this.updateType = NodeUpdateType.FRAME;
  7825. this.isInspectorNode = true;
  7826. }
  7827. /**
  7828. * Returns the name of the inspector node.
  7829. *
  7830. * @returns {string}
  7831. */
  7832. getName() {
  7833. return this.name || this.node.name;
  7834. }
  7835. /**
  7836. * Updates the inspector node, allowing inspection of the wrapped node.
  7837. *
  7838. * @param {NodeFrame} frame - A reference to the current node frame.
  7839. */
  7840. update( frame ) {
  7841. frame.renderer.inspector.inspect( this );
  7842. }
  7843. /**
  7844. * Returns the type of the wrapped node.
  7845. *
  7846. * @param {NodeBuilder} builder - The node builder.
  7847. * @returns {string}
  7848. */
  7849. getNodeType( builder ) {
  7850. return this.node.getNodeType( builder );
  7851. }
  7852. /**
  7853. * Sets up the inspector node.
  7854. *
  7855. * @param {NodeBuilder} builder - The node builder.
  7856. * @returns {Node} The setup node.
  7857. */
  7858. setup( builder ) {
  7859. let node = this.node;
  7860. if ( builder.context.inspector === true && this.callback !== null ) {
  7861. node = this.callback( node );
  7862. }
  7863. if ( builder.renderer.backend.isWebGPUBackend !== true && builder.renderer.inspector.constructor !== InspectorBase ) {
  7864. warnOnce( 'TSL: ".toInspector()" is only available with WebGPU.' );
  7865. }
  7866. return node;
  7867. }
  7868. }
  7869. /**
  7870. * Creates an inspector node to wrap around a given node for inspection purposes.
  7871. *
  7872. * @tsl
  7873. * @param {Node} node - The node to inspect.
  7874. * @param {string} [name=''] - Optional name for the inspector node.
  7875. * @param {Function|null} [callback=null] - Optional callback to modify the node during setup.
  7876. * @returns {Node} The inspector node.
  7877. */
  7878. function inspector( node, name = '', callback = null ) {
  7879. node = nodeObject( node );
  7880. return node.before( new InspectorNode( node, name, callback ) );
  7881. }
  7882. addMethodChaining( 'toInspector', inspector );
  7883. function addNodeElement( name/*, nodeElement*/ ) {
  7884. warn( 'TSL: AddNodeElement has been removed in favor of tree-shaking. Trying add', name );
  7885. }
  7886. /**
  7887. * Base class for representing shader attributes as nodes.
  7888. *
  7889. * @augments Node
  7890. */
  7891. class AttributeNode extends Node {
  7892. static get type() {
  7893. return 'AttributeNode';
  7894. }
  7895. /**
  7896. * Constructs a new attribute node.
  7897. *
  7898. * @param {string} attributeName - The name of the attribute.
  7899. * @param {?string} nodeType - The node type.
  7900. */
  7901. constructor( attributeName, nodeType = null ) {
  7902. super( nodeType );
  7903. /**
  7904. * `AttributeNode` sets this property to `true` by default.
  7905. *
  7906. * @type {boolean}
  7907. * @default true
  7908. */
  7909. this.global = true;
  7910. this._attributeName = attributeName;
  7911. }
  7912. getHash( builder ) {
  7913. return this.getAttributeName( builder );
  7914. }
  7915. getNodeType( builder ) {
  7916. let nodeType = this.nodeType;
  7917. if ( nodeType === null ) {
  7918. const attributeName = this.getAttributeName( builder );
  7919. if ( builder.hasGeometryAttribute( attributeName ) ) {
  7920. const attribute = builder.geometry.getAttribute( attributeName );
  7921. nodeType = builder.getTypeFromAttribute( attribute );
  7922. } else {
  7923. nodeType = 'float';
  7924. }
  7925. }
  7926. return nodeType;
  7927. }
  7928. /**
  7929. * Sets the attribute name to the given value. The method can be
  7930. * overwritten in derived classes if the final name must be computed
  7931. * analytically.
  7932. *
  7933. * @param {string} attributeName - The name of the attribute.
  7934. * @return {AttributeNode} A reference to this node.
  7935. */
  7936. setAttributeName( attributeName ) {
  7937. this._attributeName = attributeName;
  7938. return this;
  7939. }
  7940. /**
  7941. * Returns the attribute name of this node. The method can be
  7942. * overwritten in derived classes if the final name must be computed
  7943. * analytically.
  7944. *
  7945. * @param {NodeBuilder} builder - The current node builder.
  7946. * @return {string} The attribute name.
  7947. */
  7948. getAttributeName( /*builder*/ ) {
  7949. return this._attributeName;
  7950. }
  7951. generate( builder ) {
  7952. const attributeName = this.getAttributeName( builder );
  7953. const nodeType = this.getNodeType( builder );
  7954. const geometryAttribute = builder.hasGeometryAttribute( attributeName );
  7955. if ( geometryAttribute === true ) {
  7956. const attribute = builder.geometry.getAttribute( attributeName );
  7957. const attributeType = builder.getTypeFromAttribute( attribute );
  7958. const nodeAttribute = builder.getAttribute( attributeName, attributeType );
  7959. if ( builder.shaderStage === 'vertex' ) {
  7960. return builder.format( nodeAttribute.name, attributeType, nodeType );
  7961. } else {
  7962. const nodeVarying = varying( this );
  7963. return nodeVarying.build( builder, nodeType );
  7964. }
  7965. } else {
  7966. warn( `AttributeNode: Vertex attribute "${ attributeName }" not found on geometry.` );
  7967. return builder.generateConst( nodeType );
  7968. }
  7969. }
  7970. serialize( data ) {
  7971. super.serialize( data );
  7972. data.global = this.global;
  7973. data._attributeName = this._attributeName;
  7974. }
  7975. deserialize( data ) {
  7976. super.deserialize( data );
  7977. this.global = data.global;
  7978. this._attributeName = data._attributeName;
  7979. }
  7980. }
  7981. /**
  7982. * TSL function for creating an attribute node.
  7983. *
  7984. * @tsl
  7985. * @function
  7986. * @param {string} name - The name of the attribute.
  7987. * @param {?string} [nodeType=null] - The node type.
  7988. * @returns {AttributeNode}
  7989. */
  7990. const attribute = ( name, nodeType = null ) => nodeObject( new AttributeNode( name, nodeType ) );
  7991. /**
  7992. * TSL function for creating an uv attribute node with the given index.
  7993. *
  7994. * @tsl
  7995. * @function
  7996. * @param {number} [index=0] - The uv index.
  7997. * @return {AttributeNode<vec2>} The uv attribute node.
  7998. */
  7999. const uv$1 = ( index = 0 ) => attribute( 'uv' + ( index > 0 ? index : '' ), 'vec2' );
  8000. /**
  8001. * A node that represents the dimensions of a texture. The texture size is
  8002. * retrieved in the shader via built-in shader functions like `textureDimensions()`
  8003. * or `textureSize()`.
  8004. *
  8005. * @augments Node
  8006. */
  8007. class TextureSizeNode extends Node {
  8008. static get type() {
  8009. return 'TextureSizeNode';
  8010. }
  8011. /**
  8012. * Constructs a new texture size node.
  8013. *
  8014. * @param {TextureNode} textureNode - A texture node which size should be retrieved.
  8015. * @param {?Node<int>} [levelNode=null] - A level node which defines the requested mip.
  8016. */
  8017. constructor( textureNode, levelNode = null ) {
  8018. super( 'uvec2' );
  8019. /**
  8020. * This flag can be used for type testing.
  8021. *
  8022. * @type {boolean}
  8023. * @readonly
  8024. * @default true
  8025. */
  8026. this.isTextureSizeNode = true;
  8027. /**
  8028. * A texture node which size should be retrieved.
  8029. *
  8030. * @type {TextureNode}
  8031. */
  8032. this.textureNode = textureNode;
  8033. /**
  8034. * A level node which defines the requested mip.
  8035. *
  8036. * @type {Node<int>}
  8037. * @default null
  8038. */
  8039. this.levelNode = levelNode;
  8040. }
  8041. generate( builder, output ) {
  8042. const textureProperty = this.textureNode.build( builder, 'property' );
  8043. const level = this.levelNode === null ? '0' : this.levelNode.build( builder, 'int' );
  8044. return builder.format( `${ builder.getMethod( 'textureDimensions' ) }( ${ textureProperty }, ${ level } )`, this.getNodeType( builder ), output );
  8045. }
  8046. }
  8047. /**
  8048. * TSL function for creating a texture size node.
  8049. *
  8050. * @tsl
  8051. * @function
  8052. * @param {TextureNode} textureNode - A texture node which size should be retrieved.
  8053. * @param {?Node<int>} [levelNode=null] - A level node which defines the requested mip.
  8054. * @returns {TextureSizeNode}
  8055. */
  8056. const textureSize = /*@__PURE__*/ nodeProxy( TextureSizeNode ).setParameterLength( 1, 2 );
  8057. /**
  8058. * A special type of uniform node that computes the
  8059. * maximum mipmap level for a given texture node.
  8060. *
  8061. * ```js
  8062. * const level = maxMipLevel( textureNode );
  8063. * ```
  8064. *
  8065. * @augments UniformNode
  8066. */
  8067. class MaxMipLevelNode extends UniformNode {
  8068. static get type() {
  8069. return 'MaxMipLevelNode';
  8070. }
  8071. /**
  8072. * Constructs a new max mip level node.
  8073. *
  8074. * @param {TextureNode} textureNode - The texture node to compute the max mip level for.
  8075. */
  8076. constructor( textureNode ) {
  8077. super( 0 );
  8078. /**
  8079. * The texture node to compute the max mip level for.
  8080. *
  8081. * @private
  8082. * @type {TextureNode}
  8083. */
  8084. this._textureNode = textureNode;
  8085. /**
  8086. * The `updateType` is set to `NodeUpdateType.FRAME` since the node updates
  8087. * the texture once per frame in its {@link MaxMipLevelNode#update} method.
  8088. *
  8089. * @type {string}
  8090. * @default 'frame'
  8091. */
  8092. this.updateType = NodeUpdateType.FRAME;
  8093. }
  8094. /**
  8095. * The texture node to compute the max mip level for.
  8096. *
  8097. * @readonly
  8098. * @type {TextureNode}
  8099. */
  8100. get textureNode() {
  8101. return this._textureNode;
  8102. }
  8103. /**
  8104. * The texture.
  8105. *
  8106. * @readonly
  8107. * @type {Texture}
  8108. */
  8109. get texture() {
  8110. return this._textureNode.value;
  8111. }
  8112. update() {
  8113. const texture = this.texture;
  8114. const images = texture.images;
  8115. const image = ( images && images.length > 0 ) ? ( ( images[ 0 ] && images[ 0 ].image ) || images[ 0 ] ) : texture.image;
  8116. if ( image && image.width !== undefined ) {
  8117. const { width, height } = image;
  8118. this.value = Math.log2( Math.max( width, height ) );
  8119. }
  8120. }
  8121. }
  8122. /**
  8123. * TSL function for creating a max mip level node.
  8124. *
  8125. * @tsl
  8126. * @function
  8127. * @param {TextureNode} textureNode - The texture node to compute the max mip level for.
  8128. * @returns {MaxMipLevelNode}
  8129. */
  8130. const maxMipLevel = /*@__PURE__*/ nodeProxy( MaxMipLevelNode ).setParameterLength( 1 );
  8131. const EmptyTexture$1 = /*@__PURE__*/ new Texture();
  8132. /**
  8133. * This type of uniform node represents a 2D texture.
  8134. *
  8135. * @augments UniformNode
  8136. */
  8137. class TextureNode extends UniformNode {
  8138. static get type() {
  8139. return 'TextureNode';
  8140. }
  8141. /**
  8142. * Constructs a new texture node.
  8143. *
  8144. * @param {Texture} [value=EmptyTexture] - The texture.
  8145. * @param {?Node<vec2|vec3>} [uvNode=null] - The uv node.
  8146. * @param {?Node<int>} [levelNode=null] - The level node.
  8147. * @param {?Node<float>} [biasNode=null] - The bias node.
  8148. */
  8149. constructor( value = EmptyTexture$1, uvNode = null, levelNode = null, biasNode = null ) {
  8150. super( value );
  8151. /**
  8152. * This flag can be used for type testing.
  8153. *
  8154. * @type {boolean}
  8155. * @readonly
  8156. * @default true
  8157. */
  8158. this.isTextureNode = true;
  8159. /**
  8160. * Represents the texture coordinates.
  8161. *
  8162. * @type {?Node<vec2|vec3>}
  8163. * @default null
  8164. */
  8165. this.uvNode = uvNode;
  8166. /**
  8167. * Represents the mip level that should be selected.
  8168. *
  8169. * @type {?Node<int>}
  8170. * @default null
  8171. */
  8172. this.levelNode = levelNode;
  8173. /**
  8174. * Represents the bias to be applied during level-of-detail computation.
  8175. *
  8176. * @type {?Node<float>}
  8177. * @default null
  8178. */
  8179. this.biasNode = biasNode;
  8180. /**
  8181. * Represents a reference value a texture sample is compared to.
  8182. *
  8183. * @type {?Node<float>}
  8184. * @default null
  8185. */
  8186. this.compareNode = null;
  8187. /**
  8188. * When using texture arrays, the depth node defines the layer to select.
  8189. *
  8190. * @type {?Node<int>}
  8191. * @default null
  8192. */
  8193. this.depthNode = null;
  8194. /**
  8195. * When defined, a texture is sampled using explicit gradients.
  8196. *
  8197. * @type {?Array<Node<vec2>>}
  8198. * @default null
  8199. */
  8200. this.gradNode = null;
  8201. /**
  8202. * Represents the optional texel offset applied to the unnormalized texture
  8203. * coordinate before sampling the texture.
  8204. *
  8205. * @type {?Node<ivec2|ivec3>}
  8206. * @default null
  8207. */
  8208. this.offsetNode = null;
  8209. /**
  8210. * Whether texture values should be sampled or fetched.
  8211. *
  8212. * @type {boolean}
  8213. * @default true
  8214. */
  8215. this.sampler = true;
  8216. /**
  8217. * Whether the uv transformation matrix should be
  8218. * automatically updated or not. Use `setUpdateMatrix()`
  8219. * if you want to change the value of the property.
  8220. *
  8221. * @type {boolean}
  8222. * @default false
  8223. */
  8224. this.updateMatrix = false;
  8225. /**
  8226. * By default the `update()` method is not executed. Depending on
  8227. * whether a uv transformation matrix and/or flipY is applied, `update()`
  8228. * is executed per object.
  8229. *
  8230. * @type {string}
  8231. * @default 'none'
  8232. */
  8233. this.updateType = NodeUpdateType.NONE;
  8234. /**
  8235. * The reference node.
  8236. *
  8237. * @type {?Node}
  8238. * @default null
  8239. */
  8240. this.referenceNode = null;
  8241. /**
  8242. * The texture value is stored in a private property.
  8243. *
  8244. * @private
  8245. * @type {Texture}
  8246. */
  8247. this._value = value;
  8248. /**
  8249. * The uniform node that represents the uv transformation matrix.
  8250. *
  8251. * @private
  8252. * @type {?UniformNode<mat3>}
  8253. * @default null
  8254. */
  8255. this._matrixUniform = null;
  8256. /**
  8257. * The uniform node that represents the y-flip. Only required for WebGL.
  8258. *
  8259. * @private
  8260. * @type {?UniformNode<bool>}
  8261. * @default null
  8262. */
  8263. this._flipYUniform = null;
  8264. this.setUpdateMatrix( uvNode === null );
  8265. }
  8266. set value( value ) {
  8267. if ( this.referenceNode ) {
  8268. this.referenceNode.value = value;
  8269. } else {
  8270. this._value = value;
  8271. }
  8272. }
  8273. /**
  8274. * The texture value.
  8275. *
  8276. * @type {Texture}
  8277. */
  8278. get value() {
  8279. return this.referenceNode ? this.referenceNode.value : this._value;
  8280. }
  8281. /**
  8282. * Overwritten since the uniform hash is defined by the texture's UUID.
  8283. *
  8284. * @param {NodeBuilder} builder - The current node builder.
  8285. * @return {string} The uniform hash.
  8286. */
  8287. getUniformHash( /*builder*/ ) {
  8288. return this.value.uuid;
  8289. }
  8290. /**
  8291. * Overwritten since the node type is inferred from the texture type.
  8292. *
  8293. * @param {NodeBuilder} builder - The current node builder.
  8294. * @return {string} The node type.
  8295. */
  8296. getNodeType( /*builder*/ ) {
  8297. if ( this.value.isDepthTexture === true ) return 'float';
  8298. if ( this.value.type === UnsignedIntType ) {
  8299. return 'uvec4';
  8300. } else if ( this.value.type === IntType ) {
  8301. return 'ivec4';
  8302. }
  8303. return 'vec4';
  8304. }
  8305. /**
  8306. * Overwrites the default implementation to return a fixed value `'texture'`.
  8307. *
  8308. * @param {NodeBuilder} builder - The current node builder.
  8309. * @return {string} The input type.
  8310. */
  8311. getInputType( /*builder*/ ) {
  8312. return 'texture';
  8313. }
  8314. /**
  8315. * Returns a default uvs based on the current texture's channel.
  8316. *
  8317. * @return {AttributeNode<vec2>} The default uvs.
  8318. */
  8319. getDefaultUV() {
  8320. return uv$1( this.value.channel );
  8321. }
  8322. /**
  8323. * Overwritten to always return the texture reference of the node.
  8324. *
  8325. * @param {any} state - This method can be invocated in different contexts so `state` can refer to any object type.
  8326. * @return {Texture} The texture reference.
  8327. */
  8328. updateReference( /*state*/ ) {
  8329. return this.value;
  8330. }
  8331. /**
  8332. * Transforms the given uv node with the texture transformation matrix.
  8333. *
  8334. * @param {Node} uvNode - The uv node to transform.
  8335. * @return {Node} The transformed uv node.
  8336. */
  8337. getTransformedUV( uvNode ) {
  8338. if ( this._matrixUniform === null ) this._matrixUniform = uniform( this.value.matrix );
  8339. return this._matrixUniform.mul( vec3( uvNode, 1 ) ).xy;
  8340. }
  8341. /**
  8342. * Defines whether the uv transformation matrix should automatically be updated or not.
  8343. *
  8344. * @param {boolean} value - The update toggle.
  8345. * @return {TextureNode} A reference to this node.
  8346. */
  8347. setUpdateMatrix( value ) {
  8348. this.updateMatrix = value;
  8349. return this;
  8350. }
  8351. /**
  8352. * Setups the uv node. Depending on the backend as well as texture's image and type, it might be necessary
  8353. * to modify the uv node for correct sampling.
  8354. *
  8355. * @param {NodeBuilder} builder - The current node builder.
  8356. * @param {Node} uvNode - The uv node to setup.
  8357. * @return {Node} The updated uv node.
  8358. */
  8359. setupUV( builder, uvNode ) {
  8360. if ( builder.isFlipY() ) {
  8361. if ( this._flipYUniform === null ) this._flipYUniform = uniform( false );
  8362. uvNode = uvNode.toVar();
  8363. if ( this.sampler ) {
  8364. uvNode = this._flipYUniform.select( uvNode.flipY(), uvNode );
  8365. } else {
  8366. uvNode = this._flipYUniform.select( uvNode.setY( int( textureSize( this, this.levelNode ).y ).sub( uvNode.y ).sub( 1 ) ), uvNode );
  8367. }
  8368. }
  8369. return uvNode;
  8370. }
  8371. /**
  8372. * Setups texture node by preparing the internal nodes for code generation.
  8373. *
  8374. * @param {NodeBuilder} builder - The current node builder.
  8375. */
  8376. setup( builder ) {
  8377. const properties = builder.getNodeProperties( this );
  8378. properties.referenceNode = this.referenceNode;
  8379. //
  8380. const texture = this.value;
  8381. if ( ! texture || texture.isTexture !== true ) {
  8382. throw new Error( 'THREE.TSL: `texture( value )` function expects a valid instance of THREE.Texture().' );
  8383. }
  8384. //
  8385. const uvNode = Fn( () => {
  8386. let uvNode = this.uvNode;
  8387. if ( ( uvNode === null || builder.context.forceUVContext === true ) && builder.context.getUV ) {
  8388. uvNode = builder.context.getUV( this, builder );
  8389. }
  8390. if ( ! uvNode ) uvNode = this.getDefaultUV();
  8391. if ( this.updateMatrix === true ) {
  8392. uvNode = this.getTransformedUV( uvNode );
  8393. }
  8394. uvNode = this.setupUV( builder, uvNode );
  8395. //
  8396. this.updateType = ( this._matrixUniform !== null || this._flipYUniform !== null ) ? NodeUpdateType.OBJECT : NodeUpdateType.NONE;
  8397. //
  8398. return uvNode;
  8399. } )();
  8400. //
  8401. let levelNode = this.levelNode;
  8402. if ( levelNode === null && builder.context.getTextureLevel ) {
  8403. levelNode = builder.context.getTextureLevel( this );
  8404. }
  8405. //
  8406. properties.uvNode = uvNode;
  8407. properties.levelNode = levelNode;
  8408. properties.biasNode = this.biasNode;
  8409. properties.compareNode = this.compareNode;
  8410. properties.gradNode = this.gradNode;
  8411. properties.depthNode = this.depthNode;
  8412. properties.offsetNode = this.offsetNode;
  8413. }
  8414. /**
  8415. * Generates the uv code snippet.
  8416. *
  8417. * @param {NodeBuilder} builder - The current node builder.
  8418. * @param {Node} uvNode - The uv node to generate code for.
  8419. * @return {string} The generated code snippet.
  8420. */
  8421. generateUV( builder, uvNode ) {
  8422. return uvNode.build( builder, this.sampler === true ? 'vec2' : 'ivec2' );
  8423. }
  8424. /**
  8425. * Generates the offset code snippet.
  8426. *
  8427. * @param {NodeBuilder} builder - The current node builder.
  8428. * @param {Node} offsetNode - The offset node to generate code for.
  8429. * @return {string} The generated code snippet.
  8430. */
  8431. generateOffset( builder, offsetNode ) {
  8432. return offsetNode.build( builder, 'ivec2' );
  8433. }
  8434. /**
  8435. * Generates the snippet for the texture sampling.
  8436. *
  8437. * @param {NodeBuilder} builder - The current node builder.
  8438. * @param {string} textureProperty - The texture property.
  8439. * @param {string} uvSnippet - The uv snippet.
  8440. * @param {?string} levelSnippet - The level snippet.
  8441. * @param {?string} biasSnippet - The bias snippet.
  8442. * @param {?string} depthSnippet - The depth snippet.
  8443. * @param {?string} compareSnippet - The compare snippet.
  8444. * @param {?Array<string>} gradSnippet - The grad snippet.
  8445. * @param {?string} offsetSnippet - The offset snippet.
  8446. * @return {string} The generated code snippet.
  8447. */
  8448. generateSnippet( builder, textureProperty, uvSnippet, levelSnippet, biasSnippet, depthSnippet, compareSnippet, gradSnippet, offsetSnippet ) {
  8449. const texture = this.value;
  8450. let snippet;
  8451. if ( biasSnippet ) {
  8452. snippet = builder.generateTextureBias( texture, textureProperty, uvSnippet, biasSnippet, depthSnippet, offsetSnippet );
  8453. } else if ( gradSnippet ) {
  8454. snippet = builder.generateTextureGrad( texture, textureProperty, uvSnippet, gradSnippet, depthSnippet, offsetSnippet );
  8455. } else if ( compareSnippet ) {
  8456. snippet = builder.generateTextureCompare( texture, textureProperty, uvSnippet, compareSnippet, depthSnippet, offsetSnippet );
  8457. } else if ( this.sampler === false ) {
  8458. snippet = builder.generateTextureLoad( texture, textureProperty, uvSnippet, levelSnippet, depthSnippet, offsetSnippet );
  8459. } else if ( levelSnippet ) {
  8460. snippet = builder.generateTextureLevel( texture, textureProperty, uvSnippet, levelSnippet, depthSnippet, offsetSnippet );
  8461. } else {
  8462. snippet = builder.generateTexture( texture, textureProperty, uvSnippet, depthSnippet, offsetSnippet );
  8463. }
  8464. return snippet;
  8465. }
  8466. /**
  8467. * Generates the code snippet of the texture node.
  8468. *
  8469. * @param {NodeBuilder} builder - The current node builder.
  8470. * @param {string} output - The current output.
  8471. * @return {string} The generated code snippet.
  8472. */
  8473. generate( builder, output ) {
  8474. const texture = this.value;
  8475. const properties = builder.getNodeProperties( this );
  8476. const textureProperty = super.generate( builder, 'property' );
  8477. if ( /^sampler/.test( output ) ) {
  8478. return textureProperty + '_sampler';
  8479. } else if ( builder.isReference( output ) ) {
  8480. return textureProperty;
  8481. } else {
  8482. const nodeData = builder.getDataFromNode( this );
  8483. let propertyName = nodeData.propertyName;
  8484. if ( propertyName === undefined ) {
  8485. const { uvNode, levelNode, biasNode, compareNode, depthNode, gradNode, offsetNode } = properties;
  8486. const uvSnippet = this.generateUV( builder, uvNode );
  8487. const levelSnippet = levelNode ? levelNode.build( builder, 'float' ) : null;
  8488. const biasSnippet = biasNode ? biasNode.build( builder, 'float' ) : null;
  8489. const depthSnippet = depthNode ? depthNode.build( builder, 'int' ) : null;
  8490. const compareSnippet = compareNode ? compareNode.build( builder, 'float' ) : null;
  8491. const gradSnippet = gradNode ? [ gradNode[ 0 ].build( builder, 'vec2' ), gradNode[ 1 ].build( builder, 'vec2' ) ] : null;
  8492. const offsetSnippet = offsetNode ? this.generateOffset( builder, offsetNode ) : null;
  8493. const nodeVar = builder.getVarFromNode( this );
  8494. propertyName = builder.getPropertyName( nodeVar );
  8495. const snippet = this.generateSnippet( builder, textureProperty, uvSnippet, levelSnippet, biasSnippet, depthSnippet, compareSnippet, gradSnippet, offsetSnippet );
  8496. builder.addLineFlowCode( `${propertyName} = ${snippet}`, this );
  8497. nodeData.snippet = snippet;
  8498. nodeData.propertyName = propertyName;
  8499. }
  8500. let snippet = propertyName;
  8501. const nodeType = this.getNodeType( builder );
  8502. if ( builder.needsToWorkingColorSpace( texture ) ) {
  8503. snippet = colorSpaceToWorking( expression( snippet, nodeType ), texture.colorSpace ).setup( builder ).build( builder, nodeType );
  8504. }
  8505. return builder.format( snippet, nodeType, output );
  8506. }
  8507. }
  8508. /**
  8509. * Sets the sampler value.
  8510. *
  8511. * @param {boolean} value - The sampler value to set.
  8512. * @return {TextureNode} A reference to this texture node.
  8513. */
  8514. setSampler( value ) {
  8515. this.sampler = value;
  8516. return this;
  8517. }
  8518. /**
  8519. * Returns the sampler value.
  8520. *
  8521. * @return {boolean} The sampler value.
  8522. */
  8523. getSampler() {
  8524. return this.sampler;
  8525. }
  8526. // @TODO: Move to TSL
  8527. /**
  8528. * @function
  8529. * @deprecated since r172. Use {@link TextureNode#sample} instead.
  8530. *
  8531. * @param {Node} uvNode - The uv node.
  8532. * @return {TextureNode} A texture node representing the texture sample.
  8533. */
  8534. uv( uvNode ) { // @deprecated, r172
  8535. warn( 'TextureNode: .uv() has been renamed. Use .sample() instead.' );
  8536. return this.sample( uvNode );
  8537. }
  8538. /**
  8539. * Samples the texture with the given uv node.
  8540. *
  8541. * @param {Node} uvNode - The uv node.
  8542. * @return {TextureNode} A texture node representing the texture sample.
  8543. */
  8544. sample( uvNode ) {
  8545. const textureNode = this.clone();
  8546. textureNode.uvNode = nodeObject( uvNode );
  8547. textureNode.referenceNode = this.getBase();
  8548. return nodeObject( textureNode );
  8549. }
  8550. /**
  8551. * TSL function for creating a texture node that fetches/loads texels without interpolation.
  8552. *
  8553. * @param {Node<uvec2>} uvNode - The uv node.
  8554. * @returns {TextureNode} A texture node representing the texture load.
  8555. */
  8556. load( uvNode ) {
  8557. return this.sample( uvNode ).setSampler( false );
  8558. }
  8559. /**
  8560. * Samples a blurred version of the texture by defining an internal bias.
  8561. *
  8562. * @param {Node<float>} amountNode - How blurred the texture should be.
  8563. * @return {TextureNode} A texture node representing the texture sample.
  8564. */
  8565. blur( amountNode ) {
  8566. const textureNode = this.clone();
  8567. textureNode.biasNode = nodeObject( amountNode ).mul( maxMipLevel( textureNode ) );
  8568. textureNode.referenceNode = this.getBase();
  8569. const map = textureNode.value;
  8570. if ( textureNode.generateMipmaps === false && ( map && map.generateMipmaps === false || map.minFilter === NearestFilter || map.magFilter === NearestFilter ) ) {
  8571. warn( 'TSL: texture().blur() requires mipmaps and sampling. Use .generateMipmaps=true and .minFilter/.magFilter=THREE.LinearFilter in the Texture.' );
  8572. textureNode.biasNode = null;
  8573. }
  8574. return nodeObject( textureNode );
  8575. }
  8576. /**
  8577. * Samples a specific mip of the texture.
  8578. *
  8579. * @param {Node<int>} levelNode - The mip level to sample.
  8580. * @return {TextureNode} A texture node representing the texture sample.
  8581. */
  8582. level( levelNode ) {
  8583. const textureNode = this.clone();
  8584. textureNode.levelNode = nodeObject( levelNode );
  8585. textureNode.referenceNode = this.getBase();
  8586. return nodeObject( textureNode );
  8587. }
  8588. /**
  8589. * Returns the texture size of the requested level.
  8590. *
  8591. * @param {Node<int>} levelNode - The level to compute the size for.
  8592. * @return {TextureSizeNode} The texture size.
  8593. */
  8594. size( levelNode ) {
  8595. return textureSize( this, levelNode );
  8596. }
  8597. /**
  8598. * Samples the texture with the given bias.
  8599. *
  8600. * @param {Node<float>} biasNode - The bias node.
  8601. * @return {TextureNode} A texture node representing the texture sample.
  8602. */
  8603. bias( biasNode ) {
  8604. const textureNode = this.clone();
  8605. textureNode.biasNode = nodeObject( biasNode );
  8606. textureNode.referenceNode = this.getBase();
  8607. return nodeObject( textureNode );
  8608. }
  8609. /**
  8610. * Returns the base texture of this node.
  8611. * @return {TextureNode} The base texture node.
  8612. */
  8613. getBase() {
  8614. return this.referenceNode ? this.referenceNode.getBase() : this;
  8615. }
  8616. /**
  8617. * Samples the texture by executing a compare operation.
  8618. *
  8619. * @param {Node<float>} compareNode - The node that defines the compare value.
  8620. * @return {TextureNode} A texture node representing the texture sample.
  8621. */
  8622. compare( compareNode ) {
  8623. const textureNode = this.clone();
  8624. textureNode.compareNode = nodeObject( compareNode );
  8625. textureNode.referenceNode = this.getBase();
  8626. return nodeObject( textureNode );
  8627. }
  8628. /**
  8629. * Samples the texture using an explicit gradient.
  8630. *
  8631. * @param {Node<vec2>} gradNodeX - The gradX node.
  8632. * @param {Node<vec2>} gradNodeY - The gradY node.
  8633. * @return {TextureNode} A texture node representing the texture sample.
  8634. */
  8635. grad( gradNodeX, gradNodeY ) {
  8636. const textureNode = this.clone();
  8637. textureNode.gradNode = [ nodeObject( gradNodeX ), nodeObject( gradNodeY ) ];
  8638. textureNode.referenceNode = this.getBase();
  8639. return nodeObject( textureNode );
  8640. }
  8641. /**
  8642. * Samples the texture by defining a depth node.
  8643. *
  8644. * @param {Node<int>} depthNode - The depth node.
  8645. * @return {TextureNode} A texture node representing the texture sample.
  8646. */
  8647. depth( depthNode ) {
  8648. const textureNode = this.clone();
  8649. textureNode.depthNode = nodeObject( depthNode );
  8650. textureNode.referenceNode = this.getBase();
  8651. return nodeObject( textureNode );
  8652. }
  8653. /**
  8654. * Samples the texture by defining an offset node.
  8655. *
  8656. * @param {Node<ivec2>} offsetNode - The offset node.
  8657. * @return {TextureNode} A texture node representing the texture sample.
  8658. */
  8659. offset( offsetNode ) {
  8660. const textureNode = this.clone();
  8661. textureNode.offsetNode = nodeObject( offsetNode );
  8662. textureNode.referenceNode = this.getBase();
  8663. return nodeObject( textureNode );
  8664. }
  8665. // --
  8666. serialize( data ) {
  8667. super.serialize( data );
  8668. data.value = this.value.toJSON( data.meta ).uuid;
  8669. data.sampler = this.sampler;
  8670. data.updateMatrix = this.updateMatrix;
  8671. data.updateType = this.updateType;
  8672. }
  8673. deserialize( data ) {
  8674. super.deserialize( data );
  8675. this.value = data.meta.textures[ data.value ];
  8676. this.sampler = data.sampler;
  8677. this.updateMatrix = data.updateMatrix;
  8678. this.updateType = data.updateType;
  8679. }
  8680. /**
  8681. * The update is used to implement the update of the uv transformation matrix.
  8682. */
  8683. update() {
  8684. const texture = this.value;
  8685. const matrixUniform = this._matrixUniform;
  8686. if ( matrixUniform !== null ) matrixUniform.value = texture.matrix;
  8687. if ( texture.matrixAutoUpdate === true ) {
  8688. texture.updateMatrix();
  8689. }
  8690. //
  8691. const flipYUniform = this._flipYUniform;
  8692. if ( flipYUniform !== null ) {
  8693. flipYUniform.value = ( ( texture.image instanceof ImageBitmap && texture.flipY === true ) || texture.isRenderTargetTexture === true || texture.isFramebufferTexture === true || texture.isDepthTexture === true );
  8694. }
  8695. }
  8696. /**
  8697. * Clones the texture node.
  8698. *
  8699. * @return {TextureNode} The cloned texture node.
  8700. */
  8701. clone() {
  8702. const newNode = new this.constructor( this.value, this.uvNode, this.levelNode, this.biasNode );
  8703. newNode.sampler = this.sampler;
  8704. newNode.depthNode = this.depthNode;
  8705. newNode.compareNode = this.compareNode;
  8706. newNode.gradNode = this.gradNode;
  8707. newNode.offsetNode = this.offsetNode;
  8708. return newNode;
  8709. }
  8710. }
  8711. /**
  8712. * TSL function for creating a texture node.
  8713. *
  8714. * @tsl
  8715. * @function
  8716. * @param {?Texture} value - The texture.
  8717. * @param {?Node<vec2|vec3>} [uvNode=null] - The uv node.
  8718. * @param {?Node<int>} [levelNode=null] - The level node.
  8719. * @param {?Node<float>} [biasNode=null] - The bias node.
  8720. * @returns {TextureNode}
  8721. */
  8722. const textureBase = /*@__PURE__*/ nodeProxy( TextureNode ).setParameterLength( 1, 4 ).setName( 'texture' );
  8723. /**
  8724. * TSL function for creating a texture node or sample a texture node already existing.
  8725. *
  8726. * @tsl
  8727. * @function
  8728. * @param {?(Texture|TextureNode)} [value=EmptyTexture] - The texture.
  8729. * @param {?Node<vec2|vec3>} [uvNode=null] - The uv node.
  8730. * @param {?Node<int>} [levelNode=null] - The level node.
  8731. * @param {?Node<float>} [biasNode=null] - The bias node.
  8732. * @returns {TextureNode}
  8733. */
  8734. const texture = ( value = EmptyTexture$1, uvNode = null, levelNode = null, biasNode = null ) => {
  8735. let textureNode;
  8736. if ( value && value.isTextureNode === true ) {
  8737. textureNode = nodeObject( value.clone() );
  8738. textureNode.referenceNode = value.getBase(); // Ensure the reference is set to the original node
  8739. if ( uvNode !== null ) textureNode.uvNode = nodeObject( uvNode );
  8740. if ( levelNode !== null ) textureNode.levelNode = nodeObject( levelNode );
  8741. if ( biasNode !== null ) textureNode.biasNode = nodeObject( biasNode );
  8742. } else {
  8743. textureNode = textureBase( value, uvNode, levelNode, biasNode );
  8744. }
  8745. return textureNode;
  8746. };
  8747. /**
  8748. * TSL function for creating a uniform texture node.
  8749. *
  8750. * @tsl
  8751. * @function
  8752. * @param {?Texture} value - The texture.
  8753. * @returns {TextureNode}
  8754. */
  8755. const uniformTexture = ( value = EmptyTexture$1 ) => texture( value );
  8756. /**
  8757. * TSL function for creating a texture node that fetches/loads texels without interpolation.
  8758. *
  8759. * @tsl
  8760. * @function
  8761. * @param {?(Texture|TextureNode)} [value=EmptyTexture] - The texture.
  8762. * @param {?Node<vec2|vec3>} [uvNode=null] - The uv node.
  8763. * @param {?Node<int>} [levelNode=null] - The level node.
  8764. * @param {?Node<float>} [biasNode=null] - The bias node.
  8765. * @returns {TextureNode}
  8766. */
  8767. const textureLoad = ( ...params ) => texture( ...params ).setSampler( false );
  8768. const textureLevel = ( value, uv, level ) => texture( value, uv ).level( level );
  8769. /**
  8770. * Converts a texture or texture node to a sampler.
  8771. *
  8772. * @tsl
  8773. * @function
  8774. * @param {TextureNode|Texture} value - The texture or texture node to convert.
  8775. * @returns {Node}
  8776. */
  8777. const sampler = ( value ) => ( value.isNode === true ? value : texture( value ) ).convert( 'sampler' );
  8778. /**
  8779. * Converts a texture or texture node to a sampler comparison.
  8780. *
  8781. * @tsl
  8782. * @function
  8783. * @param {TextureNode|Texture} value - The texture or texture node to convert.
  8784. * @returns {Node}
  8785. */
  8786. const samplerComparison = ( value ) => ( value.isNode === true ? value : texture( value ) ).convert( 'samplerComparison' );
  8787. /**
  8788. * A special type of uniform node which represents array-like data
  8789. * as uniform buffers. The access usually happens via `element()`
  8790. * which returns an instance of {@link ArrayElementNode}. For example:
  8791. *
  8792. * ```js
  8793. * const bufferNode = buffer( array, 'mat4', count );
  8794. * const matrixNode = bufferNode.element( index ); // access a matrix from the buffer
  8795. * ```
  8796. * In general, it is recommended to use the more managed {@link UniformArrayNode}
  8797. * since it handles more input types and automatically cares about buffer paddings.
  8798. *
  8799. * @augments UniformNode
  8800. */
  8801. class BufferNode extends UniformNode {
  8802. static get type() {
  8803. return 'BufferNode';
  8804. }
  8805. /**
  8806. * Constructs a new buffer node.
  8807. *
  8808. * @param {Array<number>} value - Array-like buffer data.
  8809. * @param {string} bufferType - The data type of the buffer.
  8810. * @param {number} [bufferCount=0] - The count of buffer elements.
  8811. */
  8812. constructor( value, bufferType, bufferCount = 0 ) {
  8813. super( value, bufferType );
  8814. /**
  8815. * This flag can be used for type testing.
  8816. *
  8817. * @type {boolean}
  8818. * @readonly
  8819. * @default true
  8820. */
  8821. this.isBufferNode = true;
  8822. /**
  8823. * The data type of the buffer.
  8824. *
  8825. * @type {string}
  8826. */
  8827. this.bufferType = bufferType;
  8828. /**
  8829. * The uniform node that holds the value of the reference node.
  8830. *
  8831. * @type {number}
  8832. * @default 0
  8833. */
  8834. this.bufferCount = bufferCount;
  8835. /**
  8836. * An array of update ranges.
  8837. *
  8838. * @type {Array<{start: number, count: number}>}
  8839. */
  8840. this.updateRanges = [];
  8841. }
  8842. /**
  8843. * Adds a range of data in the data array to be updated on the GPU.
  8844. *
  8845. * @param {number} start - Position at which to start update.
  8846. * @param {number} count - The number of components to update.
  8847. */
  8848. addUpdateRange( start, count ) {
  8849. this.updateRanges.push( { start, count } );
  8850. }
  8851. /**
  8852. * Clears the update ranges.
  8853. */
  8854. clearUpdateRanges() {
  8855. this.updateRanges.length = 0;
  8856. }
  8857. /**
  8858. * The data type of the buffer elements.
  8859. *
  8860. * @param {NodeBuilder} builder - The current node builder.
  8861. * @return {string} The element type.
  8862. */
  8863. getElementType( builder ) {
  8864. return this.getNodeType( builder );
  8865. }
  8866. /**
  8867. * Overwrites the default implementation to return a fixed value `'buffer'`.
  8868. *
  8869. * @param {NodeBuilder} builder - The current node builder.
  8870. * @return {string} The input type.
  8871. */
  8872. getInputType( /*builder*/ ) {
  8873. return 'buffer';
  8874. }
  8875. }
  8876. /**
  8877. * TSL function for creating a buffer node.
  8878. *
  8879. * @tsl
  8880. * @function
  8881. * @param {Array<number>} value - Array-like buffer data.
  8882. * @param {string} type - The data type of a buffer element.
  8883. * @param {number} count - The count of buffer elements.
  8884. * @returns {BufferNode}
  8885. */
  8886. const buffer = ( value, type, count ) => nodeObject( new BufferNode( value, type, count ) );
  8887. /**
  8888. * Represents the element access on uniform array nodes.
  8889. *
  8890. * @augments ArrayElementNode
  8891. */
  8892. class UniformArrayElementNode extends ArrayElementNode {
  8893. static get type() {
  8894. return 'UniformArrayElementNode';
  8895. }
  8896. /**
  8897. * Constructs a new buffer node.
  8898. *
  8899. * @param {UniformArrayNode} uniformArrayNode - The uniform array node to access.
  8900. * @param {IndexNode} indexNode - The index data that define the position of the accessed element in the array.
  8901. */
  8902. constructor( uniformArrayNode, indexNode ) {
  8903. super( uniformArrayNode, indexNode );
  8904. /**
  8905. * This flag can be used for type testing.
  8906. *
  8907. * @type {boolean}
  8908. * @readonly
  8909. * @default true
  8910. */
  8911. this.isArrayBufferElementNode = true;
  8912. }
  8913. generate( builder ) {
  8914. const snippet = super.generate( builder );
  8915. const type = this.getNodeType();
  8916. const paddedType = this.node.getPaddedType();
  8917. return builder.format( snippet, paddedType, type );
  8918. }
  8919. }
  8920. /**
  8921. * Similar to {@link BufferNode} this module represents array-like data as
  8922. * uniform buffers. Unlike {@link BufferNode}, it can handle more common
  8923. * data types in the array (e.g `three.js` primitives) and automatically
  8924. * manage buffer padding. It should be the first choice when working with
  8925. * uniforms buffers.
  8926. * ```js
  8927. * const tintColors = uniformArray( [
  8928. * new Color( 1, 0, 0 ),
  8929. * new Color( 0, 1, 0 ),
  8930. * new Color( 0, 0, 1 )
  8931. * ], 'color' );
  8932. *
  8933. * const redColor = tintColors.element( 0 );
  8934. *
  8935. * @augments BufferNode
  8936. */
  8937. class UniformArrayNode extends BufferNode {
  8938. static get type() {
  8939. return 'UniformArrayNode';
  8940. }
  8941. /**
  8942. * Constructs a new uniform array node.
  8943. *
  8944. * @param {Array<any>} value - Array holding the buffer data.
  8945. * @param {?string} [elementType=null] - The data type of a buffer element.
  8946. */
  8947. constructor( value, elementType = null ) {
  8948. super( null );
  8949. /**
  8950. * Array holding the buffer data. Unlike {@link BufferNode}, the array can
  8951. * hold number primitives as well as three.js objects like vectors, matrices
  8952. * or colors.
  8953. *
  8954. * @type {Array<any>}
  8955. */
  8956. this.array = value;
  8957. /**
  8958. * The data type of an array element.
  8959. *
  8960. * @type {string}
  8961. */
  8962. this.elementType = elementType === null ? getValueType( value[ 0 ] ) : elementType;
  8963. /**
  8964. * The padded type. Uniform buffers must conform to a certain buffer layout
  8965. * so a separate type is computed to ensure correct buffer size.
  8966. *
  8967. * @type {string}
  8968. */
  8969. this.paddedType = this.getPaddedType();
  8970. /**
  8971. * Overwritten since uniform array nodes are updated per render.
  8972. *
  8973. * @type {string}
  8974. * @default 'render'
  8975. */
  8976. this.updateType = NodeUpdateType.RENDER;
  8977. /**
  8978. * This flag can be used for type testing.
  8979. *
  8980. * @type {boolean}
  8981. * @readonly
  8982. * @default true
  8983. */
  8984. this.isArrayBufferNode = true;
  8985. }
  8986. /**
  8987. * This method is overwritten since the node type is inferred from the
  8988. * {@link UniformArrayNode#paddedType}.
  8989. *
  8990. * @param {NodeBuilder} builder - The current node builder.
  8991. * @return {string} The node type.
  8992. */
  8993. getNodeType( /*builder*/ ) {
  8994. return this.paddedType;
  8995. }
  8996. /**
  8997. * The data type of the array elements.
  8998. *
  8999. * @param {NodeBuilder} builder - The current node builder.
  9000. * @return {string} The element type.
  9001. */
  9002. getElementType() {
  9003. return this.elementType;
  9004. }
  9005. /**
  9006. * Returns the padded type based on the element type.
  9007. *
  9008. * @return {string} The padded type.
  9009. */
  9010. getPaddedType() {
  9011. const elementType = this.elementType;
  9012. let paddedType = 'vec4';
  9013. if ( elementType === 'mat2' ) {
  9014. paddedType = 'mat2';
  9015. } else if ( /mat/.test( elementType ) === true ) {
  9016. paddedType = 'mat4';
  9017. } else if ( elementType.charAt( 0 ) === 'i' ) {
  9018. paddedType = 'ivec4';
  9019. } else if ( elementType.charAt( 0 ) === 'u' ) {
  9020. paddedType = 'uvec4';
  9021. }
  9022. return paddedType;
  9023. }
  9024. /**
  9025. * The update makes sure to correctly transfer the data from the (complex) objects
  9026. * in the array to the internal, correctly padded value buffer.
  9027. *
  9028. * @param {NodeFrame} frame - A reference to the current node frame.
  9029. */
  9030. update( /*frame*/ ) {
  9031. const { array, value } = this;
  9032. const elementType = this.elementType;
  9033. if ( elementType === 'float' || elementType === 'int' || elementType === 'uint' ) {
  9034. for ( let i = 0; i < array.length; i ++ ) {
  9035. const index = i * 4;
  9036. value[ index ] = array[ i ];
  9037. }
  9038. } else if ( elementType === 'color' ) {
  9039. for ( let i = 0; i < array.length; i ++ ) {
  9040. const index = i * 4;
  9041. const vector = array[ i ];
  9042. value[ index ] = vector.r;
  9043. value[ index + 1 ] = vector.g;
  9044. value[ index + 2 ] = vector.b || 0;
  9045. //value[ index + 3 ] = vector.a || 0;
  9046. }
  9047. } else if ( elementType === 'mat2' ) {
  9048. for ( let i = 0; i < array.length; i ++ ) {
  9049. const index = i * 4;
  9050. const matrix = array[ i ];
  9051. value[ index ] = matrix.elements[ 0 ];
  9052. value[ index + 1 ] = matrix.elements[ 1 ];
  9053. value[ index + 2 ] = matrix.elements[ 2 ];
  9054. value[ index + 3 ] = matrix.elements[ 3 ];
  9055. }
  9056. } else if ( elementType === 'mat3' ) {
  9057. for ( let i = 0; i < array.length; i ++ ) {
  9058. const index = i * 16;
  9059. const matrix = array[ i ];
  9060. value[ index ] = matrix.elements[ 0 ];
  9061. value[ index + 1 ] = matrix.elements[ 1 ];
  9062. value[ index + 2 ] = matrix.elements[ 2 ];
  9063. value[ index + 4 ] = matrix.elements[ 3 ];
  9064. value[ index + 5 ] = matrix.elements[ 4 ];
  9065. value[ index + 6 ] = matrix.elements[ 5 ];
  9066. value[ index + 8 ] = matrix.elements[ 6 ];
  9067. value[ index + 9 ] = matrix.elements[ 7 ];
  9068. value[ index + 10 ] = matrix.elements[ 8 ];
  9069. value[ index + 15 ] = 1;
  9070. }
  9071. } else if ( elementType === 'mat4' ) {
  9072. for ( let i = 0; i < array.length; i ++ ) {
  9073. const index = i * 16;
  9074. const matrix = array[ i ];
  9075. for ( let i = 0; i < matrix.elements.length; i ++ ) {
  9076. value[ index + i ] = matrix.elements[ i ];
  9077. }
  9078. }
  9079. } else {
  9080. for ( let i = 0; i < array.length; i ++ ) {
  9081. const index = i * 4;
  9082. const vector = array[ i ];
  9083. value[ index ] = vector.x;
  9084. value[ index + 1 ] = vector.y;
  9085. value[ index + 2 ] = vector.z || 0;
  9086. value[ index + 3 ] = vector.w || 0;
  9087. }
  9088. }
  9089. }
  9090. /**
  9091. * Implement the value buffer creation based on the array data.
  9092. *
  9093. * @param {NodeBuilder} builder - A reference to the current node builder.
  9094. * @return {null}
  9095. */
  9096. setup( builder ) {
  9097. const length = this.array.length;
  9098. const elementType = this.elementType;
  9099. let arrayType = Float32Array;
  9100. const paddedType = this.paddedType;
  9101. const paddedElementLength = builder.getTypeLength( paddedType );
  9102. if ( elementType.charAt( 0 ) === 'i' ) arrayType = Int32Array;
  9103. if ( elementType.charAt( 0 ) === 'u' ) arrayType = Uint32Array;
  9104. this.value = new arrayType( length * paddedElementLength );
  9105. this.bufferCount = length;
  9106. this.bufferType = paddedType;
  9107. return super.setup( builder );
  9108. }
  9109. /**
  9110. * Overwrites the default `element()` method to provide element access
  9111. * based on {@link UniformArrayNode}.
  9112. *
  9113. * @param {IndexNode} indexNode - The index node.
  9114. * @return {UniformArrayElementNode}
  9115. */
  9116. element( indexNode ) {
  9117. return nodeObject( new UniformArrayElementNode( this, nodeObject( indexNode ) ) );
  9118. }
  9119. }
  9120. /**
  9121. * TSL function for creating an uniform array node.
  9122. *
  9123. * @tsl
  9124. * @function
  9125. * @param {Array<any>} values - Array-like data.
  9126. * @param {?string} [nodeType] - The data type of the array elements.
  9127. * @returns {UniformArrayNode}
  9128. */
  9129. const uniformArray = ( values, nodeType ) => nodeObject( new UniformArrayNode( values, nodeType ) );
  9130. /**
  9131. * The node allows to set values for built-in shader variables. That is
  9132. * required for features like hardware-accelerated vertex clipping.
  9133. *
  9134. * @augments Node
  9135. */
  9136. class BuiltinNode extends Node {
  9137. /**
  9138. * Constructs a new builtin node.
  9139. *
  9140. * @param {string} name - The name of the built-in shader variable.
  9141. */
  9142. constructor( name ) {
  9143. super( 'float' );
  9144. /**
  9145. * The name of the built-in shader variable.
  9146. *
  9147. * @type {string}
  9148. */
  9149. this.name = name;
  9150. /**
  9151. * This flag can be used for type testing.
  9152. *
  9153. * @type {boolean}
  9154. * @readonly
  9155. * @default true
  9156. */
  9157. this.isBuiltinNode = true;
  9158. }
  9159. /**
  9160. * Generates the code snippet of the builtin node.
  9161. *
  9162. * @param {NodeBuilder} builder - The current node builder.
  9163. * @return {string} The generated code snippet.
  9164. */
  9165. generate( /* builder */ ) {
  9166. return this.name;
  9167. }
  9168. }
  9169. /**
  9170. * TSL function for creating a builtin node.
  9171. *
  9172. * @tsl
  9173. * @function
  9174. * @param {string} name - The name of the built-in shader variable.
  9175. * @returns {BuiltinNode}
  9176. */
  9177. const builtin = nodeProxy( BuiltinNode ).setParameterLength( 1 );
  9178. let _screenSizeVec, _viewportVec;
  9179. /**
  9180. * This node provides a collection of screen related metrics.
  9181. * Depending on {@link ScreenNode#scope}, the nodes can represent
  9182. * resolution or viewport data as well as fragment or uv coordinates.
  9183. *
  9184. * @augments Node
  9185. */
  9186. class ScreenNode extends Node {
  9187. static get type() {
  9188. return 'ScreenNode';
  9189. }
  9190. /**
  9191. * Constructs a new screen node.
  9192. *
  9193. * @param {('coordinate'|'viewport'|'size'|'uv'|'dpr')} scope - The node's scope.
  9194. */
  9195. constructor( scope ) {
  9196. super();
  9197. /**
  9198. * The node represents different metric depending on which scope is selected.
  9199. *
  9200. * - `ScreenNode.COORDINATE`: Window-relative coordinates of the current fragment according to WebGPU standards.
  9201. * - `ScreenNode.VIEWPORT`: The current viewport defined as a four-dimensional vector.
  9202. * - `ScreenNode.SIZE`: The dimensions of the current bound framebuffer.
  9203. * - `ScreenNode.UV`: Normalized coordinates.
  9204. * - `ScreenNode.DPR`: Device pixel ratio.
  9205. *
  9206. * @type {('coordinate'|'viewport'|'size'|'uv'|'dpr')}
  9207. */
  9208. this.scope = scope;
  9209. /**
  9210. * This output node.
  9211. *
  9212. * @private
  9213. * @type {?Node}
  9214. * @default null
  9215. */
  9216. this._output = null;
  9217. /**
  9218. * This flag can be used for type testing.
  9219. *
  9220. * @type {boolean}
  9221. * @readonly
  9222. * @default true
  9223. */
  9224. this.isViewportNode = true;
  9225. }
  9226. /**
  9227. * This method is overwritten since the node type depends on the selected scope.
  9228. *
  9229. * @return {('float'|'vec2'|'vec4')} The node type.
  9230. */
  9231. getNodeType() {
  9232. if ( this.scope === ScreenNode.DPR ) return 'float';
  9233. if ( this.scope === ScreenNode.VIEWPORT ) return 'vec4';
  9234. else return 'vec2';
  9235. }
  9236. /**
  9237. * This method is overwritten since the node's update type depends on the selected scope.
  9238. *
  9239. * @return {NodeUpdateType} The update type.
  9240. */
  9241. getUpdateType() {
  9242. let updateType = NodeUpdateType.NONE;
  9243. if ( this.scope === ScreenNode.SIZE || this.scope === ScreenNode.VIEWPORT || this.scope === ScreenNode.DPR ) {
  9244. updateType = NodeUpdateType.RENDER;
  9245. }
  9246. this.updateType = updateType;
  9247. return updateType;
  9248. }
  9249. /**
  9250. * `ScreenNode` implements {@link Node#update} to retrieve viewport and size information
  9251. * from the current renderer.
  9252. *
  9253. * @param {NodeFrame} frame - A reference to the current node frame.
  9254. */
  9255. update( { renderer } ) {
  9256. const renderTarget = renderer.getRenderTarget();
  9257. if ( this.scope === ScreenNode.VIEWPORT ) {
  9258. if ( renderTarget !== null ) {
  9259. _viewportVec.copy( renderTarget.viewport );
  9260. } else {
  9261. renderer.getViewport( _viewportVec );
  9262. _viewportVec.multiplyScalar( renderer.getPixelRatio() );
  9263. }
  9264. } else if ( this.scope === ScreenNode.DPR ) {
  9265. this._output.value = renderer.getPixelRatio();
  9266. } else {
  9267. if ( renderTarget !== null ) {
  9268. _screenSizeVec.width = renderTarget.width;
  9269. _screenSizeVec.height = renderTarget.height;
  9270. } else {
  9271. renderer.getDrawingBufferSize( _screenSizeVec );
  9272. }
  9273. }
  9274. }
  9275. setup( /*builder*/ ) {
  9276. const scope = this.scope;
  9277. let output = null;
  9278. if ( scope === ScreenNode.SIZE ) {
  9279. output = uniform( _screenSizeVec || ( _screenSizeVec = new Vector2() ) );
  9280. } else if ( scope === ScreenNode.VIEWPORT ) {
  9281. output = uniform( _viewportVec || ( _viewportVec = new Vector4() ) );
  9282. } else if ( scope === ScreenNode.DPR ) {
  9283. output = uniform( 1 );
  9284. } else {
  9285. output = vec2( screenCoordinate.div( screenSize ) );
  9286. }
  9287. this._output = output;
  9288. return output;
  9289. }
  9290. generate( builder ) {
  9291. if ( this.scope === ScreenNode.COORDINATE ) {
  9292. let coord = builder.getFragCoord();
  9293. if ( builder.isFlipY() ) {
  9294. // follow webgpu standards
  9295. const size = builder.getNodeProperties( screenSize ).outputNode.build( builder );
  9296. coord = `${ builder.getType( 'vec2' ) }( ${ coord }.x, ${ size }.y - ${ coord }.y )`;
  9297. }
  9298. return coord;
  9299. }
  9300. return super.generate( builder );
  9301. }
  9302. }
  9303. ScreenNode.COORDINATE = 'coordinate';
  9304. ScreenNode.VIEWPORT = 'viewport';
  9305. ScreenNode.SIZE = 'size';
  9306. ScreenNode.UV = 'uv';
  9307. ScreenNode.DPR = 'dpr';
  9308. // Screen
  9309. /**
  9310. * TSL object that represents the current DPR.
  9311. *
  9312. * @tsl
  9313. * @type {ScreenNode<float>}
  9314. */
  9315. const screenDPR = /*@__PURE__*/ nodeImmutable( ScreenNode, ScreenNode.DPR );
  9316. /**
  9317. * TSL object that represents normalized screen coordinates, unitless in `[0, 1]`.
  9318. *
  9319. * @tsl
  9320. * @type {ScreenNode<vec2>}
  9321. */
  9322. const screenUV = /*@__PURE__*/ nodeImmutable( ScreenNode, ScreenNode.UV );
  9323. /**
  9324. * TSL object that represents the screen resolution in physical pixel units.
  9325. *
  9326. * @tsl
  9327. * @type {ScreenNode<vec2>}
  9328. */
  9329. const screenSize = /*@__PURE__*/ nodeImmutable( ScreenNode, ScreenNode.SIZE );
  9330. /**
  9331. * TSL object that represents the current `x`/`y` pixel position on the screen in physical pixel units.
  9332. *
  9333. * @tsl
  9334. * @type {ScreenNode<vec2>}
  9335. */
  9336. const screenCoordinate = /*@__PURE__*/ nodeImmutable( ScreenNode, ScreenNode.COORDINATE );
  9337. // Viewport
  9338. /**
  9339. * TSL object that represents the viewport rectangle as `x`, `y`, `width` and `height` in physical pixel units.
  9340. *
  9341. * @tsl
  9342. * @type {ScreenNode<vec4>}
  9343. */
  9344. const viewport = /*@__PURE__*/ nodeImmutable( ScreenNode, ScreenNode.VIEWPORT );
  9345. /**
  9346. * TSL object that represents the viewport resolution in physical pixel units.
  9347. *
  9348. * @tsl
  9349. * @type {ScreenNode<vec2>}
  9350. */
  9351. const viewportSize = viewport.zw;
  9352. /**
  9353. * TSL object that represents the current `x`/`y` pixel position on the viewport in physical pixel units.
  9354. *
  9355. * @tsl
  9356. * @type {ScreenNode<vec2>}
  9357. */
  9358. const viewportCoordinate = /*@__PURE__*/ screenCoordinate.sub( viewport.xy );
  9359. /**
  9360. * TSL object that represents normalized viewport coordinates, unitless in `[0, 1]`.
  9361. *
  9362. * @tsl
  9363. * @type {ScreenNode<vec2>}
  9364. */
  9365. const viewportUV = /*@__PURE__*/ viewportCoordinate.div( viewportSize );
  9366. // Deprecated
  9367. /**
  9368. * @deprecated since r169. Use {@link screenSize} instead.
  9369. */
  9370. const viewportResolution = /*@__PURE__*/ ( Fn( () => { // @deprecated, r169
  9371. warn( 'TSL: "viewportResolution" is deprecated. Use "screenSize" instead.' );
  9372. return screenSize;
  9373. }, 'vec2' ).once() )();
  9374. /**
  9375. * TSL object that represents the current `index` value of the camera if used ArrayCamera.
  9376. *
  9377. * @tsl
  9378. * @type {UniformNode<uint>}
  9379. */
  9380. const cameraIndex = /*@__PURE__*/ uniform( 0, 'uint' ).setName( 'u_cameraIndex' ).setGroup( sharedUniformGroup( 'cameraIndex' ) ).toVarying( 'v_cameraIndex' );
  9381. /**
  9382. * TSL object that represents the `near` value of the camera used for the current render.
  9383. *
  9384. * @tsl
  9385. * @type {UniformNode<float>}
  9386. */
  9387. const cameraNear = /*@__PURE__*/ uniform( 'float' ).setName( 'cameraNear' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.near );
  9388. /**
  9389. * TSL object that represents the `far` value of the camera used for the current render.
  9390. *
  9391. * @tsl
  9392. * @type {UniformNode<float>}
  9393. */
  9394. const cameraFar = /*@__PURE__*/ uniform( 'float' ).setName( 'cameraFar' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.far );
  9395. /**
  9396. * TSL object that represents the projection matrix of the camera used for the current render.
  9397. *
  9398. * @tsl
  9399. * @type {UniformNode<mat4>}
  9400. */
  9401. const cameraProjectionMatrix = /*@__PURE__*/ ( Fn( ( { camera } ) => {
  9402. let cameraProjectionMatrix;
  9403. if ( camera.isArrayCamera && camera.cameras.length > 0 ) {
  9404. const matrices = [];
  9405. for ( const subCamera of camera.cameras ) {
  9406. matrices.push( subCamera.projectionMatrix );
  9407. }
  9408. const cameraProjectionMatrices = uniformArray( matrices ).setGroup( renderGroup ).setName( 'cameraProjectionMatrices' );
  9409. cameraProjectionMatrix = cameraProjectionMatrices.element( camera.isMultiViewCamera ? builtin( 'gl_ViewID_OVR' ) : cameraIndex ).toConst( 'cameraProjectionMatrix' );
  9410. } else {
  9411. cameraProjectionMatrix = uniform( 'mat4' ).setName( 'cameraProjectionMatrix' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.projectionMatrix );
  9412. }
  9413. return cameraProjectionMatrix;
  9414. } ).once() )();
  9415. /**
  9416. * TSL object that represents the inverse projection matrix of the camera used for the current render.
  9417. *
  9418. * @tsl
  9419. * @type {UniformNode<mat4>}
  9420. */
  9421. const cameraProjectionMatrixInverse = /*@__PURE__*/ ( Fn( ( { camera } ) => {
  9422. let cameraProjectionMatrixInverse;
  9423. if ( camera.isArrayCamera && camera.cameras.length > 0 ) {
  9424. const matrices = [];
  9425. for ( const subCamera of camera.cameras ) {
  9426. matrices.push( subCamera.projectionMatrixInverse );
  9427. }
  9428. const cameraProjectionMatricesInverse = uniformArray( matrices ).setGroup( renderGroup ).setName( 'cameraProjectionMatricesInverse' );
  9429. cameraProjectionMatrixInverse = cameraProjectionMatricesInverse.element( camera.isMultiViewCamera ? builtin( 'gl_ViewID_OVR' ) : cameraIndex ).toConst( 'cameraProjectionMatrixInverse' );
  9430. } else {
  9431. cameraProjectionMatrixInverse = uniform( 'mat4' ).setName( 'cameraProjectionMatrixInverse' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.projectionMatrixInverse );
  9432. }
  9433. return cameraProjectionMatrixInverse;
  9434. } ).once() )();
  9435. /**
  9436. * TSL object that represents the view matrix of the camera used for the current render.
  9437. *
  9438. * @tsl
  9439. * @type {UniformNode<mat4>}
  9440. */
  9441. const cameraViewMatrix = /*@__PURE__*/ ( Fn( ( { camera } ) => {
  9442. let cameraViewMatrix;
  9443. if ( camera.isArrayCamera && camera.cameras.length > 0 ) {
  9444. const matrices = [];
  9445. for ( const subCamera of camera.cameras ) {
  9446. matrices.push( subCamera.matrixWorldInverse );
  9447. }
  9448. const cameraViewMatrices = uniformArray( matrices ).setGroup( renderGroup ).setName( 'cameraViewMatrices' );
  9449. cameraViewMatrix = cameraViewMatrices.element( camera.isMultiViewCamera ? builtin( 'gl_ViewID_OVR' ) : cameraIndex ).toConst( 'cameraViewMatrix' );
  9450. } else {
  9451. cameraViewMatrix = uniform( 'mat4' ).setName( 'cameraViewMatrix' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.matrixWorldInverse );
  9452. }
  9453. return cameraViewMatrix;
  9454. } ).once() )();
  9455. /**
  9456. * TSL object that represents the world matrix of the camera used for the current render.
  9457. *
  9458. * @tsl
  9459. * @type {UniformNode<mat4>}
  9460. */
  9461. const cameraWorldMatrix = /*@__PURE__*/ ( Fn( ( { camera } ) => {
  9462. let cameraWorldMatrix;
  9463. if ( camera.isArrayCamera && camera.cameras.length > 0 ) {
  9464. const matrices = [];
  9465. for ( const subCamera of camera.cameras ) {
  9466. matrices.push( subCamera.matrixWorld );
  9467. }
  9468. const cameraWorldMatrices = uniformArray( matrices ).setGroup( renderGroup ).setName( 'cameraWorldMatrices' );
  9469. cameraWorldMatrix = cameraWorldMatrices.element( camera.isMultiViewCamera ? builtin( 'gl_ViewID_OVR' ) : cameraIndex ).toConst( 'cameraWorldMatrix' );
  9470. } else {
  9471. cameraWorldMatrix = uniform( 'mat4' ).setName( 'cameraWorldMatrix' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.matrixWorld );
  9472. }
  9473. return cameraWorldMatrix;
  9474. } ).once() )();
  9475. /**
  9476. * TSL object that represents the normal matrix of the camera used for the current render.
  9477. *
  9478. * @tsl
  9479. * @type {UniformNode<mat3>}
  9480. */
  9481. const cameraNormalMatrix = /*@__PURE__*/ ( Fn( ( { camera } ) => {
  9482. let cameraNormalMatrix;
  9483. if ( camera.isArrayCamera && camera.cameras.length > 0 ) {
  9484. const matrices = [];
  9485. for ( const subCamera of camera.cameras ) {
  9486. matrices.push( subCamera.normalMatrix );
  9487. }
  9488. const cameraNormalMatrices = uniformArray( matrices ).setGroup( renderGroup ).setName( 'cameraNormalMatrices' );
  9489. cameraNormalMatrix = cameraNormalMatrices.element( camera.isMultiViewCamera ? builtin( 'gl_ViewID_OVR' ) : cameraIndex ).toConst( 'cameraNormalMatrix' );
  9490. } else {
  9491. cameraNormalMatrix = uniform( 'mat3' ).setName( 'cameraNormalMatrix' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.normalMatrix );
  9492. }
  9493. return cameraNormalMatrix;
  9494. } ).once() )();
  9495. /**
  9496. * TSL object that represents the position in world space of the camera used for the current render.
  9497. *
  9498. * @tsl
  9499. * @type {UniformNode<vec3>}
  9500. */
  9501. const cameraPosition = /*@__PURE__*/ ( Fn( ( { camera } ) => {
  9502. let cameraPosition;
  9503. if ( camera.isArrayCamera && camera.cameras.length > 0 ) {
  9504. const positions = [];
  9505. for ( let i = 0, l = camera.cameras.length; i < l; i ++ ) {
  9506. positions.push( new Vector3() );
  9507. }
  9508. const cameraPositions = uniformArray( positions ).setGroup( renderGroup ).setName( 'cameraPositions' ).onRenderUpdate( ( { camera }, self ) => {
  9509. const subCameras = camera.cameras;
  9510. const array = self.array;
  9511. for ( let i = 0, l = subCameras.length; i < l; i ++ ) {
  9512. array[ i ].setFromMatrixPosition( subCameras[ i ].matrixWorld );
  9513. }
  9514. } );
  9515. cameraPosition = cameraPositions.element( camera.isMultiViewCamera ? builtin( 'gl_ViewID_OVR' ) : cameraIndex ).toConst( 'cameraPosition' );
  9516. } else {
  9517. cameraPosition = uniform( new Vector3() ).setName( 'cameraPosition' ).setGroup( renderGroup ).onRenderUpdate( ( { camera }, self ) => self.value.setFromMatrixPosition( camera.matrixWorld ) );
  9518. }
  9519. return cameraPosition;
  9520. } ).once() )();
  9521. /**
  9522. * TSL object that represents the viewport of the camera used for the current render.
  9523. *
  9524. * @tsl
  9525. * @type {UniformNode<vec4>}
  9526. */
  9527. const cameraViewport = /*@__PURE__*/ ( Fn( ( { camera } ) => {
  9528. let cameraViewport;
  9529. if ( camera.isArrayCamera && camera.cameras.length > 0 ) {
  9530. const viewports = [];
  9531. for ( const subCamera of camera.cameras ) {
  9532. viewports.push( subCamera.viewport );
  9533. }
  9534. const cameraViewports = uniformArray( viewports, 'vec4' ).setGroup( renderGroup ).setName( 'cameraViewports' );
  9535. cameraViewport = cameraViewports.element( cameraIndex ).toConst( 'cameraViewport' );
  9536. } else {
  9537. // Fallback for single camera
  9538. cameraViewport = vec4( 0, 0, screenSize.x, screenSize.y ).toConst( 'cameraViewport' );
  9539. }
  9540. return cameraViewport;
  9541. } ).once() )();
  9542. const _sphere = /*@__PURE__*/ new Sphere();
  9543. /**
  9544. * This node can be used to access transformation related metrics of 3D objects.
  9545. * Depending on the selected scope, a different metric is represented as a uniform
  9546. * in the shader. The following scopes are supported:
  9547. *
  9548. * - `POSITION`: The object's position in world space.
  9549. * - `VIEW_POSITION`: The object's position in view/camera space.
  9550. * - `DIRECTION`: The object's direction in world space.
  9551. * - `SCALE`: The object's scale in world space.
  9552. * - `WORLD_MATRIX`: The object's matrix in world space.
  9553. *
  9554. * @augments Node
  9555. */
  9556. class Object3DNode extends Node {
  9557. static get type() {
  9558. return 'Object3DNode';
  9559. }
  9560. /**
  9561. * Constructs a new object 3D node.
  9562. *
  9563. * @param {('position'|'viewPosition'|'direction'|'scale'|'worldMatrix')} scope - The node represents a different type of transformation depending on the scope.
  9564. * @param {?Object3D} [object3d=null] - The 3D object.
  9565. */
  9566. constructor( scope, object3d = null ) {
  9567. super();
  9568. /**
  9569. * The node reports a different type of transformation depending on the scope.
  9570. *
  9571. * @type {('position'|'viewPosition'|'direction'|'scale'|'worldMatrix')}
  9572. */
  9573. this.scope = scope;
  9574. /**
  9575. * The 3D object.
  9576. *
  9577. * @type {?Object3D}
  9578. * @default null
  9579. */
  9580. this.object3d = object3d;
  9581. /**
  9582. * Overwritten since this type of node is updated per object.
  9583. *
  9584. * @type {string}
  9585. * @default 'object'
  9586. */
  9587. this.updateType = NodeUpdateType.OBJECT;
  9588. /**
  9589. * Holds the value of the node as a uniform.
  9590. *
  9591. * @type {UniformNode}
  9592. */
  9593. this.uniformNode = new UniformNode( null );
  9594. }
  9595. /**
  9596. * Overwritten since the node type is inferred from the scope.
  9597. *
  9598. * @return {('mat4'|'vec3'|'float')} The node type.
  9599. */
  9600. getNodeType() {
  9601. const scope = this.scope;
  9602. if ( scope === Object3DNode.WORLD_MATRIX ) {
  9603. return 'mat4';
  9604. } else if ( scope === Object3DNode.POSITION || scope === Object3DNode.VIEW_POSITION || scope === Object3DNode.DIRECTION || scope === Object3DNode.SCALE ) {
  9605. return 'vec3';
  9606. } else if ( scope === Object3DNode.RADIUS ) {
  9607. return 'float';
  9608. }
  9609. }
  9610. /**
  9611. * Updates the uniform value depending on the scope.
  9612. *
  9613. * @param {NodeFrame} frame - The current node frame.
  9614. */
  9615. update( frame ) {
  9616. const object = this.object3d;
  9617. const uniformNode = this.uniformNode;
  9618. const scope = this.scope;
  9619. if ( scope === Object3DNode.WORLD_MATRIX ) {
  9620. uniformNode.value = object.matrixWorld;
  9621. } else if ( scope === Object3DNode.POSITION ) {
  9622. uniformNode.value = uniformNode.value || new Vector3();
  9623. uniformNode.value.setFromMatrixPosition( object.matrixWorld );
  9624. } else if ( scope === Object3DNode.SCALE ) {
  9625. uniformNode.value = uniformNode.value || new Vector3();
  9626. uniformNode.value.setFromMatrixScale( object.matrixWorld );
  9627. } else if ( scope === Object3DNode.DIRECTION ) {
  9628. uniformNode.value = uniformNode.value || new Vector3();
  9629. object.getWorldDirection( uniformNode.value );
  9630. } else if ( scope === Object3DNode.VIEW_POSITION ) {
  9631. const camera = frame.camera;
  9632. uniformNode.value = uniformNode.value || new Vector3();
  9633. uniformNode.value.setFromMatrixPosition( object.matrixWorld );
  9634. uniformNode.value.applyMatrix4( camera.matrixWorldInverse );
  9635. } else if ( scope === Object3DNode.RADIUS ) {
  9636. const geometry = frame.object.geometry;
  9637. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  9638. _sphere.copy( geometry.boundingSphere ).applyMatrix4( object.matrixWorld );
  9639. uniformNode.value = _sphere.radius;
  9640. }
  9641. }
  9642. /**
  9643. * Generates the code snippet of the uniform node. The node type of the uniform
  9644. * node also depends on the selected scope.
  9645. *
  9646. * @param {NodeBuilder} builder - The current node builder.
  9647. * @return {string} The generated code snippet.
  9648. */
  9649. generate( builder ) {
  9650. const scope = this.scope;
  9651. if ( scope === Object3DNode.WORLD_MATRIX ) {
  9652. this.uniformNode.nodeType = 'mat4';
  9653. } else if ( scope === Object3DNode.POSITION || scope === Object3DNode.VIEW_POSITION || scope === Object3DNode.DIRECTION || scope === Object3DNode.SCALE ) {
  9654. this.uniformNode.nodeType = 'vec3';
  9655. } else if ( scope === Object3DNode.RADIUS ) {
  9656. this.uniformNode.nodeType = 'float';
  9657. }
  9658. return this.uniformNode.build( builder );
  9659. }
  9660. serialize( data ) {
  9661. super.serialize( data );
  9662. data.scope = this.scope;
  9663. }
  9664. deserialize( data ) {
  9665. super.deserialize( data );
  9666. this.scope = data.scope;
  9667. }
  9668. }
  9669. Object3DNode.WORLD_MATRIX = 'worldMatrix';
  9670. Object3DNode.POSITION = 'position';
  9671. Object3DNode.SCALE = 'scale';
  9672. Object3DNode.VIEW_POSITION = 'viewPosition';
  9673. Object3DNode.DIRECTION = 'direction';
  9674. Object3DNode.RADIUS = 'radius';
  9675. /**
  9676. * TSL function for creating an object 3D node that represents the object's direction in world space.
  9677. *
  9678. * @tsl
  9679. * @function
  9680. * @param {?Object3D} [object3d] - The 3D object.
  9681. * @returns {Object3DNode<vec3>}
  9682. */
  9683. const objectDirection = /*@__PURE__*/ nodeProxy( Object3DNode, Object3DNode.DIRECTION ).setParameterLength( 1 );
  9684. /**
  9685. * TSL function for creating an object 3D node that represents the object's world matrix.
  9686. *
  9687. * @tsl
  9688. * @function
  9689. * @param {?Object3D} [object3d] - The 3D object.
  9690. * @returns {Object3DNode<mat4>}
  9691. */
  9692. const objectWorldMatrix = /*@__PURE__*/ nodeProxy( Object3DNode, Object3DNode.WORLD_MATRIX ).setParameterLength( 1 );
  9693. /**
  9694. * TSL function for creating an object 3D node that represents the object's position in world space.
  9695. *
  9696. * @tsl
  9697. * @function
  9698. * @param {?Object3D} [object3d] - The 3D object.
  9699. * @returns {Object3DNode<vec3>}
  9700. */
  9701. const objectPosition = /*@__PURE__*/ nodeProxy( Object3DNode, Object3DNode.POSITION ).setParameterLength( 1 );
  9702. /**
  9703. * TSL function for creating an object 3D node that represents the object's scale in world space.
  9704. *
  9705. * @tsl
  9706. * @function
  9707. * @param {?Object3D} [object3d] - The 3D object.
  9708. * @returns {Object3DNode<vec3>}
  9709. */
  9710. const objectScale = /*@__PURE__*/ nodeProxy( Object3DNode, Object3DNode.SCALE ).setParameterLength( 1 );
  9711. /**
  9712. * TSL function for creating an object 3D node that represents the object's position in view/camera space.
  9713. *
  9714. * @tsl
  9715. * @function
  9716. * @param {?Object3D} [object3d] - The 3D object.
  9717. * @returns {Object3DNode<vec3>}
  9718. */
  9719. const objectViewPosition = /*@__PURE__*/ nodeProxy( Object3DNode, Object3DNode.VIEW_POSITION ).setParameterLength( 1 );
  9720. /**
  9721. * TSL function for creating an object 3D node that represents the object's radius.
  9722. *
  9723. * @tsl
  9724. * @function
  9725. * @param {?Object3D} [object3d] - The 3D object.
  9726. * @returns {Object3DNode<float>}
  9727. */
  9728. const objectRadius = /*@__PURE__*/ nodeProxy( Object3DNode, Object3DNode.RADIUS ).setParameterLength( 1 );
  9729. /**
  9730. * This type of node is a specialized version of `Object3DNode`
  9731. * with larger set of model related metrics. Unlike `Object3DNode`,
  9732. * `ModelNode` extracts the reference to the 3D object from the
  9733. * current node frame state.
  9734. *
  9735. * @augments Object3DNode
  9736. */
  9737. class ModelNode extends Object3DNode {
  9738. static get type() {
  9739. return 'ModelNode';
  9740. }
  9741. /**
  9742. * Constructs a new object model node.
  9743. *
  9744. * @param {('position'|'viewPosition'|'direction'|'scale'|'worldMatrix')} scope - The node represents a different type of transformation depending on the scope.
  9745. */
  9746. constructor( scope ) {
  9747. super( scope );
  9748. }
  9749. /**
  9750. * Extracts the model reference from the frame state and then
  9751. * updates the uniform value depending on the scope.
  9752. *
  9753. * @param {NodeFrame} frame - The current node frame.
  9754. */
  9755. update( frame ) {
  9756. this.object3d = frame.object;
  9757. super.update( frame );
  9758. }
  9759. }
  9760. /**
  9761. * TSL object that represents the object's direction in world space.
  9762. *
  9763. * @tsl
  9764. * @type {ModelNode<vec3>}
  9765. */
  9766. const modelDirection = /*@__PURE__*/ nodeImmutable( ModelNode, ModelNode.DIRECTION );
  9767. /**
  9768. * TSL object that represents the object's world matrix.
  9769. *
  9770. * @tsl
  9771. * @type {ModelNode<mat4>}
  9772. */
  9773. const modelWorldMatrix = /*@__PURE__*/ nodeImmutable( ModelNode, ModelNode.WORLD_MATRIX );
  9774. /**
  9775. * TSL object that represents the object's position in world space.
  9776. *
  9777. * @tsl
  9778. * @type {ModelNode<vec3>}
  9779. */
  9780. const modelPosition = /*@__PURE__*/ nodeImmutable( ModelNode, ModelNode.POSITION );
  9781. /**
  9782. * TSL object that represents the object's scale in world space.
  9783. *
  9784. * @tsl
  9785. * @type {ModelNode<vec3>}
  9786. */
  9787. const modelScale = /*@__PURE__*/ nodeImmutable( ModelNode, ModelNode.SCALE );
  9788. /**
  9789. * TSL object that represents the object's position in view/camera space.
  9790. *
  9791. * @tsl
  9792. * @type {ModelNode<vec3>}
  9793. */
  9794. const modelViewPosition = /*@__PURE__*/ nodeImmutable( ModelNode, ModelNode.VIEW_POSITION );
  9795. /**
  9796. * TSL object that represents the object's radius.
  9797. *
  9798. * @tsl
  9799. * @type {ModelNode<float>}
  9800. */
  9801. const modelRadius = /*@__PURE__*/ nodeImmutable( ModelNode, ModelNode.RADIUS );
  9802. /**
  9803. * TSL object that represents the object's normal matrix.
  9804. *
  9805. * @tsl
  9806. * @type {UniformNode<mat3>}
  9807. */
  9808. const modelNormalMatrix = /*@__PURE__*/ uniform( new Matrix3() ).onObjectUpdate( ( { object }, self ) => self.value.getNormalMatrix( object.matrixWorld ) );
  9809. /**
  9810. * TSL object that represents the object's inverse world matrix.
  9811. *
  9812. * @tsl
  9813. * @type {UniformNode<mat4>}
  9814. */
  9815. const modelWorldMatrixInverse = /*@__PURE__*/ uniform( new Matrix4() ).onObjectUpdate( ( { object }, self ) => self.value.copy( object.matrixWorld ).invert() );
  9816. /**
  9817. * TSL object that represents the object's model view matrix.
  9818. *
  9819. * @tsl
  9820. * @type {Node<mat4>}
  9821. */
  9822. const modelViewMatrix = /*@__PURE__*/ ( Fn( ( builder ) => {
  9823. return builder.context.modelViewMatrix || mediumpModelViewMatrix;
  9824. } ).once() )().toVar( 'modelViewMatrix' );
  9825. // GPU Precision
  9826. /**
  9827. * TSL object that represents the object's model view in `mediump` precision.
  9828. *
  9829. * @tsl
  9830. * @type {Node<mat4>}
  9831. */
  9832. const mediumpModelViewMatrix = /*@__PURE__*/ cameraViewMatrix.mul( modelWorldMatrix );
  9833. // CPU Precision
  9834. /**
  9835. * TSL object that represents the object's model view in `highp` precision
  9836. * which is achieved by computing the matrix in JS and not in the shader.
  9837. *
  9838. * @tsl
  9839. * @type {Node<mat4>}
  9840. */
  9841. const highpModelViewMatrix = /*@__PURE__*/ ( Fn( ( builder ) => {
  9842. builder.context.isHighPrecisionModelViewMatrix = true;
  9843. return uniform( 'mat4' ).onObjectUpdate( ( { object, camera } ) => {
  9844. return object.modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld );
  9845. } );
  9846. } ).once() )().toVar( 'highpModelViewMatrix' );
  9847. /**
  9848. * TSL object that represents the object's model normal view in `highp` precision
  9849. * which is achieved by computing the matrix in JS and not in the shader.
  9850. *
  9851. * @tsl
  9852. * @type {Node<mat3>}
  9853. */
  9854. const highpModelNormalViewMatrix = /*@__PURE__*/ ( Fn( ( builder ) => {
  9855. const isHighPrecisionModelViewMatrix = builder.context.isHighPrecisionModelViewMatrix;
  9856. return uniform( 'mat3' ).onObjectUpdate( ( { object, camera } ) => {
  9857. if ( isHighPrecisionModelViewMatrix !== true ) {
  9858. object.modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld );
  9859. }
  9860. return object.normalMatrix.getNormalMatrix( object.modelViewMatrix );
  9861. } );
  9862. } ).once() )().toVar( 'highpModelNormalViewMatrix' );
  9863. /**
  9864. * TSL object that represents the position attribute of the current rendered object.
  9865. *
  9866. * @tsl
  9867. * @type {AttributeNode<vec3>}
  9868. */
  9869. const positionGeometry = /*@__PURE__*/ attribute( 'position', 'vec3' );
  9870. /**
  9871. * TSL object that represents the vertex position in local space of the current rendered object.
  9872. *
  9873. * @tsl
  9874. * @type {AttributeNode<vec3>}
  9875. */
  9876. const positionLocal = /*@__PURE__*/ positionGeometry.toVarying( 'positionLocal' );
  9877. /**
  9878. * TSL object that represents the previous vertex position in local space of the current rendered object.
  9879. * Used in context of {@link VelocityNode} for rendering motion vectors.
  9880. *
  9881. * @tsl
  9882. * @type {AttributeNode<vec3>}
  9883. */
  9884. const positionPrevious = /*@__PURE__*/ positionGeometry.toVarying( 'positionPrevious' );
  9885. /**
  9886. * TSL object that represents the vertex position in world space of the current rendered object.
  9887. *
  9888. * @tsl
  9889. * @type {VaryingNode<vec3>}
  9890. */
  9891. const positionWorld = /*@__PURE__*/ ( Fn( ( builder ) => {
  9892. return modelWorldMatrix.mul( positionLocal ).xyz.toVarying( builder.getSubBuildProperty( 'v_positionWorld' ) );
  9893. }, 'vec3' ).once( [ 'POSITION' ] ) )();
  9894. /**
  9895. * TSL object that represents the position world direction of the current rendered object.
  9896. *
  9897. * @tsl
  9898. * @type {Node<vec3>}
  9899. */
  9900. const positionWorldDirection = /*@__PURE__*/ ( Fn( () => {
  9901. const vertexPWD = positionLocal.transformDirection( modelWorldMatrix ).toVarying( 'v_positionWorldDirection' );
  9902. return vertexPWD.normalize().toVar( 'positionWorldDirection' );
  9903. }, 'vec3' ).once( [ 'POSITION' ] ) )();
  9904. /**
  9905. * TSL object that represents the vertex position in view space of the current rendered object.
  9906. *
  9907. * @tsl
  9908. * @type {VaryingNode<vec3>}
  9909. */
  9910. const positionView = /*@__PURE__*/ ( Fn( ( builder ) => {
  9911. return builder.context.setupPositionView().toVarying( 'v_positionView' );
  9912. }, 'vec3' ).once( [ 'POSITION' ] ) )();
  9913. /**
  9914. * TSL object that represents the position view direction of the current rendered object.
  9915. *
  9916. * @tsl
  9917. * @type {VaryingNode<vec3>}
  9918. */
  9919. const positionViewDirection = /*@__PURE__*/ ( Fn( ( builder ) => {
  9920. let output;
  9921. if ( builder.camera.isOrthographicCamera ) {
  9922. output = vec3( 0, 0, 1 );
  9923. } else {
  9924. output = positionView.negate().toVarying( 'v_positionViewDirection' ).normalize();
  9925. }
  9926. return output.toVar( 'positionViewDirection' );
  9927. }, 'vec3' ).once( [ 'POSITION' ] ) )();
  9928. /**
  9929. * This node can be used to evaluate whether a primitive is front or back facing.
  9930. *
  9931. * @augments Node
  9932. */
  9933. class FrontFacingNode extends Node {
  9934. static get type() {
  9935. return 'FrontFacingNode';
  9936. }
  9937. /**
  9938. * Constructs a new front facing node.
  9939. */
  9940. constructor() {
  9941. super( 'bool' );
  9942. /**
  9943. * This flag can be used for type testing.
  9944. *
  9945. * @type {boolean}
  9946. * @readonly
  9947. * @default true
  9948. */
  9949. this.isFrontFacingNode = true;
  9950. }
  9951. generate( builder ) {
  9952. if ( builder.shaderStage !== 'fragment' ) return 'true';
  9953. //
  9954. const { material } = builder;
  9955. if ( material.side === BackSide ) {
  9956. return 'false';
  9957. }
  9958. return builder.getFrontFacing();
  9959. }
  9960. }
  9961. /**
  9962. * TSL object that represents whether a primitive is front or back facing
  9963. *
  9964. * @tsl
  9965. * @type {FrontFacingNode<bool>}
  9966. */
  9967. const frontFacing = /*@__PURE__*/ nodeImmutable( FrontFacingNode );
  9968. /**
  9969. * TSL object that represents the front facing status as a number instead of a bool.
  9970. * `1` means front facing, `-1` means back facing.
  9971. *
  9972. * @tsl
  9973. * @type {Node<float>}
  9974. */
  9975. const faceDirection = /*@__PURE__*/ float( frontFacing ).mul( 2.0 ).sub( 1.0 );
  9976. /**
  9977. * Converts a direction vector to a face direction vector based on the material's side.
  9978. *
  9979. * If the material is set to `BackSide`, the direction is inverted.
  9980. * If the material is set to `DoubleSide`, the direction is multiplied by `faceDirection`.
  9981. *
  9982. * @tsl
  9983. * @param {Node<vec3>} direction - The direction vector to convert.
  9984. * @returns {Node<vec3>} The converted direction vector.
  9985. */
  9986. const directionToFaceDirection = /*@__PURE__*/ Fn( ( [ direction ], { material } ) => {
  9987. const side = material.side;
  9988. if ( side === BackSide ) {
  9989. direction = direction.mul( -1 );
  9990. } else if ( side === DoubleSide ) {
  9991. direction = direction.mul( faceDirection );
  9992. }
  9993. return direction;
  9994. } );
  9995. /**
  9996. * TSL object that represents the normal attribute of the current rendered object in local space.
  9997. *
  9998. * @tsl
  9999. * @type {Node<vec3>}
  10000. */
  10001. const normalGeometry = /*@__PURE__*/ attribute( 'normal', 'vec3' );
  10002. /**
  10003. * TSL object that represents the vertex normal of the current rendered object in local space.
  10004. *
  10005. * @tsl
  10006. * @type {Node<vec3>}
  10007. */
  10008. const normalLocal = /*@__PURE__*/ ( Fn( ( builder ) => {
  10009. if ( builder.geometry.hasAttribute( 'normal' ) === false ) {
  10010. warn( 'TSL: Vertex attribute "normal" not found on geometry.' );
  10011. return vec3( 0, 1, 0 );
  10012. }
  10013. return normalGeometry;
  10014. }, 'vec3' ).once() )().toVar( 'normalLocal' );
  10015. /**
  10016. * TSL object that represents the flat vertex normal of the current rendered object in view space.
  10017. *
  10018. * @tsl
  10019. * @type {Node<vec3>}
  10020. */
  10021. const normalFlat = /*@__PURE__*/ positionView.dFdx().cross( positionView.dFdy() ).normalize().toVar( 'normalFlat' );
  10022. /**
  10023. * TSL object that represents the vertex normal of the current rendered object in view space.
  10024. *
  10025. * @tsl
  10026. * @type {Node<vec3>}
  10027. */
  10028. const normalViewGeometry = /*@__PURE__*/ ( Fn( ( builder ) => {
  10029. let node;
  10030. if ( builder.material.flatShading === true ) {
  10031. node = normalFlat;
  10032. } else {
  10033. node = transformNormalToView( normalLocal ).toVarying( 'v_normalViewGeometry' ).normalize();
  10034. }
  10035. return node;
  10036. }, 'vec3' ).once() )().toVar( 'normalViewGeometry' );
  10037. /**
  10038. * TSL object that represents the vertex normal of the current rendered object in world space.
  10039. *
  10040. * @tsl
  10041. * @type {Node<vec3>}
  10042. */
  10043. const normalWorldGeometry = /*@__PURE__*/ ( Fn( ( builder ) => {
  10044. let normal = normalViewGeometry.transformDirection( cameraViewMatrix );
  10045. if ( builder.material.flatShading !== true ) {
  10046. normal = normal.toVarying( 'v_normalWorldGeometry' );
  10047. }
  10048. return normal.normalize().toVar( 'normalWorldGeometry' );
  10049. }, 'vec3' ).once() )();
  10050. /**
  10051. * TSL object that represents the vertex normal of the current rendered object in view space.
  10052. *
  10053. * @tsl
  10054. * @type {Node<vec3>}
  10055. */
  10056. const normalView = /*@__PURE__*/ ( Fn( ( { subBuildFn, material, context } ) => {
  10057. let node;
  10058. if ( subBuildFn === 'NORMAL' || subBuildFn === 'VERTEX' ) {
  10059. node = normalViewGeometry;
  10060. if ( material.flatShading !== true ) {
  10061. node = directionToFaceDirection( node );
  10062. }
  10063. } else {
  10064. // Use getUV context to avoid side effects from nodes overwriting getUV in the context (e.g. EnvironmentNode)
  10065. node = context.setupNormal().context( { getUV: null } );
  10066. }
  10067. return node;
  10068. }, 'vec3' ).once( [ 'NORMAL', 'VERTEX' ] ) )().toVar( 'normalView' );
  10069. /**
  10070. * TSL object that represents the vertex normal of the current rendered object in world space.
  10071. *
  10072. * @tsl
  10073. * @type {Node<vec3>}
  10074. */
  10075. const normalWorld = /*@__PURE__*/ normalView.transformDirection( cameraViewMatrix ).toVar( 'normalWorld' );
  10076. /**
  10077. * TSL object that represents the clearcoat vertex normal of the current rendered object in view space.
  10078. *
  10079. * @tsl
  10080. * @type {Node<vec3>}
  10081. */
  10082. const clearcoatNormalView = /*@__PURE__*/ ( Fn( ( { subBuildFn, context } ) => {
  10083. let node;
  10084. if ( subBuildFn === 'NORMAL' || subBuildFn === 'VERTEX' ) {
  10085. node = normalView;
  10086. } else {
  10087. // Use getUV context to avoid side effects from nodes overwriting getUV in the context (e.g. EnvironmentNode)
  10088. node = context.setupClearcoatNormal().context( { getUV: null } );
  10089. }
  10090. return node;
  10091. }, 'vec3' ).once( [ 'NORMAL', 'VERTEX' ] ) )().toVar( 'clearcoatNormalView' );
  10092. /**
  10093. * Transforms the normal with the given matrix.
  10094. *
  10095. * @tsl
  10096. * @function
  10097. * @param {Node<vec3>} normal - The normal.
  10098. * @param {Node<mat3>} [matrix=modelWorldMatrix] - The matrix.
  10099. * @return {Node<vec3>} The transformed normal.
  10100. */
  10101. const transformNormal = /*@__PURE__*/ Fn( ( [ normal, matrix = modelWorldMatrix ] ) => {
  10102. const m = mat3( matrix );
  10103. const transformedNormal = normal.div( vec3( m[ 0 ].dot( m[ 0 ] ), m[ 1 ].dot( m[ 1 ] ), m[ 2 ].dot( m[ 2 ] ) ) );
  10104. return m.mul( transformedNormal ).xyz;
  10105. } );
  10106. /**
  10107. * Transforms the given normal from local to view space.
  10108. *
  10109. * @tsl
  10110. * @function
  10111. * @param {Node<vec3>} normal - The normal.
  10112. * @param {NodeBuilder} builder - The current node builder.
  10113. * @return {Node<vec3>} The transformed normal.
  10114. */
  10115. const transformNormalToView = /*@__PURE__*/ Fn( ( [ normal ], builder ) => {
  10116. const modelNormalViewMatrix = builder.context.modelNormalViewMatrix;
  10117. if ( modelNormalViewMatrix ) {
  10118. return modelNormalViewMatrix.transformDirection( normal );
  10119. }
  10120. //
  10121. const transformedNormal = modelNormalMatrix.mul( normal );
  10122. return cameraViewMatrix.transformDirection( transformedNormal );
  10123. } );
  10124. // Deprecated
  10125. /**
  10126. * TSL object that represents the transformed vertex normal of the current rendered object in view space.
  10127. *
  10128. * @tsl
  10129. * @type {Node<vec3>}
  10130. * @deprecated since r178. Use `normalView` instead.
  10131. */
  10132. const transformedNormalView = ( Fn( () => { // @deprecated, r177
  10133. warn( 'TSL: "transformedNormalView" is deprecated. Use "normalView" instead.' );
  10134. return normalView;
  10135. } ).once( [ 'NORMAL', 'VERTEX' ] ) )();
  10136. /**
  10137. * TSL object that represents the transformed vertex normal of the current rendered object in world space.
  10138. *
  10139. * @tsl
  10140. * @type {Node<vec3>}
  10141. * @deprecated since r178. Use `normalWorld` instead.
  10142. */
  10143. const transformedNormalWorld = ( Fn( () => { // @deprecated, r177
  10144. warn( 'TSL: "transformedNormalWorld" is deprecated. Use "normalWorld" instead.' );
  10145. return normalWorld;
  10146. } ).once( [ 'NORMAL', 'VERTEX' ] ) )();
  10147. /**
  10148. * TSL object that represents the transformed clearcoat vertex normal of the current rendered object in view space.
  10149. *
  10150. * @tsl
  10151. * @type {Node<vec3>}
  10152. * @deprecated since r178. Use `clearcoatNormalView` instead.
  10153. */
  10154. const transformedClearcoatNormalView = ( Fn( () => { // @deprecated, r177
  10155. warn( 'TSL: "transformedClearcoatNormalView" is deprecated. Use "clearcoatNormalView" instead.' );
  10156. return clearcoatNormalView;
  10157. } ).once( [ 'NORMAL', 'VERTEX' ] ) )();
  10158. const _e1$1 = /*@__PURE__*/ new Euler();
  10159. const _m1$1 = /*@__PURE__*/ new Matrix4();
  10160. /**
  10161. * TSL object that represents the refraction ratio of the material used for rendering the current object.
  10162. *
  10163. * @tsl
  10164. * @type {UniformNode<float>}
  10165. */
  10166. const materialRefractionRatio = /*@__PURE__*/ uniform( 0 ).onReference( ( { material } ) => material ).onObjectUpdate( ( { material } ) => material.refractionRatio );
  10167. /**
  10168. * TSL object that represents the intensity of environment maps of PBR materials.
  10169. * When `material.envMap` is set, the value is `material.envMapIntensity` otherwise `scene.environmentIntensity`.
  10170. *
  10171. * @tsl
  10172. * @type {Node<float>}
  10173. */
  10174. const materialEnvIntensity = /*@__PURE__*/ uniform( 1 ).onReference( ( { material } ) => material ).onObjectUpdate( function ( { material, scene } ) {
  10175. return material.envMap ? material.envMapIntensity : scene.environmentIntensity;
  10176. } );
  10177. /**
  10178. * TSL object that represents the rotation of environment maps.
  10179. * When `material.envMap` is set, the value is `material.envMapRotation`. `scene.environmentRotation` controls the
  10180. * rotation of `scene.environment` instead.
  10181. *
  10182. * @tsl
  10183. * @type {Node<mat4>}
  10184. */
  10185. const materialEnvRotation = /*@__PURE__*/ uniform( new Matrix4() ).onReference( function ( frame ) {
  10186. return frame.material;
  10187. } ).onObjectUpdate( function ( { material, scene } ) {
  10188. const rotation = ( scene.environment !== null && material.envMap === null ) ? scene.environmentRotation : material.envMapRotation;
  10189. if ( rotation ) {
  10190. _e1$1.copy( rotation );
  10191. _m1$1.makeRotationFromEuler( _e1$1 );
  10192. } else {
  10193. _m1$1.identity();
  10194. }
  10195. return _m1$1;
  10196. } );
  10197. /**
  10198. * The reflect vector in view space.
  10199. *
  10200. * @tsl
  10201. * @type {Node<vec3>}
  10202. */
  10203. const reflectView = /*@__PURE__*/ positionViewDirection.negate().reflect( normalView );
  10204. /**
  10205. * The refract vector in view space.
  10206. *
  10207. * @tsl
  10208. * @type {Node<vec3>}
  10209. */
  10210. const refractView = /*@__PURE__*/ positionViewDirection.negate().refract( normalView, materialRefractionRatio );
  10211. /**
  10212. * Used for sampling cube maps when using cube reflection mapping.
  10213. *
  10214. * @tsl
  10215. * @type {Node<vec3>}
  10216. */
  10217. const reflectVector = /*@__PURE__*/ reflectView.transformDirection( cameraViewMatrix ).toVar( 'reflectVector' );
  10218. /**
  10219. * Used for sampling cube maps when using cube refraction mapping.
  10220. *
  10221. * @tsl
  10222. * @type {Node<vec3>}
  10223. */
  10224. const refractVector = /*@__PURE__*/ refractView.transformDirection( cameraViewMatrix ).toVar( 'reflectVector' );
  10225. const EmptyTexture = /*@__PURE__*/ new CubeTexture();
  10226. /**
  10227. * This type of uniform node represents a cube texture.
  10228. *
  10229. * @augments TextureNode
  10230. */
  10231. class CubeTextureNode extends TextureNode {
  10232. static get type() {
  10233. return 'CubeTextureNode';
  10234. }
  10235. /**
  10236. * Constructs a new cube texture node.
  10237. *
  10238. * @param {CubeTexture} value - The cube texture.
  10239. * @param {?Node<vec3>} [uvNode=null] - The uv node.
  10240. * @param {?Node<int>} [levelNode=null] - The level node.
  10241. * @param {?Node<float>} [biasNode=null] - The bias node.
  10242. */
  10243. constructor( value, uvNode = null, levelNode = null, biasNode = null ) {
  10244. super( value, uvNode, levelNode, biasNode );
  10245. /**
  10246. * This flag can be used for type testing.
  10247. *
  10248. * @type {boolean}
  10249. * @readonly
  10250. * @default true
  10251. */
  10252. this.isCubeTextureNode = true;
  10253. }
  10254. /**
  10255. * Overwrites the default implementation to return the appropriate cube texture type.
  10256. *
  10257. * @param {NodeBuilder} builder - The current node builder.
  10258. * @return {string} The input type.
  10259. */
  10260. getInputType( /*builder*/ ) {
  10261. if ( this.value.isDepthTexture === true ) {
  10262. return 'cubeDepthTexture';
  10263. }
  10264. return 'cubeTexture';
  10265. }
  10266. /**
  10267. * Returns a default uvs based on the mapping type of the cube texture.
  10268. *
  10269. * @return {Node<vec3>} The default uv attribute.
  10270. */
  10271. getDefaultUV() {
  10272. const texture = this.value;
  10273. if ( texture.mapping === CubeReflectionMapping ) {
  10274. return reflectVector;
  10275. } else if ( texture.mapping === CubeRefractionMapping ) {
  10276. return refractVector;
  10277. } else {
  10278. error( 'CubeTextureNode: Mapping "%s" not supported.', texture.mapping );
  10279. return vec3( 0, 0, 0 );
  10280. }
  10281. }
  10282. /**
  10283. * Overwritten with an empty implementation since the `updateMatrix` flag is ignored
  10284. * for cube textures. The uv transformation matrix is not applied to cube textures.
  10285. *
  10286. * @param {boolean} value - The update toggle.
  10287. */
  10288. setUpdateMatrix( /*updateMatrix*/ ) { } // Ignore .updateMatrix for CubeTextureNode
  10289. /**
  10290. * Setups the uv node. Depending on the backend as well as the texture type, it might be necessary
  10291. * to modify the uv node for correct sampling.
  10292. *
  10293. * @param {NodeBuilder} builder - The current node builder.
  10294. * @param {Node} uvNode - The uv node to setup.
  10295. * @return {Node} The updated uv node.
  10296. */
  10297. setupUV( builder, uvNode ) {
  10298. const texture = this.value;
  10299. // Depth textures (shadow maps) - no environment rotation, Y flip for WebGPU
  10300. if ( texture.isDepthTexture === true ) {
  10301. if ( builder.renderer.coordinateSystem === WebGPUCoordinateSystem ) {
  10302. return vec3( uvNode.x, uvNode.y.negate(), uvNode.z );
  10303. }
  10304. return uvNode;
  10305. }
  10306. if ( builder.renderer.coordinateSystem === WebGPUCoordinateSystem || ! texture.isRenderTargetTexture ) {
  10307. uvNode = vec3( uvNode.x.negate(), uvNode.yz );
  10308. }
  10309. return materialEnvRotation.mul( uvNode );
  10310. }
  10311. /**
  10312. * Generates the uv code snippet.
  10313. *
  10314. * @param {NodeBuilder} builder - The current node builder.
  10315. * @param {Node} cubeUV - The uv node to generate code for.
  10316. * @return {string} The generated code snippet.
  10317. */
  10318. generateUV( builder, cubeUV ) {
  10319. return cubeUV.build( builder, this.sampler === true ? 'vec3' : 'ivec3' );
  10320. }
  10321. }
  10322. /**
  10323. * TSL function for creating a cube texture node.
  10324. *
  10325. * @tsl
  10326. * @function
  10327. * @param {CubeTexture} value - The cube texture.
  10328. * @param {?Node<vec3>} [uvNode=null] - The uv node.
  10329. * @param {?Node<int>} [levelNode=null] - The level node.
  10330. * @param {?Node<float>} [biasNode=null] - The bias node.
  10331. * @returns {CubeTextureNode}
  10332. */
  10333. const cubeTextureBase = /*@__PURE__*/ nodeProxy( CubeTextureNode ).setParameterLength( 1, 4 ).setName( 'cubeTexture' );
  10334. /**
  10335. * TSL function for creating a cube texture uniform node.
  10336. *
  10337. * @tsl
  10338. * @function
  10339. * @param {?(CubeTexture|CubeTextureNode)} [value=EmptyTexture] - The cube texture.
  10340. * @param {?Node<vec3>} [uvNode=null] - The uv node.
  10341. * @param {?Node<int>} [levelNode=null] - The level node.
  10342. * @param {?Node<float>} [biasNode=null] - The bias node.
  10343. * @returns {CubeTextureNode}
  10344. */
  10345. const cubeTexture = ( value = EmptyTexture, uvNode = null, levelNode = null, biasNode = null ) => {
  10346. let textureNode;
  10347. if ( value && value.isCubeTextureNode === true ) {
  10348. textureNode = nodeObject( value.clone() );
  10349. textureNode.referenceNode = value; // Ensure the reference is set to the original node
  10350. if ( uvNode !== null ) textureNode.uvNode = nodeObject( uvNode );
  10351. if ( levelNode !== null ) textureNode.levelNode = nodeObject( levelNode );
  10352. if ( biasNode !== null ) textureNode.biasNode = nodeObject( biasNode );
  10353. } else {
  10354. textureNode = cubeTextureBase( value, uvNode, levelNode, biasNode );
  10355. }
  10356. return textureNode;
  10357. };
  10358. /**
  10359. * TSL function for creating a uniform cube texture node.
  10360. *
  10361. * @tsl
  10362. * @function
  10363. * @param {?CubeTexture} [value=EmptyTexture] - The cube texture.
  10364. * @returns {CubeTextureNode}
  10365. */
  10366. const uniformCubeTexture = ( value = EmptyTexture ) => cubeTextureBase( value );
  10367. // TODO: Avoid duplicated code and use only ReferenceBaseNode or ReferenceNode
  10368. /**
  10369. * This class is only relevant if the referenced property is array-like.
  10370. * In this case, `ReferenceElementNode` allows to refer to a specific
  10371. * element inside the data structure via an index.
  10372. *
  10373. * @augments ArrayElementNode
  10374. */
  10375. class ReferenceElementNode extends ArrayElementNode {
  10376. static get type() {
  10377. return 'ReferenceElementNode';
  10378. }
  10379. /**
  10380. * Constructs a new reference element node.
  10381. *
  10382. * @param {?ReferenceNode} referenceNode - The reference node.
  10383. * @param {Node} indexNode - The index node that defines the element access.
  10384. */
  10385. constructor( referenceNode, indexNode ) {
  10386. super( referenceNode, indexNode );
  10387. /**
  10388. * Similar to {@link ReferenceNode#reference}, an additional
  10389. * property references to the current node.
  10390. *
  10391. * @type {?ReferenceNode}
  10392. * @default null
  10393. */
  10394. this.referenceNode = referenceNode;
  10395. /**
  10396. * This flag can be used for type testing.
  10397. *
  10398. * @type {boolean}
  10399. * @readonly
  10400. * @default true
  10401. */
  10402. this.isReferenceElementNode = true;
  10403. }
  10404. /**
  10405. * This method is overwritten since the node type is inferred from
  10406. * the uniform type of the reference node.
  10407. *
  10408. * @return {string} The node type.
  10409. */
  10410. getNodeType() {
  10411. return this.referenceNode.uniformType;
  10412. }
  10413. generate( builder ) {
  10414. const snippet = super.generate( builder );
  10415. const arrayType = this.referenceNode.getNodeType();
  10416. const elementType = this.getNodeType();
  10417. return builder.format( snippet, arrayType, elementType );
  10418. }
  10419. }
  10420. /**
  10421. * This type of node establishes a reference to a property of another object.
  10422. * In this way, the value of the node is automatically linked to the value of
  10423. * referenced object. Reference nodes internally represent the linked value
  10424. * as a uniform.
  10425. *
  10426. * @augments Node
  10427. */
  10428. class ReferenceNode extends Node {
  10429. static get type() {
  10430. return 'ReferenceNode';
  10431. }
  10432. /**
  10433. * Constructs a new reference node.
  10434. *
  10435. * @param {string} property - The name of the property the node refers to.
  10436. * @param {string} uniformType - The uniform type that should be used to represent the property value.
  10437. * @param {?Object} [object=null] - The object the property belongs to.
  10438. * @param {?number} [count=null] - When the linked property is an array-like, this parameter defines its length.
  10439. */
  10440. constructor( property, uniformType, object = null, count = null ) {
  10441. super();
  10442. /**
  10443. * The name of the property the node refers to.
  10444. *
  10445. * @type {string}
  10446. */
  10447. this.property = property;
  10448. /**
  10449. * The uniform type that should be used to represent the property value.
  10450. *
  10451. * @type {string}
  10452. */
  10453. this.uniformType = uniformType;
  10454. /**
  10455. * The object the property belongs to.
  10456. *
  10457. * @type {?Object}
  10458. * @default null
  10459. */
  10460. this.object = object;
  10461. /**
  10462. * When the linked property is an array, this parameter defines its length.
  10463. *
  10464. * @type {?number}
  10465. * @default null
  10466. */
  10467. this.count = count;
  10468. /**
  10469. * The property name might have dots so nested properties can be referred.
  10470. * The hierarchy of the names is stored inside this array.
  10471. *
  10472. * @type {Array<string>}
  10473. */
  10474. this.properties = property.split( '.' );
  10475. /**
  10476. * Points to the current referred object. This property exists next to {@link ReferenceNode#object}
  10477. * since the final reference might be updated from calling code.
  10478. *
  10479. * @type {?Object}
  10480. * @default null
  10481. */
  10482. this.reference = object;
  10483. /**
  10484. * The uniform node that holds the value of the reference node.
  10485. *
  10486. * @type {UniformNode}
  10487. * @default null
  10488. */
  10489. this.node = null;
  10490. /**
  10491. * The uniform group of the internal uniform.
  10492. *
  10493. * @type {UniformGroupNode}
  10494. * @default null
  10495. */
  10496. this.group = null;
  10497. /**
  10498. * An optional label of the internal uniform node.
  10499. *
  10500. * @type {?string}
  10501. * @default null
  10502. */
  10503. this.name = null;
  10504. /**
  10505. * Overwritten since reference nodes are updated per object.
  10506. *
  10507. * @type {string}
  10508. * @default 'object'
  10509. */
  10510. this.updateType = NodeUpdateType.OBJECT;
  10511. }
  10512. /**
  10513. * When the referred property is array-like, this method can be used
  10514. * to access elements via an index node.
  10515. *
  10516. * @param {IndexNode} indexNode - indexNode.
  10517. * @return {ReferenceElementNode} A reference to an element.
  10518. */
  10519. element( indexNode ) {
  10520. return nodeObject( new ReferenceElementNode( this, nodeObject( indexNode ) ) );
  10521. }
  10522. /**
  10523. * Sets the uniform group for this reference node.
  10524. *
  10525. * @param {UniformGroupNode} group - The uniform group to set.
  10526. * @return {ReferenceNode} A reference to this node.
  10527. */
  10528. setGroup( group ) {
  10529. this.group = group;
  10530. return this;
  10531. }
  10532. /**
  10533. * Sets the name for the internal uniform.
  10534. *
  10535. * @param {string} name - The label to set.
  10536. * @return {ReferenceNode} A reference to this node.
  10537. */
  10538. setName( name ) {
  10539. this.name = name;
  10540. return this;
  10541. }
  10542. /**
  10543. * Sets the label for the internal uniform.
  10544. *
  10545. * @deprecated
  10546. * @param {string} name - The label to set.
  10547. * @return {ReferenceNode} A reference to this node.
  10548. */
  10549. label( name ) {
  10550. warn( 'TSL: "label()" has been deprecated. Use "setName()" instead.' ); // @deprecated r179
  10551. return this.setName( name );
  10552. }
  10553. /**
  10554. * Sets the node type which automatically defines the internal
  10555. * uniform type.
  10556. *
  10557. * @param {string} uniformType - The type to set.
  10558. */
  10559. setNodeType( uniformType ) {
  10560. let node = null;
  10561. if ( this.count !== null ) {
  10562. node = buffer( null, uniformType, this.count );
  10563. } else if ( Array.isArray( this.getValueFromReference() ) ) {
  10564. node = uniformArray( null, uniformType );
  10565. } else if ( uniformType === 'texture' ) {
  10566. node = texture( null );
  10567. } else if ( uniformType === 'cubeTexture' ) {
  10568. node = cubeTexture( null );
  10569. } else {
  10570. node = uniform( null, uniformType );
  10571. }
  10572. if ( this.group !== null ) {
  10573. node.setGroup( this.group );
  10574. }
  10575. if ( this.name !== null ) node.setName( this.name );
  10576. this.node = node;
  10577. }
  10578. /**
  10579. * This method is overwritten since the node type is inferred from
  10580. * the type of the reference node.
  10581. *
  10582. * @param {NodeBuilder} builder - The current node builder.
  10583. * @return {string} The node type.
  10584. */
  10585. getNodeType( builder ) {
  10586. if ( this.node === null ) {
  10587. this.updateReference( builder );
  10588. this.updateValue();
  10589. }
  10590. return this.node.getNodeType( builder );
  10591. }
  10592. /**
  10593. * Returns the property value from the given referred object.
  10594. *
  10595. * @param {Object} [object=this.reference] - The object to retrieve the property value from.
  10596. * @return {any} The value.
  10597. */
  10598. getValueFromReference( object = this.reference ) {
  10599. const { properties } = this;
  10600. let value = object[ properties[ 0 ] ];
  10601. for ( let i = 1; i < properties.length; i ++ ) {
  10602. value = value[ properties[ i ] ];
  10603. }
  10604. return value;
  10605. }
  10606. /**
  10607. * Allows to update the reference based on the given state. The state is only
  10608. * evaluated {@link ReferenceNode#object} is not set.
  10609. *
  10610. * @param {(NodeFrame|NodeBuilder)} state - The current state.
  10611. * @return {Object} The updated reference.
  10612. */
  10613. updateReference( state ) {
  10614. this.reference = this.object !== null ? this.object : state.object;
  10615. return this.reference;
  10616. }
  10617. /**
  10618. * The output of the reference node is the internal uniform node.
  10619. *
  10620. * @param {NodeBuilder} builder - The current node builder.
  10621. * @return {UniformNode} The output node.
  10622. */
  10623. setup( /* builder */ ) {
  10624. this.updateValue();
  10625. return this.node;
  10626. }
  10627. /**
  10628. * Overwritten to update the internal uniform value.
  10629. *
  10630. * @param {NodeFrame} frame - A reference to the current node frame.
  10631. */
  10632. update( /*frame*/ ) {
  10633. this.updateValue();
  10634. }
  10635. /**
  10636. * Retrieves the value from the referred object property and uses it
  10637. * to updated the internal uniform.
  10638. */
  10639. updateValue() {
  10640. if ( this.node === null ) this.setNodeType( this.uniformType );
  10641. const value = this.getValueFromReference();
  10642. if ( Array.isArray( value ) ) {
  10643. this.node.array = value;
  10644. } else {
  10645. this.node.value = value;
  10646. }
  10647. }
  10648. }
  10649. /**
  10650. * TSL function for creating a reference node.
  10651. *
  10652. * @tsl
  10653. * @function
  10654. * @param {string} name - The name of the property the node refers to.
  10655. * @param {string} type - The uniform type that should be used to represent the property value.
  10656. * @param {?Object} [object] - The object the property belongs to.
  10657. * @returns {ReferenceNode}
  10658. */
  10659. const reference = ( name, type, object ) => nodeObject( new ReferenceNode( name, type, object ) );
  10660. /**
  10661. * TSL function for creating a reference node. Use this function if you want need a reference
  10662. * to an array-like property that should be represented as a uniform buffer.
  10663. *
  10664. * @tsl
  10665. * @function
  10666. * @param {string} name - The name of the property the node refers to.
  10667. * @param {string} type - The uniform type that should be used to represent the property value.
  10668. * @param {number} count - The number of value inside the array-like object.
  10669. * @param {Object} object - An array-like object the property belongs to.
  10670. * @returns {ReferenceNode}
  10671. */
  10672. const referenceBuffer = ( name, type, count, object ) => nodeObject( new ReferenceNode( name, type, object, count ) );
  10673. /**
  10674. * This node is a special type of reference node which is intended
  10675. * for linking material properties with node values.
  10676. * ```js
  10677. * const opacityNode = materialReference( 'opacity', 'float', material );
  10678. * ```
  10679. * When changing `material.opacity`, the node value of `opacityNode` will
  10680. * automatically be updated.
  10681. *
  10682. * @augments ReferenceNode
  10683. */
  10684. class MaterialReferenceNode extends ReferenceNode {
  10685. static get type() {
  10686. return 'MaterialReferenceNode';
  10687. }
  10688. /**
  10689. * Constructs a new material reference node.
  10690. *
  10691. * @param {string} property - The name of the property the node refers to.
  10692. * @param {string} inputType - The uniform type that should be used to represent the property value.
  10693. * @param {?Material} [material=null] - The material the property belongs to. When no material is set,
  10694. * the node refers to the material of the current rendered object.
  10695. */
  10696. constructor( property, inputType, material = null ) {
  10697. super( property, inputType, material );
  10698. /**
  10699. * The material the property belongs to. When no material is set,
  10700. * the node refers to the material of the current rendered object.
  10701. *
  10702. * @type {?Material}
  10703. * @default null
  10704. */
  10705. this.material = material;
  10706. /**
  10707. * This flag can be used for type testing.
  10708. *
  10709. * @type {boolean}
  10710. * @readonly
  10711. * @default true
  10712. */
  10713. this.isMaterialReferenceNode = true;
  10714. }
  10715. /**
  10716. * Updates the reference based on the given state. The state is only evaluated
  10717. * {@link MaterialReferenceNode#material} is not set.
  10718. *
  10719. * @param {(NodeFrame|NodeBuilder)} state - The current state.
  10720. * @return {Object} The updated reference.
  10721. */
  10722. updateReference( state ) {
  10723. this.reference = this.material !== null ? this.material : state.material;
  10724. return this.reference;
  10725. }
  10726. }
  10727. /**
  10728. * TSL function for creating a material reference node.
  10729. *
  10730. * @tsl
  10731. * @function
  10732. * @param {string} name - The name of the property the node refers to.
  10733. * @param {string} type - The uniform type that should be used to represent the property value.
  10734. * @param {?Material} [material=null] - The material the property belongs to.
  10735. * When no material is set, the node refers to the material of the current rendered object.
  10736. * @returns {MaterialReferenceNode}
  10737. */
  10738. const materialReference = ( name, type, material = null ) => nodeObject( new MaterialReferenceNode( name, type, material ) );
  10739. // Normal Mapping Without Precomputed Tangents
  10740. // http://www.thetenthplanet.de/archives/1180
  10741. const uv = uv$1();
  10742. const q0 = positionView.dFdx();
  10743. const q1 = positionView.dFdy();
  10744. const st0 = uv.dFdx();
  10745. const st1 = uv.dFdy();
  10746. const N = normalView;
  10747. const q1perp = q1.cross( N );
  10748. const q0perp = N.cross( q0 );
  10749. const T = q1perp.mul( st0.x ).add( q0perp.mul( st1.x ) );
  10750. const B = q1perp.mul( st0.y ).add( q0perp.mul( st1.y ) );
  10751. const det = T.dot( T ).max( B.dot( B ) );
  10752. const scale$1 = det.equal( 0.0 ).select( 0.0, det.inverseSqrt() );
  10753. /**
  10754. * Tangent vector in view space, computed dynamically from geometry and UV derivatives.
  10755. * Useful for normal mapping without precomputed tangents.
  10756. *
  10757. * Reference: http://www.thetenthplanet.de/archives/1180
  10758. *
  10759. * @tsl
  10760. * @type {Node<vec3>}
  10761. */
  10762. const tangentViewFrame = /*@__PURE__*/ T.mul( scale$1 ).toVar( 'tangentViewFrame' );
  10763. /**
  10764. * Bitangent vector in view space, computed dynamically from geometry and UV derivatives.
  10765. * Complements the tangentViewFrame for constructing the tangent space basis.
  10766. *
  10767. * Reference: http://www.thetenthplanet.de/archives/1180
  10768. *
  10769. * @tsl
  10770. * @type {Node<vec3>}
  10771. */
  10772. const bitangentViewFrame = /*@__PURE__*/ B.mul( scale$1 ).toVar( 'bitangentViewFrame' );
  10773. /**
  10774. * TSL object that represents the tangent attribute of the current rendered object.
  10775. *
  10776. * @tsl
  10777. * @type {Node<vec4>}
  10778. */
  10779. const tangentGeometry = /*@__PURE__*/ attribute( 'tangent', 'vec4' );
  10780. /**
  10781. * TSL object that represents the vertex tangent in local space of the current rendered object.
  10782. *
  10783. * @tsl
  10784. * @type {Node<vec3>}
  10785. */
  10786. const tangentLocal = /*@__PURE__*/ tangentGeometry.xyz.toVar( 'tangentLocal' );
  10787. /**
  10788. * TSL object that represents the vertex tangent in view space of the current rendered object.
  10789. *
  10790. * @tsl
  10791. * @type {Node<vec3>}
  10792. */
  10793. const tangentView = /*@__PURE__*/ ( Fn( ( { subBuildFn, geometry, material } ) => {
  10794. let node;
  10795. if ( subBuildFn === 'VERTEX' || geometry.hasAttribute( 'tangent' ) ) {
  10796. node = modelViewMatrix.mul( vec4( tangentLocal, 0 ) ).xyz.toVarying( 'v_tangentView' ).normalize();
  10797. } else {
  10798. node = tangentViewFrame;
  10799. }
  10800. if ( material.flatShading !== true ) {
  10801. node = directionToFaceDirection( node );
  10802. }
  10803. return node;
  10804. }, 'vec3' ).once( [ 'NORMAL', 'VERTEX' ] ) )().toVar( 'tangentView' );
  10805. /**
  10806. * TSL object that represents the vertex tangent in world space of the current rendered object.
  10807. *
  10808. * @tsl
  10809. * @type {Node<vec3>}
  10810. */
  10811. const tangentWorld = /*@__PURE__*/ tangentView.transformDirection( cameraViewMatrix ).toVarying( 'v_tangentWorld' ).normalize().toVar( 'tangentWorld' );
  10812. /**
  10813. * Returns the bitangent node and assigns it to a varying if the material is not flat shaded.
  10814. *
  10815. * @tsl
  10816. * @private
  10817. * @param {Node<vec3>} crossNormalTangent - The cross product of the normal and tangent vectors.
  10818. * @param {string} varyingName - The name of the varying to assign the bitangent to.
  10819. * @returns {Node<vec3>} The bitangent node.
  10820. */
  10821. const getBitangent = /*@__PURE__*/ Fn( ( [ crossNormalTangent, varyingName ], { subBuildFn, material } ) => {
  10822. let bitangent = crossNormalTangent.mul( tangentGeometry.w ).xyz;
  10823. if ( subBuildFn === 'NORMAL' && material.flatShading !== true ) {
  10824. bitangent = bitangent.toVarying( varyingName );
  10825. }
  10826. return bitangent;
  10827. } ).once( [ 'NORMAL' ] );
  10828. /**
  10829. * TSL object that represents the bitangent attribute of the current rendered object.
  10830. *
  10831. * @tsl
  10832. * @type {Node<vec3>}
  10833. */
  10834. const bitangentGeometry = /*@__PURE__*/ getBitangent( normalGeometry.cross( tangentGeometry ), 'v_bitangentGeometry' ).normalize().toVar( 'bitangentGeometry' );
  10835. /**
  10836. * TSL object that represents the vertex bitangent in local space of the current rendered object.
  10837. *
  10838. * @tsl
  10839. * @type {Node<vec3>}
  10840. */
  10841. const bitangentLocal = /*@__PURE__*/ getBitangent( normalLocal.cross( tangentLocal ), 'v_bitangentLocal' ).normalize().toVar( 'bitangentLocal' );
  10842. /**
  10843. * TSL object that represents the vertex bitangent in view space of the current rendered object.
  10844. *
  10845. * @tsl
  10846. * @type {Node<vec3>}
  10847. */
  10848. const bitangentView = /*@__PURE__*/ ( Fn( ( { subBuildFn, geometry, material } ) => {
  10849. let node;
  10850. if ( subBuildFn === 'VERTEX' || geometry.hasAttribute( 'tangent' ) ) {
  10851. node = getBitangent( normalView.cross( tangentView ), 'v_bitangentView' ).normalize();
  10852. } else {
  10853. node = bitangentViewFrame;
  10854. }
  10855. if ( material.flatShading !== true ) {
  10856. node = directionToFaceDirection( node );
  10857. }
  10858. return node;
  10859. }, 'vec3' ).once( [ 'NORMAL', 'VERTEX' ] ) )().toVar( 'bitangentView' );
  10860. /**
  10861. * TSL object that represents the vertex bitangent in world space of the current rendered object.
  10862. *
  10863. * @tsl
  10864. * @type {Node<vec3>}
  10865. */
  10866. const bitangentWorld = /*@__PURE__*/ getBitangent( normalWorld.cross( tangentWorld ), 'v_bitangentWorld' ).normalize().toVar( 'bitangentWorld' );
  10867. /**
  10868. * TSL object that represents the TBN matrix in view space.
  10869. *
  10870. * @tsl
  10871. * @type {Node<mat3>}
  10872. */
  10873. const TBNViewMatrix = /*@__PURE__*/ mat3( tangentView, bitangentView, normalView ).toVar( 'TBNViewMatrix' );
  10874. /**
  10875. * TSL object that represents the parallax direction.
  10876. *
  10877. * @tsl
  10878. * @type {Node<mat3>}
  10879. */
  10880. const parallaxDirection = /*@__PURE__*/ positionViewDirection.mul( TBNViewMatrix )/*.normalize()*/;
  10881. /**
  10882. * TSL function for computing parallax uv coordinates.
  10883. *
  10884. * @tsl
  10885. * @function
  10886. * @param {Node<vec2>} uv - A uv node.
  10887. * @param {Node<vec2>} scale - A scale node.
  10888. * @returns {Node<vec2>} Parallax uv coordinates.
  10889. */
  10890. const parallaxUV = ( uv, scale ) => uv.sub( parallaxDirection.mul( scale ) );
  10891. /**
  10892. * TSL function for computing bent normals.
  10893. *
  10894. * @tsl
  10895. * @function
  10896. * @returns {Node<vec3>} Bent normals.
  10897. */
  10898. const bentNormalView = /*@__PURE__*/ ( Fn( () => {
  10899. // https://google.github.io/filament/Filament.md.html#lighting/imagebasedlights/anisotropy
  10900. let bentNormal = anisotropyB.cross( positionViewDirection );
  10901. bentNormal = bentNormal.cross( anisotropyB ).normalize();
  10902. bentNormal = mix( bentNormal, normalView, anisotropy.mul( roughness.oneMinus() ).oneMinus().pow2().pow2() ).normalize();
  10903. return bentNormal;
  10904. } ).once() )();
  10905. /**
  10906. * Packs a direction vector into a color value.
  10907. *
  10908. * @tsl
  10909. * @function
  10910. * @param {Node<vec3>} node - The direction to pack.
  10911. * @return {Node<vec3>} The color.
  10912. */
  10913. const directionToColor = ( node ) => nodeObject( node ).mul( 0.5 ).add( 0.5 );
  10914. /**
  10915. * Unpacks a color value into a direction vector.
  10916. *
  10917. * @tsl
  10918. * @function
  10919. * @param {Node<vec3>} node - The color to unpack.
  10920. * @return {Node<vec3>} The direction.
  10921. */
  10922. const colorToDirection = ( node ) => nodeObject( node ).mul( 2.0 ).sub( 1 );
  10923. /**
  10924. * Unpacks a tangent space normal, reconstructing the Z component by projecting the X,Y coordinates onto the hemisphere.
  10925. * The X,Y coordinates are expected to be in the [-1, 1] range.
  10926. *
  10927. * @tsl
  10928. * @function
  10929. * @param {Node<vec2>} xy - The X,Y coordinates of the normal.
  10930. * @return {Node<vec3>} The resulting normal.
  10931. */
  10932. const unpackNormal = ( xy ) => vec3( xy, sqrt( saturate( float( 1.0 ).sub( dot( xy, xy ) ) ) ) );
  10933. /**
  10934. * This class can be used for applying normals maps to materials.
  10935. *
  10936. * ```js
  10937. * material.normalNode = normalMap( texture( normalTex ) );
  10938. * ```
  10939. *
  10940. * @augments TempNode
  10941. */
  10942. class NormalMapNode extends TempNode {
  10943. static get type() {
  10944. return 'NormalMapNode';
  10945. }
  10946. /**
  10947. * Constructs a new normal map node.
  10948. *
  10949. * @param {Node<vec3>} node - Represents the normal map data.
  10950. * @param {?Node<vec2>} [scaleNode=null] - Controls the intensity of the effect.
  10951. */
  10952. constructor( node, scaleNode = null ) {
  10953. super( 'vec3' );
  10954. /**
  10955. * Represents the normal map data.
  10956. *
  10957. * @type {Node<vec3>}
  10958. */
  10959. this.node = node;
  10960. /**
  10961. * Controls the intensity of the effect.
  10962. *
  10963. * @type {?Node<vec2>}
  10964. * @default null
  10965. */
  10966. this.scaleNode = scaleNode;
  10967. /**
  10968. * The normal map type.
  10969. *
  10970. * @type {(TangentSpaceNormalMap|ObjectSpaceNormalMap)}
  10971. * @default TangentSpaceNormalMap
  10972. */
  10973. this.normalMapType = TangentSpaceNormalMap;
  10974. /**
  10975. * Controls how to unpack the sampled normal map values.
  10976. *
  10977. * @type {string}
  10978. * @default NoNormalPacking
  10979. */
  10980. this.unpackNormalMode = NoNormalPacking;
  10981. }
  10982. setup( { material } ) {
  10983. const { normalMapType, scaleNode, unpackNormalMode } = this;
  10984. let normalMap = this.node.mul( 2.0 ).sub( 1.0 );
  10985. if ( normalMapType === TangentSpaceNormalMap ) {
  10986. if ( unpackNormalMode === NormalRGPacking ) {
  10987. normalMap = unpackNormal( normalMap.xy );
  10988. } else if ( unpackNormalMode === NormalGAPacking ) {
  10989. normalMap = unpackNormal( normalMap.yw );
  10990. } else if ( unpackNormalMode !== NoNormalPacking ) {
  10991. console.error( `THREE.NodeMaterial: Unexpected unpack normal mode: ${ unpackNormalMode }` );
  10992. }
  10993. } else {
  10994. if ( unpackNormalMode !== NoNormalPacking ) {
  10995. console.error( `THREE.NodeMaterial: Normal map type '${ normalMapType }' is not compatible with unpack normal mode '${ unpackNormalMode }'` );
  10996. }
  10997. }
  10998. if ( scaleNode !== null ) {
  10999. let scale = scaleNode;
  11000. if ( material.flatShading === true ) {
  11001. scale = directionToFaceDirection( scale );
  11002. }
  11003. normalMap = vec3( normalMap.xy.mul( scale ), normalMap.z );
  11004. }
  11005. let output = null;
  11006. if ( normalMapType === ObjectSpaceNormalMap ) {
  11007. output = transformNormalToView( normalMap );
  11008. } else if ( normalMapType === TangentSpaceNormalMap ) {
  11009. output = TBNViewMatrix.mul( normalMap ).normalize();
  11010. } else {
  11011. error( `NodeMaterial: Unsupported normal map type: ${ normalMapType }` );
  11012. output = normalView; // Fallback to default normal view
  11013. }
  11014. return output;
  11015. }
  11016. }
  11017. /**
  11018. * TSL function for creating a normal map node.
  11019. *
  11020. * @tsl
  11021. * @function
  11022. * @param {Node<vec3>} node - Represents the normal map data.
  11023. * @param {?Node<vec2>} [scaleNode=null] - Controls the intensity of the effect.
  11024. * @returns {NormalMapNode}
  11025. */
  11026. const normalMap = /*@__PURE__*/ nodeProxy( NormalMapNode ).setParameterLength( 1, 2 );
  11027. // Bump Mapping Unparametrized Surfaces on the GPU by Morten S. Mikkelsen
  11028. // https://mmikk.github.io/papers3d/mm_sfgrad_bump.pdf
  11029. const dHdxy_fwd = Fn( ( { textureNode, bumpScale } ) => {
  11030. // It's used to preserve the same TextureNode instance
  11031. const sampleTexture = ( callback ) => textureNode.isolate().context( { getUV: ( texNode ) => callback( texNode.uvNode || uv$1() ), forceUVContext: true } );
  11032. const Hll = float( sampleTexture( ( uvNode ) => uvNode ) );
  11033. return vec2(
  11034. float( sampleTexture( ( uvNode ) => uvNode.add( uvNode.dFdx() ) ) ).sub( Hll ),
  11035. float( sampleTexture( ( uvNode ) => uvNode.add( uvNode.dFdy() ) ) ).sub( Hll )
  11036. ).mul( bumpScale );
  11037. } );
  11038. // Evaluate the derivative of the height w.r.t. screen-space using forward differencing (listing 2)
  11039. const perturbNormalArb = Fn( ( inputs ) => {
  11040. const { surf_pos, surf_norm, dHdxy } = inputs;
  11041. // normalize is done to ensure that the bump map looks the same regardless of the texture's scale
  11042. const vSigmaX = surf_pos.dFdx().normalize();
  11043. const vSigmaY = surf_pos.dFdy().normalize();
  11044. const vN = surf_norm; // normalized
  11045. const R1 = vSigmaY.cross( vN );
  11046. const R2 = vN.cross( vSigmaX );
  11047. const fDet = vSigmaX.dot( R1 ).mul( faceDirection );
  11048. const vGrad = fDet.sign().mul( dHdxy.x.mul( R1 ).add( dHdxy.y.mul( R2 ) ) );
  11049. return fDet.abs().mul( surf_norm ).sub( vGrad ).normalize();
  11050. } );
  11051. /**
  11052. * This class can be used for applying bump maps to materials.
  11053. *
  11054. * ```js
  11055. * material.normalNode = bumpMap( texture( bumpTex ) );
  11056. * ```
  11057. *
  11058. * @augments TempNode
  11059. */
  11060. class BumpMapNode extends TempNode {
  11061. static get type() {
  11062. return 'BumpMapNode';
  11063. }
  11064. /**
  11065. * Constructs a new bump map node.
  11066. *
  11067. * @param {Node<float>} textureNode - Represents the bump map data.
  11068. * @param {?Node<float>} [scaleNode=null] - Controls the intensity of the bump effect.
  11069. */
  11070. constructor( textureNode, scaleNode = null ) {
  11071. super( 'vec3' );
  11072. /**
  11073. * Represents the bump map data.
  11074. *
  11075. * @type {Node<float>}
  11076. */
  11077. this.textureNode = textureNode;
  11078. /**
  11079. * Controls the intensity of the bump effect.
  11080. *
  11081. * @type {?Node<float>}
  11082. * @default null
  11083. */
  11084. this.scaleNode = scaleNode;
  11085. }
  11086. setup() {
  11087. const bumpScale = this.scaleNode !== null ? this.scaleNode : 1;
  11088. const dHdxy = dHdxy_fwd( { textureNode: this.textureNode, bumpScale } );
  11089. return perturbNormalArb( {
  11090. surf_pos: positionView,
  11091. surf_norm: normalView,
  11092. dHdxy
  11093. } );
  11094. }
  11095. }
  11096. /**
  11097. * TSL function for creating a bump map node.
  11098. *
  11099. * @tsl
  11100. * @function
  11101. * @param {Node<float>} textureNode - Represents the bump map data.
  11102. * @param {?Node<float>} [scaleNode=null] - Controls the intensity of the bump effect.
  11103. * @returns {BumpMapNode}
  11104. */
  11105. const bumpMap = /*@__PURE__*/ nodeProxy( BumpMapNode ).setParameterLength( 1, 2 );
  11106. const _propertyCache = new Map();
  11107. /**
  11108. * This class should simplify the node access to material properties.
  11109. * It internal uses reference nodes to make sure changes to material
  11110. * properties are automatically reflected to predefined TSL objects
  11111. * like e.g. `materialColor`.
  11112. *
  11113. * @augments Node
  11114. */
  11115. class MaterialNode extends Node {
  11116. static get type() {
  11117. return 'MaterialNode';
  11118. }
  11119. /**
  11120. * Constructs a new material node.
  11121. *
  11122. * @param {string} scope - The scope defines what kind of material property is referred by the node.
  11123. */
  11124. constructor( scope ) {
  11125. super();
  11126. /**
  11127. * The scope defines what material property is referred by the node.
  11128. *
  11129. * @type {string}
  11130. */
  11131. this.scope = scope;
  11132. }
  11133. /**
  11134. * Returns a cached reference node for the given property and type.
  11135. *
  11136. * @param {string} property - The name of the material property.
  11137. * @param {string} type - The uniform type of the property.
  11138. * @return {MaterialReferenceNode} A material reference node representing the property access.
  11139. */
  11140. getCache( property, type ) {
  11141. let node = _propertyCache.get( property );
  11142. if ( node === undefined ) {
  11143. node = materialReference( property, type );
  11144. _propertyCache.set( property, node );
  11145. }
  11146. return node;
  11147. }
  11148. /**
  11149. * Returns a float-typed material reference node for the given property name.
  11150. *
  11151. * @param {string} property - The name of the material property.
  11152. * @return {MaterialReferenceNode<float>} A material reference node representing the property access.
  11153. */
  11154. getFloat( property ) {
  11155. return this.getCache( property, 'float' );
  11156. }
  11157. /**
  11158. * Returns a color-typed material reference node for the given property name.
  11159. *
  11160. * @param {string} property - The name of the material property.
  11161. * @return {MaterialReferenceNode<color>} A material reference node representing the property access.
  11162. */
  11163. getColor( property ) {
  11164. return this.getCache( property, 'color' );
  11165. }
  11166. /**
  11167. * Returns a texture-typed material reference node for the given property name.
  11168. *
  11169. * @param {string} property - The name of the material property.
  11170. * @return {MaterialReferenceNode} A material reference node representing the property access.
  11171. */
  11172. getTexture( property ) {
  11173. return this.getCache( property === 'map' ? 'map' : property + 'Map', 'texture' );
  11174. }
  11175. /**
  11176. * The node setup is done depending on the selected scope. Multiple material properties
  11177. * might be grouped into a single node composition if they logically belong together.
  11178. *
  11179. * @param {NodeBuilder} builder - The current node builder.
  11180. * @return {Node} The node representing the selected scope.
  11181. */
  11182. setup( builder ) {
  11183. const material = builder.context.material;
  11184. const scope = this.scope;
  11185. let node = null;
  11186. if ( scope === MaterialNode.COLOR ) {
  11187. const colorNode = material.color !== undefined ? this.getColor( scope ) : vec3();
  11188. if ( material.map && material.map.isTexture === true ) {
  11189. node = colorNode.mul( this.getTexture( 'map' ) );
  11190. } else {
  11191. node = colorNode;
  11192. }
  11193. } else if ( scope === MaterialNode.OPACITY ) {
  11194. const opacityNode = this.getFloat( scope );
  11195. if ( material.alphaMap && material.alphaMap.isTexture === true ) {
  11196. node = opacityNode.mul( this.getTexture( 'alpha' ) );
  11197. } else {
  11198. node = opacityNode;
  11199. }
  11200. } else if ( scope === MaterialNode.SPECULAR_STRENGTH ) {
  11201. if ( material.specularMap && material.specularMap.isTexture === true ) {
  11202. node = this.getTexture( 'specular' ).r;
  11203. } else {
  11204. node = float( 1 );
  11205. }
  11206. } else if ( scope === MaterialNode.SPECULAR_INTENSITY ) {
  11207. const specularIntensityNode = this.getFloat( scope );
  11208. if ( material.specularIntensityMap && material.specularIntensityMap.isTexture === true ) {
  11209. node = specularIntensityNode.mul( this.getTexture( scope ).a );
  11210. } else {
  11211. node = specularIntensityNode;
  11212. }
  11213. } else if ( scope === MaterialNode.SPECULAR_COLOR ) {
  11214. const specularColorNode = this.getColor( scope );
  11215. if ( material.specularColorMap && material.specularColorMap.isTexture === true ) {
  11216. node = specularColorNode.mul( this.getTexture( scope ).rgb );
  11217. } else {
  11218. node = specularColorNode;
  11219. }
  11220. } else if ( scope === MaterialNode.ROUGHNESS ) { // TODO: cleanup similar branches
  11221. const roughnessNode = this.getFloat( scope );
  11222. if ( material.roughnessMap && material.roughnessMap.isTexture === true ) {
  11223. node = roughnessNode.mul( this.getTexture( scope ).g );
  11224. } else {
  11225. node = roughnessNode;
  11226. }
  11227. } else if ( scope === MaterialNode.METALNESS ) {
  11228. const metalnessNode = this.getFloat( scope );
  11229. if ( material.metalnessMap && material.metalnessMap.isTexture === true ) {
  11230. node = metalnessNode.mul( this.getTexture( scope ).b );
  11231. } else {
  11232. node = metalnessNode;
  11233. }
  11234. } else if ( scope === MaterialNode.EMISSIVE ) {
  11235. const emissiveIntensityNode = this.getFloat( 'emissiveIntensity' );
  11236. const emissiveNode = this.getColor( scope ).mul( emissiveIntensityNode );
  11237. if ( material.emissiveMap && material.emissiveMap.isTexture === true ) {
  11238. node = emissiveNode.mul( this.getTexture( scope ) );
  11239. } else {
  11240. node = emissiveNode;
  11241. }
  11242. } else if ( scope === MaterialNode.NORMAL ) {
  11243. if ( material.normalMap ) {
  11244. node = normalMap( this.getTexture( 'normal' ), this.getCache( 'normalScale', 'vec2' ) );
  11245. node.normalMapType = material.normalMapType;
  11246. if ( material.normalMap.format == RGFormat || material.normalMap.format == RED_GREEN_RGTC2_Format || material.normalMap.format == RG11_EAC_Format ) {
  11247. node.unpackNormalMode = NormalRGPacking;
  11248. }
  11249. } else if ( material.bumpMap ) {
  11250. node = bumpMap( this.getTexture( 'bump' ).r, this.getFloat( 'bumpScale' ) );
  11251. } else {
  11252. node = normalView;
  11253. }
  11254. } else if ( scope === MaterialNode.CLEARCOAT ) {
  11255. const clearcoatNode = this.getFloat( scope );
  11256. if ( material.clearcoatMap && material.clearcoatMap.isTexture === true ) {
  11257. node = clearcoatNode.mul( this.getTexture( scope ).r );
  11258. } else {
  11259. node = clearcoatNode;
  11260. }
  11261. } else if ( scope === MaterialNode.CLEARCOAT_ROUGHNESS ) {
  11262. const clearcoatRoughnessNode = this.getFloat( scope );
  11263. if ( material.clearcoatRoughnessMap && material.clearcoatRoughnessMap.isTexture === true ) {
  11264. node = clearcoatRoughnessNode.mul( this.getTexture( scope ).r );
  11265. } else {
  11266. node = clearcoatRoughnessNode;
  11267. }
  11268. } else if ( scope === MaterialNode.CLEARCOAT_NORMAL ) {
  11269. if ( material.clearcoatNormalMap ) {
  11270. node = normalMap( this.getTexture( scope ), this.getCache( scope + 'Scale', 'vec2' ) );
  11271. } else {
  11272. node = normalView;
  11273. }
  11274. } else if ( scope === MaterialNode.SHEEN ) {
  11275. const sheenNode = this.getColor( 'sheenColor' ).mul( this.getFloat( 'sheen' ) ); // Move this mul() to CPU
  11276. if ( material.sheenColorMap && material.sheenColorMap.isTexture === true ) {
  11277. node = sheenNode.mul( this.getTexture( 'sheenColor' ).rgb );
  11278. } else {
  11279. node = sheenNode;
  11280. }
  11281. } else if ( scope === MaterialNode.SHEEN_ROUGHNESS ) {
  11282. const sheenRoughnessNode = this.getFloat( scope );
  11283. if ( material.sheenRoughnessMap && material.sheenRoughnessMap.isTexture === true ) {
  11284. node = sheenRoughnessNode.mul( this.getTexture( scope ).a );
  11285. } else {
  11286. node = sheenRoughnessNode;
  11287. }
  11288. node = node.clamp( 0.0001, 1.0 );
  11289. } else if ( scope === MaterialNode.ANISOTROPY ) {
  11290. if ( material.anisotropyMap && material.anisotropyMap.isTexture === true ) {
  11291. const anisotropyPolar = this.getTexture( scope );
  11292. const anisotropyMat = mat2( materialAnisotropyVector.x, materialAnisotropyVector.y, materialAnisotropyVector.y.negate(), materialAnisotropyVector.x );
  11293. node = anisotropyMat.mul( anisotropyPolar.rg.mul( 2.0 ).sub( vec2( 1.0 ) ).normalize().mul( anisotropyPolar.b ) );
  11294. } else {
  11295. node = materialAnisotropyVector;
  11296. }
  11297. } else if ( scope === MaterialNode.IRIDESCENCE_THICKNESS ) {
  11298. const iridescenceThicknessMaximum = reference( '1', 'float', material.iridescenceThicknessRange );
  11299. if ( material.iridescenceThicknessMap ) {
  11300. const iridescenceThicknessMinimum = reference( '0', 'float', material.iridescenceThicknessRange );
  11301. node = iridescenceThicknessMaximum.sub( iridescenceThicknessMinimum ).mul( this.getTexture( scope ).g ).add( iridescenceThicknessMinimum );
  11302. } else {
  11303. node = iridescenceThicknessMaximum;
  11304. }
  11305. } else if ( scope === MaterialNode.TRANSMISSION ) {
  11306. const transmissionNode = this.getFloat( scope );
  11307. if ( material.transmissionMap ) {
  11308. node = transmissionNode.mul( this.getTexture( scope ).r );
  11309. } else {
  11310. node = transmissionNode;
  11311. }
  11312. } else if ( scope === MaterialNode.THICKNESS ) {
  11313. const thicknessNode = this.getFloat( scope );
  11314. if ( material.thicknessMap ) {
  11315. node = thicknessNode.mul( this.getTexture( scope ).g );
  11316. } else {
  11317. node = thicknessNode;
  11318. }
  11319. } else if ( scope === MaterialNode.IOR ) {
  11320. node = this.getFloat( scope );
  11321. } else if ( scope === MaterialNode.LIGHT_MAP ) {
  11322. node = this.getTexture( scope ).rgb.mul( this.getFloat( 'lightMapIntensity' ) );
  11323. } else if ( scope === MaterialNode.AO ) {
  11324. node = this.getTexture( scope ).r.sub( 1.0 ).mul( this.getFloat( 'aoMapIntensity' ) ).add( 1.0 );
  11325. } else if ( scope === MaterialNode.LINE_DASH_OFFSET ) {
  11326. node = ( material.dashOffset ) ? this.getFloat( scope ) : float( 0 );
  11327. } else {
  11328. const outputType = this.getNodeType( builder );
  11329. node = this.getCache( scope, outputType );
  11330. }
  11331. return node;
  11332. }
  11333. }
  11334. MaterialNode.ALPHA_TEST = 'alphaTest';
  11335. MaterialNode.COLOR = 'color';
  11336. MaterialNode.OPACITY = 'opacity';
  11337. MaterialNode.SHININESS = 'shininess';
  11338. MaterialNode.SPECULAR = 'specular';
  11339. MaterialNode.SPECULAR_STRENGTH = 'specularStrength';
  11340. MaterialNode.SPECULAR_INTENSITY = 'specularIntensity';
  11341. MaterialNode.SPECULAR_COLOR = 'specularColor';
  11342. MaterialNode.REFLECTIVITY = 'reflectivity';
  11343. MaterialNode.ROUGHNESS = 'roughness';
  11344. MaterialNode.METALNESS = 'metalness';
  11345. MaterialNode.NORMAL = 'normal';
  11346. MaterialNode.CLEARCOAT = 'clearcoat';
  11347. MaterialNode.CLEARCOAT_ROUGHNESS = 'clearcoatRoughness';
  11348. MaterialNode.CLEARCOAT_NORMAL = 'clearcoatNormal';
  11349. MaterialNode.EMISSIVE = 'emissive';
  11350. MaterialNode.ROTATION = 'rotation';
  11351. MaterialNode.SHEEN = 'sheen';
  11352. MaterialNode.SHEEN_ROUGHNESS = 'sheenRoughness';
  11353. MaterialNode.ANISOTROPY = 'anisotropy';
  11354. MaterialNode.IRIDESCENCE = 'iridescence';
  11355. MaterialNode.IRIDESCENCE_IOR = 'iridescenceIOR';
  11356. MaterialNode.IRIDESCENCE_THICKNESS = 'iridescenceThickness';
  11357. MaterialNode.IOR = 'ior';
  11358. MaterialNode.TRANSMISSION = 'transmission';
  11359. MaterialNode.THICKNESS = 'thickness';
  11360. MaterialNode.ATTENUATION_DISTANCE = 'attenuationDistance';
  11361. MaterialNode.ATTENUATION_COLOR = 'attenuationColor';
  11362. MaterialNode.LINE_SCALE = 'scale';
  11363. MaterialNode.LINE_DASH_SIZE = 'dashSize';
  11364. MaterialNode.LINE_GAP_SIZE = 'gapSize';
  11365. MaterialNode.LINE_WIDTH = 'linewidth';
  11366. MaterialNode.LINE_DASH_OFFSET = 'dashOffset';
  11367. MaterialNode.POINT_SIZE = 'size';
  11368. MaterialNode.DISPERSION = 'dispersion';
  11369. MaterialNode.LIGHT_MAP = 'light';
  11370. MaterialNode.AO = 'ao';
  11371. /**
  11372. * TSL object that represents alpha test of the current material.
  11373. *
  11374. * @tsl
  11375. * @type {Node<float>}
  11376. */
  11377. const materialAlphaTest = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.ALPHA_TEST );
  11378. /**
  11379. * TSL object that represents the diffuse color of the current material.
  11380. * The value is composed via `color` * `map`.
  11381. *
  11382. * @tsl
  11383. * @type {Node<vec3>}
  11384. */
  11385. const materialColor = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.COLOR );
  11386. /**
  11387. * TSL object that represents the shininess of the current material.
  11388. *
  11389. * @tsl
  11390. * @type {Node<float>}
  11391. */
  11392. const materialShininess = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SHININESS );
  11393. /**
  11394. * TSL object that represents the emissive color of the current material.
  11395. * The value is composed via `emissive` * `emissiveIntensity` * `emissiveMap`.
  11396. *
  11397. * @tsl
  11398. * @type {Node<vec3>}
  11399. */
  11400. const materialEmissive = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.EMISSIVE );
  11401. /**
  11402. * TSL object that represents the opacity of the current material.
  11403. * The value is composed via `opacity` * `alphaMap`.
  11404. *
  11405. * @tsl
  11406. * @type {Node<float>}
  11407. */
  11408. const materialOpacity = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.OPACITY );
  11409. /**
  11410. * TSL object that represents the specular of the current material.
  11411. *
  11412. * @tsl
  11413. * @type {Node<vec3>}
  11414. */
  11415. const materialSpecular = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SPECULAR );
  11416. /**
  11417. * TSL object that represents the specular intensity of the current material.
  11418. * The value is composed via `specularIntensity` * `specularMap.a`.
  11419. *
  11420. * @tsl
  11421. * @type {Node<float>}
  11422. */
  11423. const materialSpecularIntensity = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SPECULAR_INTENSITY );
  11424. /**
  11425. * TSL object that represents the specular color of the current material.
  11426. * The value is composed via `specularColor` * `specularMap.rgb`.
  11427. *
  11428. * @tsl
  11429. * @type {Node<vec3>}
  11430. */
  11431. const materialSpecularColor = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SPECULAR_COLOR );
  11432. /**
  11433. * TSL object that represents the specular strength of the current material.
  11434. * The value is composed via `specularMap.r`.
  11435. *
  11436. * @tsl
  11437. * @type {Node<float>}
  11438. */
  11439. const materialSpecularStrength = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SPECULAR_STRENGTH );
  11440. /**
  11441. * TSL object that represents the reflectivity of the current material.
  11442. *
  11443. * @tsl
  11444. * @type {Node<float>}
  11445. */
  11446. const materialReflectivity = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.REFLECTIVITY );
  11447. /**
  11448. * TSL object that represents the roughness of the current material.
  11449. * The value is composed via `roughness` * `roughnessMap.g`.
  11450. *
  11451. * @tsl
  11452. * @type {Node<float>}
  11453. */
  11454. const materialRoughness = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.ROUGHNESS );
  11455. /**
  11456. * TSL object that represents the metalness of the current material.
  11457. * The value is composed via `metalness` * `metalnessMap.b`.
  11458. *
  11459. * @tsl
  11460. * @type {Node<float>}
  11461. */
  11462. const materialMetalness = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.METALNESS );
  11463. /**
  11464. * TSL object that represents the normal of the current material.
  11465. * The value will be either `normalMap` * `normalScale`, `bumpMap` * `bumpScale` or `normalView`.
  11466. *
  11467. * @tsl
  11468. * @type {Node<vec3>}
  11469. */
  11470. const materialNormal = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.NORMAL );
  11471. /**
  11472. * TSL object that represents the clearcoat of the current material.
  11473. * The value is composed via `clearcoat` * `clearcoatMap.r`
  11474. *
  11475. * @tsl
  11476. * @type {Node<float>}
  11477. */
  11478. const materialClearcoat = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.CLEARCOAT );
  11479. /**
  11480. * TSL object that represents the clearcoat roughness of the current material.
  11481. * The value is composed via `clearcoatRoughness` * `clearcoatRoughnessMap.r`.
  11482. *
  11483. * @tsl
  11484. * @type {Node<float>}
  11485. */
  11486. const materialClearcoatRoughness = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.CLEARCOAT_ROUGHNESS );
  11487. /**
  11488. * TSL object that represents the clearcoat normal of the current material.
  11489. * The value will be either `clearcoatNormalMap` or `normalView`.
  11490. *
  11491. * @tsl
  11492. * @type {Node<vec3>}
  11493. */
  11494. const materialClearcoatNormal = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.CLEARCOAT_NORMAL );
  11495. /**
  11496. * TSL object that represents the rotation of the current sprite material.
  11497. *
  11498. * @tsl
  11499. * @type {Node<float>}
  11500. */
  11501. const materialRotation = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.ROTATION );
  11502. /**
  11503. * TSL object that represents the sheen color of the current material.
  11504. * The value is composed via `sheen` * `sheenColor` * `sheenColorMap`.
  11505. *
  11506. * @tsl
  11507. * @type {Node<vec3>}
  11508. */
  11509. const materialSheen = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SHEEN );
  11510. /**
  11511. * TSL object that represents the sheen roughness of the current material.
  11512. * The value is composed via `sheenRoughness` * `sheenRoughnessMap.a`.
  11513. *
  11514. * @tsl
  11515. * @type {Node<float>}
  11516. */
  11517. const materialSheenRoughness = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SHEEN_ROUGHNESS );
  11518. /**
  11519. * TSL object that represents the anisotropy of the current material.
  11520. *
  11521. * @tsl
  11522. * @type {Node<vec2>}
  11523. */
  11524. const materialAnisotropy = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.ANISOTROPY );
  11525. /**
  11526. * TSL object that represents the iridescence of the current material.
  11527. *
  11528. * @tsl
  11529. * @type {Node<float>}
  11530. */
  11531. const materialIridescence = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.IRIDESCENCE );
  11532. /**
  11533. * TSL object that represents the iridescence IOR of the current material.
  11534. *
  11535. * @tsl
  11536. * @type {Node<float>}
  11537. */
  11538. const materialIridescenceIOR = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.IRIDESCENCE_IOR );
  11539. /**
  11540. * TSL object that represents the iridescence thickness of the current material.
  11541. *
  11542. * @tsl
  11543. * @type {Node<float>}
  11544. */
  11545. const materialIridescenceThickness = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.IRIDESCENCE_THICKNESS );
  11546. /**
  11547. * TSL object that represents the transmission of the current material.
  11548. * The value is composed via `transmission` * `transmissionMap.r`.
  11549. *
  11550. * @tsl
  11551. * @type {Node<float>}
  11552. */
  11553. const materialTransmission = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.TRANSMISSION );
  11554. /**
  11555. * TSL object that represents the thickness of the current material.
  11556. * The value is composed via `thickness` * `thicknessMap.g`.
  11557. *
  11558. * @tsl
  11559. * @type {Node<float>}
  11560. */
  11561. const materialThickness = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.THICKNESS );
  11562. /**
  11563. * TSL object that represents the IOR of the current material.
  11564. *
  11565. * @tsl
  11566. * @type {Node<float>}
  11567. */
  11568. const materialIOR = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.IOR );
  11569. /**
  11570. * TSL object that represents the attenuation distance of the current material.
  11571. *
  11572. * @tsl
  11573. * @type {Node<float>}
  11574. */
  11575. const materialAttenuationDistance = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.ATTENUATION_DISTANCE );
  11576. /**
  11577. * TSL object that represents the attenuation color of the current material.
  11578. *
  11579. * @tsl
  11580. * @type {Node<vec3>}
  11581. */
  11582. const materialAttenuationColor = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.ATTENUATION_COLOR );
  11583. /**
  11584. * TSL object that represents the scale of the current dashed line material.
  11585. *
  11586. * @tsl
  11587. * @type {Node<float>}
  11588. */
  11589. const materialLineScale = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.LINE_SCALE );
  11590. /**
  11591. * TSL object that represents the dash size of the current dashed line material.
  11592. *
  11593. * @tsl
  11594. * @type {Node<float>}
  11595. */
  11596. const materialLineDashSize = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.LINE_DASH_SIZE );
  11597. /**
  11598. * TSL object that represents the gap size of the current dashed line material.
  11599. *
  11600. * @tsl
  11601. * @type {Node<float>}
  11602. */
  11603. const materialLineGapSize = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.LINE_GAP_SIZE );
  11604. /**
  11605. * TSL object that represents the line width of the current line material.
  11606. *
  11607. * @tsl
  11608. * @type {Node<float>}
  11609. */
  11610. const materialLineWidth = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.LINE_WIDTH );
  11611. /**
  11612. * TSL object that represents the dash offset of the current line material.
  11613. *
  11614. * @tsl
  11615. * @type {Node<float>}
  11616. */
  11617. const materialLineDashOffset = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.LINE_DASH_OFFSET );
  11618. /**
  11619. * TSL object that represents the point size of the current points material.
  11620. *
  11621. * @tsl
  11622. * @type {Node<float>}
  11623. */
  11624. const materialPointSize = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.POINT_SIZE );
  11625. /**
  11626. * TSL object that represents the dispersion of the current material.
  11627. *
  11628. * @tsl
  11629. * @type {Node<float>}
  11630. */
  11631. const materialDispersion = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.DISPERSION );
  11632. /**
  11633. * TSL object that represents the light map of the current material.
  11634. * The value is composed via `lightMapIntensity` * `lightMap.rgb`.
  11635. *
  11636. * @tsl
  11637. * @type {Node<vec3>}
  11638. */
  11639. const materialLightMap = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.LIGHT_MAP );
  11640. /**
  11641. * TSL object that represents the ambient occlusion map of the current material.
  11642. * The value is composed via `aoMap.r` - 1 * `aoMapIntensity` + 1.
  11643. *
  11644. * @tsl
  11645. * @type {Node<float>}
  11646. */
  11647. const materialAO = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.AO );
  11648. /**
  11649. * TSL object that represents the anisotropy vector of the current material.
  11650. *
  11651. * @tsl
  11652. * @type {Node<vec2>}
  11653. */
  11654. const materialAnisotropyVector = /*@__PURE__*/ uniform( new Vector2() ).onReference( function ( frame ) {
  11655. return frame.material;
  11656. } ).onRenderUpdate( function ( { material } ) {
  11657. this.value.set( material.anisotropy * Math.cos( material.anisotropyRotation ), material.anisotropy * Math.sin( material.anisotropyRotation ) );
  11658. } );
  11659. /**
  11660. * TSL object that represents the position in clip space after the model-view-projection transform of the current rendered object.
  11661. *
  11662. * @tsl
  11663. * @type {VaryingNode<vec4>}
  11664. */
  11665. const modelViewProjection = /*@__PURE__*/ ( Fn( ( builder ) => {
  11666. return builder.context.setupModelViewProjection();
  11667. }, 'vec4' ).once() )().toVarying( 'v_modelViewProjection' );
  11668. /**
  11669. * This class enables element access on instances of {@link StorageBufferNode}.
  11670. * In most cases, it is indirectly used when accessing elements with the
  11671. * {@link StorageBufferNode#element} method.
  11672. *
  11673. * ```js
  11674. * const position = positionStorage.element( instanceIndex );
  11675. * ```
  11676. *
  11677. * @augments ArrayElementNode
  11678. */
  11679. class StorageArrayElementNode extends ArrayElementNode {
  11680. static get type() {
  11681. return 'StorageArrayElementNode';
  11682. }
  11683. /**
  11684. * Constructs storage buffer element node.
  11685. *
  11686. * @param {StorageBufferNode} storageBufferNode - The storage buffer node.
  11687. * @param {Node} indexNode - The index node that defines the element access.
  11688. */
  11689. constructor( storageBufferNode, indexNode ) {
  11690. super( storageBufferNode, indexNode );
  11691. /**
  11692. * This flag can be used for type testing.
  11693. *
  11694. * @type {boolean}
  11695. * @readonly
  11696. * @default true
  11697. */
  11698. this.isStorageArrayElementNode = true;
  11699. }
  11700. /**
  11701. * The storage buffer node.
  11702. *
  11703. * @param {Node} value
  11704. * @type {StorageBufferNode}
  11705. */
  11706. set storageBufferNode( value ) {
  11707. this.node = value;
  11708. }
  11709. get storageBufferNode() {
  11710. return this.node;
  11711. }
  11712. getMemberType( builder, name ) {
  11713. const structTypeNode = this.storageBufferNode.structTypeNode;
  11714. if ( structTypeNode ) {
  11715. return structTypeNode.getMemberType( builder, name );
  11716. }
  11717. return 'void';
  11718. }
  11719. setup( builder ) {
  11720. if ( builder.isAvailable( 'storageBuffer' ) === false ) {
  11721. if ( this.node.isPBO === true ) {
  11722. builder.setupPBO( this.node );
  11723. }
  11724. }
  11725. return super.setup( builder );
  11726. }
  11727. generate( builder, output ) {
  11728. let snippet;
  11729. const isAssignContext = builder.context.assign;
  11730. //
  11731. if ( builder.isAvailable( 'storageBuffer' ) === false ) {
  11732. if ( this.node.isPBO === true && isAssignContext !== true && ( this.node.value.isInstancedBufferAttribute || builder.shaderStage !== 'compute' ) ) {
  11733. snippet = builder.generatePBO( this );
  11734. } else {
  11735. snippet = this.node.build( builder );
  11736. }
  11737. } else {
  11738. snippet = super.generate( builder );
  11739. }
  11740. if ( isAssignContext !== true ) {
  11741. const type = this.getNodeType( builder );
  11742. snippet = builder.format( snippet, type, output );
  11743. }
  11744. return snippet;
  11745. }
  11746. }
  11747. /**
  11748. * TSL function for creating a storage element node.
  11749. *
  11750. * @tsl
  11751. * @function
  11752. * @param {StorageBufferNode} storageBufferNode - The storage buffer node.
  11753. * @param {Node} indexNode - The index node that defines the element access.
  11754. * @returns {StorageArrayElementNode}
  11755. */
  11756. const storageElement = /*@__PURE__*/ nodeProxy( StorageArrayElementNode ).setParameterLength( 2 );
  11757. /**
  11758. * This node is used in context of compute shaders and allows to define a
  11759. * storage buffer for data. A typical workflow is to create instances of
  11760. * this node with the convenience functions `attributeArray()` or `instancedArray()`,
  11761. * setup up a compute shader that writes into the buffers and then convert
  11762. * the storage buffers to attribute nodes for rendering.
  11763. *
  11764. * ```js
  11765. * const positionBuffer = instancedArray( particleCount, 'vec3' ); // the storage buffer node
  11766. *
  11767. * const computeInit = Fn( () => { // the compute shader
  11768. *
  11769. * const position = positionBuffer.element( instanceIndex );
  11770. *
  11771. * // compute position data
  11772. *
  11773. * position.x = 1;
  11774. * position.y = 1;
  11775. * position.z = 1;
  11776. *
  11777. * } )().compute( particleCount );
  11778. *
  11779. * const particleMaterial = new THREE.SpriteNodeMaterial();
  11780. * particleMaterial.positionNode = positionBuffer.toAttribute();
  11781. *
  11782. * renderer.computeAsync( computeInit );
  11783. *
  11784. * ```
  11785. *
  11786. * @augments BufferNode
  11787. */
  11788. class StorageBufferNode extends BufferNode {
  11789. static get type() {
  11790. return 'StorageBufferNode';
  11791. }
  11792. /**
  11793. * Constructs a new storage buffer node.
  11794. *
  11795. * @param {StorageBufferAttribute|StorageInstancedBufferAttribute|BufferAttribute} value - The buffer data.
  11796. * @param {?(string|Struct)} [bufferType=null] - The buffer type (e.g. `'vec3'`).
  11797. * @param {number} [bufferCount=0] - The buffer count.
  11798. */
  11799. constructor( value, bufferType = null, bufferCount = 0 ) {
  11800. let nodeType, structTypeNode = null;
  11801. if ( bufferType && bufferType.isStruct ) {
  11802. nodeType = 'struct';
  11803. structTypeNode = bufferType.layout;
  11804. if ( value.isStorageBufferAttribute || value.isStorageInstancedBufferAttribute ) {
  11805. bufferCount = value.count;
  11806. }
  11807. } else if ( bufferType === null && ( value.isStorageBufferAttribute || value.isStorageInstancedBufferAttribute ) ) {
  11808. nodeType = getTypeFromLength( value.itemSize );
  11809. bufferCount = value.count;
  11810. } else {
  11811. nodeType = bufferType;
  11812. }
  11813. super( value, nodeType, bufferCount );
  11814. /**
  11815. * This flag can be used for type testing.
  11816. *
  11817. * @type {boolean}
  11818. * @readonly
  11819. * @default true
  11820. */
  11821. this.isStorageBufferNode = true;
  11822. /**
  11823. * The buffer struct type.
  11824. *
  11825. * @type {?StructTypeNode}
  11826. * @default null
  11827. */
  11828. this.structTypeNode = structTypeNode;
  11829. /**
  11830. * The access type of the texture node.
  11831. *
  11832. * @type {string}
  11833. * @default 'readWrite'
  11834. */
  11835. this.access = NodeAccess.READ_WRITE;
  11836. /**
  11837. * Whether the node is atomic or not.
  11838. *
  11839. * @type {boolean}
  11840. * @default false
  11841. */
  11842. this.isAtomic = false;
  11843. /**
  11844. * Whether the node represents a PBO or not.
  11845. * Only relevant for WebGL.
  11846. *
  11847. * @type {boolean}
  11848. * @default false
  11849. */
  11850. this.isPBO = false;
  11851. /**
  11852. * A reference to the internal buffer attribute node.
  11853. *
  11854. * @private
  11855. * @type {?BufferAttributeNode}
  11856. * @default null
  11857. */
  11858. this._attribute = null;
  11859. /**
  11860. * A reference to the internal varying node.
  11861. *
  11862. * @private
  11863. * @type {?VaryingNode}
  11864. * @default null
  11865. */
  11866. this._varying = null;
  11867. /**
  11868. * `StorageBufferNode` sets this property to `true` by default.
  11869. *
  11870. * @type {boolean}
  11871. * @default true
  11872. */
  11873. this.global = true;
  11874. if ( value.isStorageBufferAttribute !== true && value.isStorageInstancedBufferAttribute !== true ) {
  11875. // TODO: Improve it, possibly adding a new property to the BufferAttribute to identify it as a storage buffer read-only attribute in Renderer
  11876. if ( value.isInstancedBufferAttribute ) value.isStorageInstancedBufferAttribute = true;
  11877. else value.isStorageBufferAttribute = true;
  11878. }
  11879. }
  11880. /**
  11881. * This method is overwritten since the buffer data might be shared
  11882. * and thus the hash should be shared as well.
  11883. *
  11884. * @param {NodeBuilder} builder - The current node builder.
  11885. * @return {string} The hash.
  11886. */
  11887. getHash( builder ) {
  11888. if ( this.bufferCount === 0 ) {
  11889. let bufferData = builder.globalCache.getData( this.value );
  11890. if ( bufferData === undefined ) {
  11891. bufferData = {
  11892. node: this
  11893. };
  11894. builder.globalCache.setData( this.value, bufferData );
  11895. }
  11896. return bufferData.node.uuid;
  11897. }
  11898. return this.uuid;
  11899. }
  11900. /**
  11901. * Overwrites the default implementation to return a fixed value `'indirectStorageBuffer'` or `'storageBuffer'`.
  11902. *
  11903. * @param {NodeBuilder} builder - The current node builder.
  11904. * @return {string} The input type.
  11905. */
  11906. getInputType( /*builder*/ ) {
  11907. return this.value.isIndirectStorageBufferAttribute ? 'indirectStorageBuffer' : 'storageBuffer';
  11908. }
  11909. /**
  11910. * Enables element access with the given index node.
  11911. *
  11912. * @param {IndexNode} indexNode - The index node.
  11913. * @return {StorageArrayElementNode} A node representing the element access.
  11914. */
  11915. element( indexNode ) {
  11916. return storageElement( this, indexNode );
  11917. }
  11918. /**
  11919. * Defines whether this node is a PBO or not. Only relevant for WebGL.
  11920. *
  11921. * @param {boolean} value - The value so set.
  11922. * @return {StorageBufferNode} A reference to this node.
  11923. */
  11924. setPBO( value ) {
  11925. this.isPBO = value;
  11926. return this;
  11927. }
  11928. /**
  11929. * Returns the `isPBO` value.
  11930. *
  11931. * @return {boolean} Whether the node represents a PBO or not.
  11932. */
  11933. getPBO() {
  11934. return this.isPBO;
  11935. }
  11936. /**
  11937. * Defines the node access.
  11938. *
  11939. * @param {string} value - The node access.
  11940. * @return {StorageBufferNode} A reference to this node.
  11941. */
  11942. setAccess( value ) {
  11943. this.access = value;
  11944. return this;
  11945. }
  11946. /**
  11947. * Convenience method for configuring a read-only node access.
  11948. *
  11949. * @return {StorageBufferNode} A reference to this node.
  11950. */
  11951. toReadOnly() {
  11952. return this.setAccess( NodeAccess.READ_ONLY );
  11953. }
  11954. /**
  11955. * Defines whether the node is atomic or not.
  11956. *
  11957. * @param {boolean} value - The atomic flag.
  11958. * @return {StorageBufferNode} A reference to this node.
  11959. */
  11960. setAtomic( value ) {
  11961. this.isAtomic = value;
  11962. return this;
  11963. }
  11964. /**
  11965. * Convenience method for making this node atomic.
  11966. *
  11967. * @return {StorageBufferNode} A reference to this node.
  11968. */
  11969. toAtomic() {
  11970. return this.setAtomic( true );
  11971. }
  11972. /**
  11973. * Returns attribute data for this storage buffer node.
  11974. *
  11975. * @return {{attribute: BufferAttributeNode, varying: VaryingNode}} The attribute data.
  11976. */
  11977. getAttributeData() {
  11978. if ( this._attribute === null ) {
  11979. this._attribute = bufferAttribute( this.value );
  11980. this._varying = varying( this._attribute );
  11981. }
  11982. return {
  11983. attribute: this._attribute,
  11984. varying: this._varying
  11985. };
  11986. }
  11987. /**
  11988. * This method is overwritten since the node type from the availability of storage buffers
  11989. * and the attribute data.
  11990. *
  11991. * @param {NodeBuilder} builder - The current node builder.
  11992. * @return {string} The node type.
  11993. */
  11994. getNodeType( builder ) {
  11995. if ( this.structTypeNode !== null ) {
  11996. return this.structTypeNode.getNodeType( builder );
  11997. }
  11998. if ( builder.isAvailable( 'storageBuffer' ) || builder.isAvailable( 'indirectStorageBuffer' ) ) {
  11999. return super.getNodeType( builder );
  12000. }
  12001. const { attribute } = this.getAttributeData();
  12002. return attribute.getNodeType( builder );
  12003. }
  12004. /**
  12005. * Returns the type of a member of the struct.
  12006. *
  12007. * @param {NodeBuilder} builder - The current node builder.
  12008. * @param {string} name - The name of the member.
  12009. * @return {string} The type of the member.
  12010. */
  12011. getMemberType( builder, name ) {
  12012. if ( this.structTypeNode !== null ) {
  12013. return this.structTypeNode.getMemberType( builder, name );
  12014. }
  12015. return 'void';
  12016. }
  12017. /**
  12018. * Generates the code snippet of the storage buffer node.
  12019. *
  12020. * @param {NodeBuilder} builder - The current node builder.
  12021. * @return {string} The generated code snippet.
  12022. */
  12023. generate( builder ) {
  12024. if ( this.structTypeNode !== null ) this.structTypeNode.build( builder );
  12025. if ( builder.isAvailable( 'storageBuffer' ) || builder.isAvailable( 'indirectStorageBuffer' ) ) {
  12026. return super.generate( builder );
  12027. }
  12028. const { attribute, varying } = this.getAttributeData();
  12029. const output = varying.build( builder );
  12030. builder.registerTransform( output, attribute );
  12031. return output;
  12032. }
  12033. }
  12034. /**
  12035. * TSL function for creating a storage buffer node.
  12036. *
  12037. * @tsl
  12038. * @function
  12039. * @param {StorageBufferAttribute|StorageInstancedBufferAttribute|BufferAttribute} value - The buffer data.
  12040. * @param {?(string|Struct)} [type=null] - The buffer type (e.g. `'vec3'`).
  12041. * @param {number} [count=0] - The buffer count.
  12042. * @returns {StorageBufferNode}
  12043. */
  12044. const storage = ( value, type = null, count = 0 ) => nodeObject( new StorageBufferNode( value, type, count ) );
  12045. /**
  12046. * @tsl
  12047. * @function
  12048. * @deprecated since r171. Use `storage().setPBO( true )` instead.
  12049. *
  12050. * @param {StorageBufferAttribute|StorageInstancedBufferAttribute|BufferAttribute} value - The buffer data.
  12051. * @param {?string} type - The buffer type (e.g. `'vec3'`).
  12052. * @param {number} count - The buffer count.
  12053. * @returns {StorageBufferNode}
  12054. */
  12055. const storageObject = ( value, type, count ) => { // @deprecated, r171
  12056. warn( 'TSL: "storageObject()" is deprecated. Use "storage().setPBO( true )" instead.' );
  12057. return storage( value, type, count ).setPBO( true );
  12058. };
  12059. /**
  12060. * This class represents shader indices of different types. The following predefined node
  12061. * objects cover frequent use cases:
  12062. *
  12063. * - `vertexIndex`: The index of a vertex within a mesh.
  12064. * - `instanceIndex`: The index of either a mesh instance or an invocation of a compute shader.
  12065. * - `drawIndex`: The index of a draw call.
  12066. * - `invocationLocalIndex`: The index of a compute invocation within the scope of a workgroup load.
  12067. * - `invocationSubgroupIndex`: The index of a compute invocation within the scope of a subgroup.
  12068. * - `subgroupIndex`: The index of a compute invocation's subgroup within its workgroup.
  12069. *
  12070. * @augments Node
  12071. */
  12072. class IndexNode extends Node {
  12073. static get type() {
  12074. return 'IndexNode';
  12075. }
  12076. /**
  12077. * Constructs a new index node.
  12078. *
  12079. * @param {('vertex'|'instance'|'subgroup'|'invocationLocal'|'invocationGlobal'|'invocationSubgroup'|'draw')} scope - The scope of the index node.
  12080. */
  12081. constructor( scope ) {
  12082. super( 'uint' );
  12083. /**
  12084. * The scope of the index node.
  12085. *
  12086. * @type {string}
  12087. */
  12088. this.scope = scope;
  12089. /**
  12090. * This flag can be used for type testing.
  12091. *
  12092. * @type {boolean}
  12093. * @readonly
  12094. * @default true
  12095. */
  12096. this.isIndexNode = true;
  12097. }
  12098. generate( builder ) {
  12099. const nodeType = this.getNodeType( builder );
  12100. const scope = this.scope;
  12101. let propertyName;
  12102. if ( scope === IndexNode.VERTEX ) {
  12103. propertyName = builder.getVertexIndex();
  12104. } else if ( scope === IndexNode.INSTANCE ) {
  12105. propertyName = builder.getInstanceIndex();
  12106. } else if ( scope === IndexNode.DRAW ) {
  12107. propertyName = builder.getDrawIndex();
  12108. } else if ( scope === IndexNode.INVOCATION_LOCAL ) {
  12109. propertyName = builder.getInvocationLocalIndex();
  12110. } else if ( scope === IndexNode.INVOCATION_SUBGROUP ) {
  12111. propertyName = builder.getInvocationSubgroupIndex();
  12112. } else if ( scope === IndexNode.SUBGROUP ) {
  12113. propertyName = builder.getSubgroupIndex();
  12114. } else {
  12115. throw new Error( 'THREE.IndexNode: Unknown scope: ' + scope );
  12116. }
  12117. let output;
  12118. if ( builder.shaderStage === 'vertex' || builder.shaderStage === 'compute' ) {
  12119. output = propertyName;
  12120. } else {
  12121. const nodeVarying = varying( this );
  12122. output = nodeVarying.build( builder, nodeType );
  12123. }
  12124. return output;
  12125. }
  12126. }
  12127. IndexNode.VERTEX = 'vertex';
  12128. IndexNode.INSTANCE = 'instance';
  12129. IndexNode.SUBGROUP = 'subgroup';
  12130. IndexNode.INVOCATION_LOCAL = 'invocationLocal';
  12131. IndexNode.INVOCATION_SUBGROUP = 'invocationSubgroup';
  12132. IndexNode.DRAW = 'draw';
  12133. /**
  12134. * TSL object that represents the index of a vertex within a mesh.
  12135. *
  12136. * @tsl
  12137. * @type {IndexNode}
  12138. */
  12139. const vertexIndex = /*@__PURE__*/ nodeImmutable( IndexNode, IndexNode.VERTEX );
  12140. /**
  12141. * TSL object that represents the index of either a mesh instance or an invocation of a compute shader.
  12142. *
  12143. * @tsl
  12144. * @type {IndexNode}
  12145. */
  12146. const instanceIndex = /*@__PURE__*/ nodeImmutable( IndexNode, IndexNode.INSTANCE );
  12147. /**
  12148. * TSL object that represents the index of the subgroup the current compute invocation belongs to.
  12149. *
  12150. * @tsl
  12151. * @type {IndexNode}
  12152. */
  12153. const subgroupIndex = /*@__PURE__*/ nodeImmutable( IndexNode, IndexNode.SUBGROUP );
  12154. /**
  12155. * TSL object that represents the index of a compute invocation within the scope of a subgroup.
  12156. *
  12157. * @tsl
  12158. * @type {IndexNode}
  12159. */
  12160. const invocationSubgroupIndex = /*@__PURE__*/ nodeImmutable( IndexNode, IndexNode.INVOCATION_SUBGROUP );
  12161. /**
  12162. * TSL object that represents the index of a compute invocation within the scope of a workgroup load.
  12163. *
  12164. * @tsl
  12165. * @type {IndexNode}
  12166. */
  12167. const invocationLocalIndex = /*@__PURE__*/ nodeImmutable( IndexNode, IndexNode.INVOCATION_LOCAL );
  12168. /**
  12169. * TSL object that represents the index of a draw call.
  12170. *
  12171. * @tsl
  12172. * @type {IndexNode}
  12173. */
  12174. const drawIndex = /*@__PURE__*/ nodeImmutable( IndexNode, IndexNode.DRAW );
  12175. /**
  12176. * This node implements the vertex shader logic which is required
  12177. * when rendering 3D objects via instancing. The code makes sure
  12178. * vertex positions, normals and colors can be modified via instanced
  12179. * data.
  12180. *
  12181. * @augments Node
  12182. */
  12183. class InstanceNode extends Node {
  12184. static get type() {
  12185. return 'InstanceNode';
  12186. }
  12187. /**
  12188. * Constructs a new instance node.
  12189. *
  12190. * @param {number} count - The number of instances.
  12191. * @param {InstancedBufferAttribute|StorageInstancedBufferAttribute} instanceMatrix - Instanced buffer attribute representing the instance transformations.
  12192. * @param {?InstancedBufferAttribute|StorageInstancedBufferAttribute} instanceColor - Instanced buffer attribute representing the instance colors.
  12193. */
  12194. constructor( count, instanceMatrix, instanceColor = null ) {
  12195. super( 'void' );
  12196. /**
  12197. * The number of instances.
  12198. *
  12199. * @type {number}
  12200. */
  12201. this.count = count;
  12202. /**
  12203. * Instanced buffer attribute representing the transformation of instances.
  12204. *
  12205. * @type {InstancedBufferAttribute}
  12206. */
  12207. this.instanceMatrix = instanceMatrix;
  12208. /**
  12209. * Instanced buffer attribute representing the color of instances.
  12210. *
  12211. * @type {InstancedBufferAttribute}
  12212. */
  12213. this.instanceColor = instanceColor;
  12214. /**
  12215. * The node that represents the instance matrix data.
  12216. *
  12217. * @type {?Node}
  12218. */
  12219. this.instanceMatrixNode = null;
  12220. /**
  12221. * The node that represents the instance color data.
  12222. *
  12223. * @type {?Node}
  12224. * @default null
  12225. */
  12226. this.instanceColorNode = null;
  12227. /**
  12228. * The update type is set to `frame` since an update
  12229. * of instanced buffer data must be checked per frame.
  12230. *
  12231. * @type {string}
  12232. * @default 'frame'
  12233. */
  12234. this.updateType = NodeUpdateType.FRAME;
  12235. /**
  12236. * A reference to a buffer that is used by `instanceMatrixNode`.
  12237. *
  12238. * @type {?InstancedInterleavedBuffer}
  12239. */
  12240. this.buffer = null;
  12241. /**
  12242. * A reference to a buffer that is used by `instanceColorNode`.
  12243. *
  12244. * @type {?InstancedBufferAttribute}
  12245. */
  12246. this.bufferColor = null;
  12247. }
  12248. /**
  12249. * Tracks whether the matrix data is provided via a storage buffer.
  12250. *
  12251. * @type {boolean}
  12252. */
  12253. get isStorageMatrix() {
  12254. const { instanceMatrix } = this;
  12255. return instanceMatrix && instanceMatrix.isStorageInstancedBufferAttribute === true;
  12256. }
  12257. /**
  12258. * Tracks whether the color data is provided via a storage buffer.
  12259. *
  12260. * @type {boolean}
  12261. */
  12262. get isStorageColor() {
  12263. const { instanceColor } = this;
  12264. return instanceColor && instanceColor.isStorageInstancedBufferAttribute === true;
  12265. }
  12266. /**
  12267. * Setups the internal buffers and nodes and assigns the transformed vertex data
  12268. * to predefined node variables for accumulation. That follows the same patterns
  12269. * like with morph and skinning nodes.
  12270. *
  12271. * @param {NodeBuilder} builder - The current node builder.
  12272. */
  12273. setup( builder ) {
  12274. const { instanceMatrix, instanceColor, isStorageMatrix, isStorageColor } = this;
  12275. const { count } = instanceMatrix;
  12276. let { instanceMatrixNode, instanceColorNode } = this;
  12277. if ( instanceMatrixNode === null ) {
  12278. if ( isStorageMatrix ) {
  12279. instanceMatrixNode = storage( instanceMatrix, 'mat4', Math.max( count, 1 ) ).element( instanceIndex );
  12280. } else {
  12281. // Both backends have ~64kb UBO limit; fallback to attributes above 1000 matrices.
  12282. if ( count <= 1000 ) {
  12283. instanceMatrixNode = buffer( instanceMatrix.array, 'mat4', Math.max( count, 1 ) ).element( instanceIndex );
  12284. } else {
  12285. const interleaved = new InstancedInterleavedBuffer( instanceMatrix.array, 16, 1 );
  12286. this.buffer = interleaved;
  12287. const bufferFn = instanceMatrix.usage === DynamicDrawUsage ? instancedDynamicBufferAttribute : instancedBufferAttribute;
  12288. const instanceBuffers = [
  12289. bufferFn( interleaved, 'vec4', 16, 0 ),
  12290. bufferFn( interleaved, 'vec4', 16, 4 ),
  12291. bufferFn( interleaved, 'vec4', 16, 8 ),
  12292. bufferFn( interleaved, 'vec4', 16, 12 )
  12293. ];
  12294. instanceMatrixNode = mat4( ...instanceBuffers );
  12295. }
  12296. }
  12297. this.instanceMatrixNode = instanceMatrixNode;
  12298. }
  12299. if ( instanceColor && instanceColorNode === null ) {
  12300. if ( isStorageColor ) {
  12301. instanceColorNode = storage( instanceColor, 'vec3', Math.max( instanceColor.count, 1 ) ).element( instanceIndex );
  12302. } else {
  12303. const bufferAttribute = new InstancedBufferAttribute( instanceColor.array, 3 );
  12304. const bufferFn = instanceColor.usage === DynamicDrawUsage ? instancedDynamicBufferAttribute : instancedBufferAttribute;
  12305. this.bufferColor = bufferAttribute;
  12306. instanceColorNode = vec3( bufferFn( bufferAttribute, 'vec3', 3, 0 ) );
  12307. }
  12308. this.instanceColorNode = instanceColorNode;
  12309. }
  12310. // POSITION
  12311. const instancePosition = instanceMatrixNode.mul( positionLocal ).xyz;
  12312. positionLocal.assign( instancePosition );
  12313. // NORMAL
  12314. if ( builder.hasGeometryAttribute( 'normal' ) ) {
  12315. const instanceNormal = transformNormal( normalLocal, instanceMatrixNode );
  12316. // ASSIGNS
  12317. normalLocal.assign( instanceNormal );
  12318. }
  12319. // COLOR
  12320. if ( this.instanceColorNode !== null ) {
  12321. varyingProperty( 'vec3', 'vInstanceColor' ).assign( this.instanceColorNode );
  12322. }
  12323. }
  12324. /**
  12325. * Checks if the internal buffers require an update.
  12326. *
  12327. * @param {NodeFrame} frame - The current node frame.
  12328. */
  12329. update( /*frame*/ ) {
  12330. if ( this.buffer !== null && this.isStorageMatrix !== true ) {
  12331. this.buffer.clearUpdateRanges();
  12332. this.buffer.updateRanges.push( ... this.instanceMatrix.updateRanges );
  12333. // update version if necessary
  12334. if ( this.instanceMatrix.usage !== DynamicDrawUsage && this.instanceMatrix.version !== this.buffer.version ) {
  12335. this.buffer.version = this.instanceMatrix.version;
  12336. }
  12337. }
  12338. if ( this.instanceColor && this.bufferColor !== null && this.isStorageColor !== true ) {
  12339. this.bufferColor.clearUpdateRanges();
  12340. this.bufferColor.updateRanges.push( ... this.instanceColor.updateRanges );
  12341. if ( this.instanceColor.usage !== DynamicDrawUsage && this.instanceColor.version !== this.bufferColor.version ) {
  12342. this.bufferColor.version = this.instanceColor.version;
  12343. }
  12344. }
  12345. }
  12346. }
  12347. /**
  12348. * TSL function for creating an instance node.
  12349. *
  12350. * @tsl
  12351. * @function
  12352. * @param {number} count - The number of instances.
  12353. * @param {InstancedBufferAttribute|StorageInstancedBufferAttribute} instanceMatrix - Instanced buffer attribute representing the instance transformations.
  12354. * @param {?InstancedBufferAttribute|StorageInstancedBufferAttribute} instanceColor - Instanced buffer attribute representing the instance colors.
  12355. * @returns {InstanceNode}
  12356. */
  12357. const instance = /*@__PURE__*/ nodeProxy( InstanceNode ).setParameterLength( 2, 3 );
  12358. /**
  12359. * This is a special version of `InstanceNode` which requires the usage of {@link InstancedMesh}.
  12360. * It allows an easier setup of the instance node.
  12361. *
  12362. * @augments InstanceNode
  12363. */
  12364. class InstancedMeshNode extends InstanceNode {
  12365. static get type() {
  12366. return 'InstancedMeshNode';
  12367. }
  12368. /**
  12369. * Constructs a new instanced mesh node.
  12370. *
  12371. * @param {InstancedMesh} instancedMesh - The instanced mesh.
  12372. */
  12373. constructor( instancedMesh ) {
  12374. const { count, instanceMatrix, instanceColor } = instancedMesh;
  12375. super( count, instanceMatrix, instanceColor );
  12376. /**
  12377. * A reference to the instanced mesh.
  12378. *
  12379. * @type {InstancedMesh}
  12380. */
  12381. this.instancedMesh = instancedMesh;
  12382. }
  12383. }
  12384. /**
  12385. * TSL function for creating an instanced mesh node.
  12386. *
  12387. * @tsl
  12388. * @function
  12389. * @param {InstancedMesh} instancedMesh - The instancedMesh.
  12390. * @returns {InstancedMeshNode}
  12391. */
  12392. const instancedMesh = /*@__PURE__*/ nodeProxy( InstancedMeshNode ).setParameterLength( 1 );
  12393. /**
  12394. * This node implements the vertex shader logic which is required
  12395. * when rendering 3D objects via batching. `BatchNode` must be used
  12396. * with instances of {@link BatchedMesh}.
  12397. *
  12398. * @augments Node
  12399. */
  12400. class BatchNode extends Node {
  12401. static get type() {
  12402. return 'BatchNode';
  12403. }
  12404. /**
  12405. * Constructs a new batch node.
  12406. *
  12407. * @param {BatchedMesh} batchMesh - A reference to batched mesh.
  12408. */
  12409. constructor( batchMesh ) {
  12410. super( 'void' );
  12411. /**
  12412. * A reference to batched mesh.
  12413. *
  12414. * @type {BatchedMesh}
  12415. */
  12416. this.batchMesh = batchMesh;
  12417. /**
  12418. * The batching index node.
  12419. *
  12420. * @type {?IndexNode}
  12421. * @default null
  12422. */
  12423. this.batchingIdNode = null;
  12424. }
  12425. /**
  12426. * Setups the internal buffers and nodes and assigns the transformed vertex data
  12427. * to predefined node variables for accumulation. That follows the same patterns
  12428. * like with morph and skinning nodes.
  12429. *
  12430. * @param {NodeBuilder} builder - The current node builder.
  12431. */
  12432. setup( builder ) {
  12433. if ( this.batchingIdNode === null ) {
  12434. if ( builder.getDrawIndex() === null ) {
  12435. this.batchingIdNode = instanceIndex;
  12436. } else {
  12437. this.batchingIdNode = drawIndex;
  12438. }
  12439. }
  12440. const getIndirectIndex = Fn( ( [ id ] ) => {
  12441. const size = int( textureSize( textureLoad( this.batchMesh._indirectTexture ), 0 ).x ).toConst();
  12442. const x = int( id ).mod( size ).toConst();
  12443. const y = int( id ).div( size ).toConst();
  12444. return textureLoad( this.batchMesh._indirectTexture, ivec2( x, y ) ).x;
  12445. } ).setLayout( {
  12446. name: 'getIndirectIndex',
  12447. type: 'uint',
  12448. inputs: [
  12449. { name: 'id', type: 'int' }
  12450. ]
  12451. } );
  12452. const indirectId = getIndirectIndex( int( this.batchingIdNode ) );
  12453. const matricesTexture = this.batchMesh._matricesTexture;
  12454. const size = int( textureSize( textureLoad( matricesTexture ), 0 ).x ).toConst();
  12455. const j = float( indirectId ).mul( 4 ).toInt().toConst();
  12456. const x = j.mod( size ).toConst();
  12457. const y = j.div( size ).toConst();
  12458. const batchingMatrix = mat4(
  12459. textureLoad( matricesTexture, ivec2( x, y ) ),
  12460. textureLoad( matricesTexture, ivec2( x.add( 1 ), y ) ),
  12461. textureLoad( matricesTexture, ivec2( x.add( 2 ), y ) ),
  12462. textureLoad( matricesTexture, ivec2( x.add( 3 ), y ) )
  12463. );
  12464. const colorsTexture = this.batchMesh._colorsTexture;
  12465. if ( colorsTexture !== null ) {
  12466. const getBatchingColor = Fn( ( [ id ] ) => {
  12467. const size = int( textureSize( textureLoad( colorsTexture ), 0 ).x ).toConst();
  12468. const j = id;
  12469. const x = j.mod( size ).toConst();
  12470. const y = j.div( size ).toConst();
  12471. return textureLoad( colorsTexture, ivec2( x, y ) ).rgb;
  12472. } ).setLayout( {
  12473. name: 'getBatchingColor',
  12474. type: 'vec3',
  12475. inputs: [
  12476. { name: 'id', type: 'int' }
  12477. ]
  12478. } );
  12479. const color = getBatchingColor( indirectId );
  12480. varyingProperty( 'vec3', 'vBatchColor' ).assign( color );
  12481. }
  12482. const bm = mat3( batchingMatrix );
  12483. positionLocal.assign( batchingMatrix.mul( positionLocal ) );
  12484. const transformedNormal = normalLocal.div( vec3( bm[ 0 ].dot( bm[ 0 ] ), bm[ 1 ].dot( bm[ 1 ] ), bm[ 2 ].dot( bm[ 2 ] ) ) );
  12485. const batchingNormal = bm.mul( transformedNormal ).xyz;
  12486. normalLocal.assign( batchingNormal );
  12487. if ( builder.hasGeometryAttribute( 'tangent' ) ) {
  12488. tangentLocal.mulAssign( bm );
  12489. }
  12490. }
  12491. }
  12492. /**
  12493. * TSL function for creating a batch node.
  12494. *
  12495. * @tsl
  12496. * @function
  12497. * @param {BatchedMesh} batchMesh - A reference to batched mesh.
  12498. * @returns {BatchNode}
  12499. */
  12500. const batch = /*@__PURE__*/ nodeProxy( BatchNode ).setParameterLength( 1 );
  12501. const _frameId = new WeakMap();
  12502. /**
  12503. * This node implements the vertex transformation shader logic which is required
  12504. * for skinning/skeletal animation.
  12505. *
  12506. * @augments Node
  12507. */
  12508. class SkinningNode extends Node {
  12509. static get type() {
  12510. return 'SkinningNode';
  12511. }
  12512. /**
  12513. * Constructs a new skinning node.
  12514. *
  12515. * @param {SkinnedMesh} skinnedMesh - The skinned mesh.
  12516. */
  12517. constructor( skinnedMesh ) {
  12518. super( 'void' );
  12519. /**
  12520. * The skinned mesh.
  12521. *
  12522. * @type {SkinnedMesh}
  12523. */
  12524. this.skinnedMesh = skinnedMesh;
  12525. /**
  12526. * The update type overwritten since skinning nodes are updated per object.
  12527. *
  12528. * @type {string}
  12529. */
  12530. this.updateType = NodeUpdateType.OBJECT;
  12531. //
  12532. /**
  12533. * The skin index attribute.
  12534. *
  12535. * @type {AttributeNode}
  12536. */
  12537. this.skinIndexNode = attribute( 'skinIndex', 'uvec4' );
  12538. /**
  12539. * The skin weight attribute.
  12540. *
  12541. * @type {AttributeNode}
  12542. */
  12543. this.skinWeightNode = attribute( 'skinWeight', 'vec4' );
  12544. /**
  12545. * The bind matrix node.
  12546. *
  12547. * @type {Node<mat4>}
  12548. */
  12549. this.bindMatrixNode = reference( 'bindMatrix', 'mat4' );
  12550. /**
  12551. * The bind matrix inverse node.
  12552. *
  12553. * @type {Node<mat4>}
  12554. */
  12555. this.bindMatrixInverseNode = reference( 'bindMatrixInverse', 'mat4' );
  12556. /**
  12557. * The bind matrices as a uniform buffer node.
  12558. *
  12559. * @type {Node}
  12560. */
  12561. this.boneMatricesNode = referenceBuffer( 'skeleton.boneMatrices', 'mat4', skinnedMesh.skeleton.bones.length );
  12562. /**
  12563. * The current vertex position in local space.
  12564. *
  12565. * @type {Node<vec3>}
  12566. */
  12567. this.positionNode = positionLocal;
  12568. /**
  12569. * The result of vertex position in local space.
  12570. *
  12571. * @type {Node<vec3>}
  12572. */
  12573. this.toPositionNode = positionLocal;
  12574. /**
  12575. * The previous bind matrices as a uniform buffer node.
  12576. * Required for computing motion vectors.
  12577. *
  12578. * @type {?Node}
  12579. * @default null
  12580. */
  12581. this.previousBoneMatricesNode = null;
  12582. }
  12583. /**
  12584. * Transforms the given vertex position via skinning.
  12585. *
  12586. * @param {Node} [boneMatrices=this.boneMatricesNode] - The bone matrices
  12587. * @param {Node<vec3>} [position=this.positionNode] - The vertex position in local space.
  12588. * @return {Node<vec3>} The transformed vertex position.
  12589. */
  12590. getSkinnedPosition( boneMatrices = this.boneMatricesNode, position = this.positionNode ) {
  12591. const { skinIndexNode, skinWeightNode, bindMatrixNode, bindMatrixInverseNode } = this;
  12592. const boneMatX = boneMatrices.element( skinIndexNode.x );
  12593. const boneMatY = boneMatrices.element( skinIndexNode.y );
  12594. const boneMatZ = boneMatrices.element( skinIndexNode.z );
  12595. const boneMatW = boneMatrices.element( skinIndexNode.w );
  12596. // POSITION
  12597. const skinVertex = bindMatrixNode.mul( position );
  12598. const skinned = add(
  12599. boneMatX.mul( skinWeightNode.x ).mul( skinVertex ),
  12600. boneMatY.mul( skinWeightNode.y ).mul( skinVertex ),
  12601. boneMatZ.mul( skinWeightNode.z ).mul( skinVertex ),
  12602. boneMatW.mul( skinWeightNode.w ).mul( skinVertex )
  12603. );
  12604. return bindMatrixInverseNode.mul( skinned ).xyz;
  12605. }
  12606. /**
  12607. * Transforms the given vertex normal via skinning.
  12608. *
  12609. * @param {Node} [boneMatrices=this.boneMatricesNode] - The bone matrices
  12610. * @param {Node<vec3>} [normal=normalLocal] - The vertex normal in local space.
  12611. * @return {Node<vec3>} The transformed vertex normal.
  12612. */
  12613. getSkinnedNormal( boneMatrices = this.boneMatricesNode, normal = normalLocal ) {
  12614. const { skinIndexNode, skinWeightNode, bindMatrixNode, bindMatrixInverseNode } = this;
  12615. const boneMatX = boneMatrices.element( skinIndexNode.x );
  12616. const boneMatY = boneMatrices.element( skinIndexNode.y );
  12617. const boneMatZ = boneMatrices.element( skinIndexNode.z );
  12618. const boneMatW = boneMatrices.element( skinIndexNode.w );
  12619. // NORMAL
  12620. let skinMatrix = add(
  12621. skinWeightNode.x.mul( boneMatX ),
  12622. skinWeightNode.y.mul( boneMatY ),
  12623. skinWeightNode.z.mul( boneMatZ ),
  12624. skinWeightNode.w.mul( boneMatW )
  12625. );
  12626. skinMatrix = bindMatrixInverseNode.mul( skinMatrix ).mul( bindMatrixNode );
  12627. return skinMatrix.transformDirection( normal ).xyz;
  12628. }
  12629. /**
  12630. * Computes the transformed/skinned vertex position of the previous frame.
  12631. *
  12632. * @param {NodeBuilder} builder - The current node builder.
  12633. * @return {Node<vec3>} The skinned position from the previous frame.
  12634. */
  12635. getPreviousSkinnedPosition( builder ) {
  12636. const skinnedMesh = builder.object;
  12637. if ( this.previousBoneMatricesNode === null ) {
  12638. skinnedMesh.skeleton.previousBoneMatrices = new Float32Array( skinnedMesh.skeleton.boneMatrices );
  12639. this.previousBoneMatricesNode = referenceBuffer( 'skeleton.previousBoneMatrices', 'mat4', skinnedMesh.skeleton.bones.length );
  12640. }
  12641. return this.getSkinnedPosition( this.previousBoneMatricesNode, positionPrevious );
  12642. }
  12643. /**
  12644. * Returns `true` if bone matrices from the previous frame are required. Relevant
  12645. * when computing motion vectors with {@link VelocityNode}.
  12646. *
  12647. * @param {NodeBuilder} builder - The current node builder.
  12648. * @return {boolean} Whether bone matrices from the previous frame are required or not.
  12649. */
  12650. needsPreviousBoneMatrices( builder ) {
  12651. const mrt = builder.renderer.getMRT();
  12652. return ( mrt && mrt.has( 'velocity' ) ) || getDataFromObject( builder.object ).useVelocity === true;
  12653. }
  12654. /**
  12655. * Setups the skinning node by assigning the transformed vertex data to predefined node variables.
  12656. *
  12657. * @param {NodeBuilder} builder - The current node builder.
  12658. * @return {Node<vec3>} The transformed vertex position.
  12659. */
  12660. setup( builder ) {
  12661. if ( this.needsPreviousBoneMatrices( builder ) ) {
  12662. positionPrevious.assign( this.getPreviousSkinnedPosition( builder ) );
  12663. }
  12664. const skinPosition = this.getSkinnedPosition();
  12665. if ( this.toPositionNode ) this.toPositionNode.assign( skinPosition );
  12666. //
  12667. if ( builder.hasGeometryAttribute( 'normal' ) ) {
  12668. const skinNormal = this.getSkinnedNormal();
  12669. normalLocal.assign( skinNormal );
  12670. if ( builder.hasGeometryAttribute( 'tangent' ) ) {
  12671. tangentLocal.assign( skinNormal );
  12672. }
  12673. }
  12674. return skinPosition;
  12675. }
  12676. /**
  12677. * Generates the code snippet of the skinning node.
  12678. *
  12679. * @param {NodeBuilder} builder - The current node builder.
  12680. * @param {string} output - The current output.
  12681. * @return {string} The generated code snippet.
  12682. */
  12683. generate( builder, output ) {
  12684. if ( output !== 'void' ) {
  12685. return super.generate( builder, output );
  12686. }
  12687. }
  12688. /**
  12689. * Updates the state of the skinned mesh by updating the skeleton once per frame.
  12690. *
  12691. * @param {NodeFrame} frame - The current node frame.
  12692. */
  12693. update( frame ) {
  12694. const skeleton = frame.object && frame.object.skeleton ? frame.object.skeleton : this.skinnedMesh.skeleton;
  12695. if ( _frameId.get( skeleton ) === frame.frameId ) return;
  12696. _frameId.set( skeleton, frame.frameId );
  12697. if ( this.previousBoneMatricesNode !== null ) {
  12698. if ( skeleton.previousBoneMatrices === null ) {
  12699. // cloned skeletons miss "previousBoneMatrices" in their first updated
  12700. skeleton.previousBoneMatrices = new Float32Array( skeleton.boneMatrices );
  12701. }
  12702. skeleton.previousBoneMatrices.set( skeleton.boneMatrices );
  12703. }
  12704. skeleton.update();
  12705. }
  12706. }
  12707. /**
  12708. * TSL function for creating a skinning node.
  12709. *
  12710. * @tsl
  12711. * @function
  12712. * @param {SkinnedMesh} skinnedMesh - The skinned mesh.
  12713. * @returns {SkinningNode}
  12714. */
  12715. const skinning = ( skinnedMesh ) => nodeObject( new SkinningNode( skinnedMesh ) );
  12716. /**
  12717. * TSL function for computing skinning.
  12718. *
  12719. * @tsl
  12720. * @function
  12721. * @param {SkinnedMesh} skinnedMesh - The skinned mesh.
  12722. * @param {Node<vec3>} [toPosition=null] - The target position.
  12723. * @returns {SkinningNode}
  12724. */
  12725. const computeSkinning = ( skinnedMesh, toPosition = null ) => {
  12726. const node = new SkinningNode( skinnedMesh );
  12727. node.positionNode = storage( new InstancedBufferAttribute( skinnedMesh.geometry.getAttribute( 'position' ).array, 3 ), 'vec3' ).setPBO( true ).toReadOnly().element( instanceIndex ).toVar();
  12728. node.skinIndexNode = storage( new InstancedBufferAttribute( new Uint32Array( skinnedMesh.geometry.getAttribute( 'skinIndex' ).array ), 4 ), 'uvec4' ).setPBO( true ).toReadOnly().element( instanceIndex ).toVar();
  12729. node.skinWeightNode = storage( new InstancedBufferAttribute( skinnedMesh.geometry.getAttribute( 'skinWeight' ).array, 4 ), 'vec4' ).setPBO( true ).toReadOnly().element( instanceIndex ).toVar();
  12730. node.bindMatrixNode = uniform( skinnedMesh.bindMatrix, 'mat4' );
  12731. node.bindMatrixInverseNode = uniform( skinnedMesh.bindMatrixInverse, 'mat4' );
  12732. node.boneMatricesNode = buffer( skinnedMesh.skeleton.boneMatrices, 'mat4', skinnedMesh.skeleton.bones.length );
  12733. node.toPositionNode = toPosition;
  12734. return nodeObject( node );
  12735. };
  12736. /**
  12737. * This module offers a variety of ways to implement loops in TSL. In it's basic form it's:
  12738. * ```js
  12739. * Loop( count, ( { i } ) => {
  12740. *
  12741. * } );
  12742. * ```
  12743. * However, it is also possible to define a start and end ranges, data types and loop conditions:
  12744. * ```js
  12745. * Loop( { start: int( 0 ), end: int( 10 ), type: 'int', condition: '<' }, ( { i } ) => {
  12746. *
  12747. * } );
  12748. *```
  12749. * Nested loops can be defined in a compacted form:
  12750. * ```js
  12751. * Loop( 10, 5, ( { i, j } ) => {
  12752. *
  12753. * } );
  12754. * ```
  12755. * Loops that should run backwards can be defined like so:
  12756. * ```js
  12757. * Loop( { start: 10 }, () => {} );
  12758. * ```
  12759. * It is possible to execute with boolean values, similar to the `while` syntax.
  12760. * ```js
  12761. * const value = float( 0 ).toVar();
  12762. *
  12763. * Loop( value.lessThan( 10 ), () => {
  12764. *
  12765. * value.addAssign( 1 );
  12766. *
  12767. * } );
  12768. * ```
  12769. * The module also provides `Break()` and `Continue()` TSL expression for loop control.
  12770. * @augments Node
  12771. */
  12772. class LoopNode extends Node {
  12773. static get type() {
  12774. return 'LoopNode';
  12775. }
  12776. /**
  12777. * Constructs a new loop node.
  12778. *
  12779. * @param {Array<any>} params - Depending on the loop type, array holds different parameterization values for the loop.
  12780. */
  12781. constructor( params = [] ) {
  12782. super( 'void' );
  12783. this.params = params;
  12784. }
  12785. /**
  12786. * Returns a loop variable name based on an index. The pattern is
  12787. * `0` = `i`, `1`= `j`, `2`= `k` and so on.
  12788. *
  12789. * @param {number} index - The index.
  12790. * @return {string} The loop variable name.
  12791. */
  12792. getVarName( index ) {
  12793. return String.fromCharCode( 'i'.charCodeAt( 0 ) + index );
  12794. }
  12795. /**
  12796. * Returns properties about this node.
  12797. *
  12798. * @param {NodeBuilder} builder - The current node builder.
  12799. * @return {Object} The node properties.
  12800. */
  12801. getProperties( builder ) {
  12802. const properties = builder.getNodeProperties( this );
  12803. if ( properties.stackNode !== undefined ) return properties;
  12804. //
  12805. const inputs = {};
  12806. for ( let i = 0, l = this.params.length - 1; i < l; i ++ ) {
  12807. const param = this.params[ i ];
  12808. const name = ( param.isNode !== true && param.name ) || this.getVarName( i );
  12809. const type = ( param.isNode !== true && param.type ) || 'int';
  12810. inputs[ name ] = expression( name, type );
  12811. }
  12812. const stack = builder.addStack();
  12813. const fnCall = this.params[ this.params.length - 1 ]( inputs );
  12814. properties.returnsNode = fnCall.context( { nodeLoop: fnCall } );
  12815. properties.stackNode = stack;
  12816. const baseParam = this.params[ 0 ];
  12817. if ( baseParam.isNode !== true && typeof baseParam.update === 'function' ) {
  12818. const fnUpdateCall = Fn( this.params[ 0 ].update )( inputs );
  12819. properties.updateNode = fnUpdateCall.context( { nodeLoop: fnUpdateCall } );
  12820. }
  12821. builder.removeStack();
  12822. return properties;
  12823. }
  12824. setup( builder ) {
  12825. // setup properties
  12826. this.getProperties( builder );
  12827. if ( builder.fnCall ) {
  12828. const shaderNodeData = builder.getDataFromNode( builder.fnCall.shaderNode );
  12829. shaderNodeData.hasLoop = true;
  12830. }
  12831. }
  12832. generate( builder ) {
  12833. const properties = this.getProperties( builder );
  12834. const params = this.params;
  12835. const stackNode = properties.stackNode;
  12836. for ( let i = 0, l = params.length - 1; i < l; i ++ ) {
  12837. const param = params[ i ];
  12838. let isWhile = false, start = null, end = null, name = null, type = null, condition = null, update = null;
  12839. if ( param.isNode ) {
  12840. if ( param.getNodeType( builder ) === 'bool' ) {
  12841. isWhile = true;
  12842. type = 'bool';
  12843. end = param.build( builder, type );
  12844. } else {
  12845. type = 'int';
  12846. name = this.getVarName( i );
  12847. start = '0';
  12848. end = param.build( builder, type );
  12849. condition = '<';
  12850. }
  12851. } else {
  12852. type = param.type || 'int';
  12853. name = param.name || this.getVarName( i );
  12854. start = param.start;
  12855. end = param.end;
  12856. condition = param.condition;
  12857. update = param.update;
  12858. if ( typeof start === 'number' ) start = builder.generateConst( type, start );
  12859. else if ( start && start.isNode ) start = start.build( builder, type );
  12860. if ( typeof end === 'number' ) end = builder.generateConst( type, end );
  12861. else if ( end && end.isNode ) end = end.build( builder, type );
  12862. if ( start !== undefined && end === undefined ) {
  12863. start = start + ' - 1';
  12864. end = '0';
  12865. condition = '>=';
  12866. } else if ( end !== undefined && start === undefined ) {
  12867. start = '0';
  12868. condition = '<';
  12869. }
  12870. if ( condition === undefined ) {
  12871. if ( Number( start ) > Number( end ) ) {
  12872. condition = '>=';
  12873. } else {
  12874. condition = '<';
  12875. }
  12876. }
  12877. }
  12878. let loopSnippet;
  12879. if ( isWhile ) {
  12880. loopSnippet = `while ( ${ end } )`;
  12881. } else {
  12882. const internalParam = { start, end};
  12883. //
  12884. const startSnippet = internalParam.start;
  12885. const endSnippet = internalParam.end;
  12886. let updateSnippet;
  12887. const deltaOperator = () => condition.includes( '<' ) ? '+=' : '-=';
  12888. if ( update !== undefined && update !== null ) {
  12889. switch ( typeof update ) {
  12890. case 'function':
  12891. const flow = builder.flowStagesNode( properties.updateNode, 'void' );
  12892. const snippet = flow.code.replace( /\t|;/g, '' );
  12893. updateSnippet = snippet;
  12894. break;
  12895. case 'number':
  12896. updateSnippet = name + ' ' + deltaOperator() + ' ' + builder.generateConst( type, update );
  12897. break;
  12898. case 'string':
  12899. updateSnippet = name + ' ' + update;
  12900. break;
  12901. default:
  12902. if ( update.isNode ) {
  12903. updateSnippet = name + ' ' + deltaOperator() + ' ' + update.build( builder );
  12904. } else {
  12905. error( 'TSL: \'Loop( { update: ... } )\' is not a function, string or number.' );
  12906. updateSnippet = 'break /* invalid update */';
  12907. }
  12908. }
  12909. } else {
  12910. if ( type === 'int' || type === 'uint' ) {
  12911. update = condition.includes( '<' ) ? '++' : '--';
  12912. } else {
  12913. update = deltaOperator() + ' 1.';
  12914. }
  12915. updateSnippet = name + ' ' + update;
  12916. }
  12917. const declarationSnippet = builder.getVar( type, name ) + ' = ' + startSnippet;
  12918. const conditionalSnippet = name + ' ' + condition + ' ' + endSnippet;
  12919. loopSnippet = `for ( ${ declarationSnippet }; ${ conditionalSnippet }; ${ updateSnippet } )`;
  12920. }
  12921. builder.addFlowCode( ( i === 0 ? '\n' : '' ) + builder.tab + loopSnippet + ' {\n\n' ).addFlowTab();
  12922. }
  12923. const stackSnippet = stackNode.build( builder, 'void' );
  12924. properties.returnsNode.build( builder, 'void' );
  12925. builder.removeFlowTab().addFlowCode( '\n' + builder.tab + stackSnippet );
  12926. for ( let i = 0, l = this.params.length - 1; i < l; i ++ ) {
  12927. builder.addFlowCode( ( i === 0 ? '' : builder.tab ) + '}\n\n' ).removeFlowTab();
  12928. }
  12929. builder.addFlowTab();
  12930. }
  12931. }
  12932. /**
  12933. * TSL function for creating a loop node.
  12934. *
  12935. * @tsl
  12936. * @function
  12937. * @param {...any} params - A list of parameters.
  12938. * @returns {LoopNode}
  12939. */
  12940. const Loop = ( ...params ) => new LoopNode( nodeArray( params, 'int' ) ).toStack();
  12941. /**
  12942. * TSL function for creating a `Continue()` expression.
  12943. *
  12944. * @tsl
  12945. * @function
  12946. * @returns {ExpressionNode}
  12947. */
  12948. const Continue = () => expression( 'continue' ).toStack();
  12949. /**
  12950. * TSL function for creating a `Break()` expression.
  12951. *
  12952. * @tsl
  12953. * @function
  12954. * @returns {ExpressionNode}
  12955. */
  12956. const Break = () => expression( 'break' ).toStack();
  12957. const _morphTextures = /*@__PURE__*/ new WeakMap();
  12958. const _morphVec4 = /*@__PURE__*/ new Vector4();
  12959. const getMorph = /*@__PURE__*/ Fn( ( { bufferMap, influence, stride, width, depth, offset } ) => {
  12960. const texelIndex = int( vertexIndex ).mul( stride ).add( offset );
  12961. const y = texelIndex.div( width );
  12962. const x = texelIndex.sub( y.mul( width ) );
  12963. const bufferAttrib = textureLoad( bufferMap, ivec2( x, y ) ).depth( depth ).xyz;
  12964. return bufferAttrib.mul( influence );
  12965. } );
  12966. function getEntry( geometry ) {
  12967. const hasMorphPosition = geometry.morphAttributes.position !== undefined;
  12968. const hasMorphNormals = geometry.morphAttributes.normal !== undefined;
  12969. const hasMorphColors = geometry.morphAttributes.color !== undefined;
  12970. // instead of using attributes, the WebGL 2 code path encodes morph targets
  12971. // into an array of data textures. Each layer represents a single morph target.
  12972. const morphAttribute = geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color;
  12973. const morphTargetsCount = ( morphAttribute !== undefined ) ? morphAttribute.length : 0;
  12974. let entry = _morphTextures.get( geometry );
  12975. if ( entry === undefined || entry.count !== morphTargetsCount ) {
  12976. if ( entry !== undefined ) entry.texture.dispose();
  12977. const morphTargets = geometry.morphAttributes.position || [];
  12978. const morphNormals = geometry.morphAttributes.normal || [];
  12979. const morphColors = geometry.morphAttributes.color || [];
  12980. let vertexDataCount = 0;
  12981. if ( hasMorphPosition === true ) vertexDataCount = 1;
  12982. if ( hasMorphNormals === true ) vertexDataCount = 2;
  12983. if ( hasMorphColors === true ) vertexDataCount = 3;
  12984. let width = geometry.attributes.position.count * vertexDataCount;
  12985. let height = 1;
  12986. const maxTextureSize = 4096; // @TODO: Use 'capabilities.maxTextureSize'
  12987. if ( width > maxTextureSize ) {
  12988. height = Math.ceil( width / maxTextureSize );
  12989. width = maxTextureSize;
  12990. }
  12991. const buffer = new Float32Array( width * height * 4 * morphTargetsCount );
  12992. const bufferTexture = new DataArrayTexture( buffer, width, height, morphTargetsCount );
  12993. bufferTexture.type = FloatType;
  12994. bufferTexture.needsUpdate = true;
  12995. // fill buffer
  12996. const vertexDataStride = vertexDataCount * 4;
  12997. for ( let i = 0; i < morphTargetsCount; i ++ ) {
  12998. const morphTarget = morphTargets[ i ];
  12999. const morphNormal = morphNormals[ i ];
  13000. const morphColor = morphColors[ i ];
  13001. const offset = width * height * 4 * i;
  13002. for ( let j = 0; j < morphTarget.count; j ++ ) {
  13003. const stride = j * vertexDataStride;
  13004. if ( hasMorphPosition === true ) {
  13005. _morphVec4.fromBufferAttribute( morphTarget, j );
  13006. buffer[ offset + stride + 0 ] = _morphVec4.x;
  13007. buffer[ offset + stride + 1 ] = _morphVec4.y;
  13008. buffer[ offset + stride + 2 ] = _morphVec4.z;
  13009. buffer[ offset + stride + 3 ] = 0;
  13010. }
  13011. if ( hasMorphNormals === true ) {
  13012. _morphVec4.fromBufferAttribute( morphNormal, j );
  13013. buffer[ offset + stride + 4 ] = _morphVec4.x;
  13014. buffer[ offset + stride + 5 ] = _morphVec4.y;
  13015. buffer[ offset + stride + 6 ] = _morphVec4.z;
  13016. buffer[ offset + stride + 7 ] = 0;
  13017. }
  13018. if ( hasMorphColors === true ) {
  13019. _morphVec4.fromBufferAttribute( morphColor, j );
  13020. buffer[ offset + stride + 8 ] = _morphVec4.x;
  13021. buffer[ offset + stride + 9 ] = _morphVec4.y;
  13022. buffer[ offset + stride + 10 ] = _morphVec4.z;
  13023. buffer[ offset + stride + 11 ] = ( morphColor.itemSize === 4 ) ? _morphVec4.w : 1;
  13024. }
  13025. }
  13026. }
  13027. entry = {
  13028. count: morphTargetsCount,
  13029. texture: bufferTexture,
  13030. stride: vertexDataCount,
  13031. size: new Vector2( width, height )
  13032. };
  13033. _morphTextures.set( geometry, entry );
  13034. function disposeTexture() {
  13035. bufferTexture.dispose();
  13036. _morphTextures.delete( geometry );
  13037. geometry.removeEventListener( 'dispose', disposeTexture );
  13038. }
  13039. geometry.addEventListener( 'dispose', disposeTexture );
  13040. }
  13041. return entry;
  13042. }
  13043. /**
  13044. * This node implements the vertex transformation shader logic which is required
  13045. * for morph target animation.
  13046. *
  13047. * @augments Node
  13048. */
  13049. class MorphNode extends Node {
  13050. static get type() {
  13051. return 'MorphNode';
  13052. }
  13053. /**
  13054. * Constructs a new morph node.
  13055. *
  13056. * @param {Mesh} mesh - The mesh holding the morph targets.
  13057. */
  13058. constructor( mesh ) {
  13059. super( 'void' );
  13060. /**
  13061. * The mesh holding the morph targets.
  13062. *
  13063. * @type {Mesh}
  13064. */
  13065. this.mesh = mesh;
  13066. /**
  13067. * A uniform node which represents the morph base influence value.
  13068. *
  13069. * @type {UniformNode<float>}
  13070. */
  13071. this.morphBaseInfluence = uniform( 1 );
  13072. /**
  13073. * The update type overwritten since morph nodes are updated per object.
  13074. *
  13075. * @type {string}
  13076. */
  13077. this.updateType = NodeUpdateType.OBJECT;
  13078. }
  13079. /**
  13080. * Setups the morph node by assigning the transformed vertex data to predefined node variables.
  13081. *
  13082. * @param {NodeBuilder} builder - The current node builder.
  13083. */
  13084. setup( builder ) {
  13085. const { geometry } = builder;
  13086. const hasMorphPosition = geometry.morphAttributes.position !== undefined;
  13087. const hasMorphNormals = geometry.hasAttribute( 'normal' ) && geometry.morphAttributes.normal !== undefined;
  13088. const morphAttribute = geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color;
  13089. const morphTargetsCount = ( morphAttribute !== undefined ) ? morphAttribute.length : 0;
  13090. // nodes
  13091. const { texture: bufferMap, stride, size } = getEntry( geometry );
  13092. if ( hasMorphPosition === true ) positionLocal.mulAssign( this.morphBaseInfluence );
  13093. if ( hasMorphNormals === true ) normalLocal.mulAssign( this.morphBaseInfluence );
  13094. const width = int( size.width );
  13095. Loop( morphTargetsCount, ( { i } ) => {
  13096. const influence = float( 0 ).toVar();
  13097. if ( this.mesh.count > 1 && ( this.mesh.morphTexture !== null && this.mesh.morphTexture !== undefined ) ) {
  13098. influence.assign( textureLoad( this.mesh.morphTexture, ivec2( int( i ).add( 1 ), int( instanceIndex ) ) ).r );
  13099. } else {
  13100. influence.assign( reference( 'morphTargetInfluences', 'float' ).element( i ).toVar() );
  13101. }
  13102. If( influence.notEqual( 0 ), () => {
  13103. if ( hasMorphPosition === true ) {
  13104. positionLocal.addAssign( getMorph( {
  13105. bufferMap,
  13106. influence,
  13107. stride,
  13108. width,
  13109. depth: i,
  13110. offset: int( 0 )
  13111. } ) );
  13112. }
  13113. if ( hasMorphNormals === true ) {
  13114. normalLocal.addAssign( getMorph( {
  13115. bufferMap,
  13116. influence,
  13117. stride,
  13118. width,
  13119. depth: i,
  13120. offset: int( 1 )
  13121. } ) );
  13122. }
  13123. } );
  13124. } );
  13125. }
  13126. /**
  13127. * Updates the state of the morphed mesh by updating the base influence.
  13128. *
  13129. * @param {NodeFrame} frame - The current node frame.
  13130. */
  13131. update( /*frame*/ ) {
  13132. const morphBaseInfluence = this.morphBaseInfluence;
  13133. if ( this.mesh.geometry.morphTargetsRelative ) {
  13134. morphBaseInfluence.value = 1;
  13135. } else {
  13136. morphBaseInfluence.value = 1 - this.mesh.morphTargetInfluences.reduce( ( a, b ) => a + b, 0 );
  13137. }
  13138. }
  13139. }
  13140. /**
  13141. * TSL function for creating a morph node.
  13142. *
  13143. * @tsl
  13144. * @function
  13145. * @param {Mesh} mesh - The mesh holding the morph targets.
  13146. * @returns {MorphNode}
  13147. */
  13148. const morphReference = /*@__PURE__*/ nodeProxy( MorphNode ).setParameterLength( 1 );
  13149. /**
  13150. * Base class for lighting nodes.
  13151. *
  13152. * @augments Node
  13153. */
  13154. class LightingNode extends Node {
  13155. static get type() {
  13156. return 'LightingNode';
  13157. }
  13158. /**
  13159. * Constructs a new lighting node.
  13160. */
  13161. constructor() {
  13162. super( 'vec3' );
  13163. /**
  13164. * This flag can be used for type testing.
  13165. *
  13166. * @type {boolean}
  13167. * @readonly
  13168. * @default true
  13169. */
  13170. this.isLightingNode = true;
  13171. }
  13172. }
  13173. /**
  13174. * A generic class that can be used by nodes which contribute
  13175. * ambient occlusion to the scene. E.g. an ambient occlusion map
  13176. * node can be used as input for this module. Used in {@link NodeMaterial}.
  13177. *
  13178. * @augments LightingNode
  13179. */
  13180. class AONode extends LightingNode {
  13181. static get type() {
  13182. return 'AONode';
  13183. }
  13184. /**
  13185. * Constructs a new AO node.
  13186. *
  13187. * @param {?Node<float>} [aoNode=null] - The ambient occlusion node.
  13188. */
  13189. constructor( aoNode = null ) {
  13190. super();
  13191. /**
  13192. * The ambient occlusion node.
  13193. *
  13194. * @type {?Node<float>}
  13195. * @default null
  13196. */
  13197. this.aoNode = aoNode;
  13198. }
  13199. setup( builder ) {
  13200. builder.context.ambientOcclusion.mulAssign( this.aoNode );
  13201. }
  13202. }
  13203. /**
  13204. * `LightingContextNode` represents an extension of the {@link ContextNode} module
  13205. * by adding lighting specific context data. It represents the runtime context of
  13206. * {@link LightsNode}.
  13207. *
  13208. * @augments ContextNode
  13209. */
  13210. class LightingContextNode extends ContextNode {
  13211. static get type() {
  13212. return 'LightingContextNode';
  13213. }
  13214. /**
  13215. * Constructs a new lighting context node.
  13216. *
  13217. * @param {LightsNode} lightsNode - The lights node.
  13218. * @param {?LightingModel} [lightingModel=null] - The current lighting model.
  13219. * @param {?Node<vec3>} [backdropNode=null] - A backdrop node.
  13220. * @param {?Node<float>} [backdropAlphaNode=null] - A backdrop alpha node.
  13221. */
  13222. constructor( lightsNode, lightingModel = null, backdropNode = null, backdropAlphaNode = null ) {
  13223. super( lightsNode );
  13224. /**
  13225. * The current lighting model.
  13226. *
  13227. * @type {?LightingModel}
  13228. * @default null
  13229. */
  13230. this.lightingModel = lightingModel;
  13231. /**
  13232. * A backdrop node.
  13233. *
  13234. * @type {?Node<vec3>}
  13235. * @default null
  13236. */
  13237. this.backdropNode = backdropNode;
  13238. /**
  13239. * A backdrop alpha node.
  13240. *
  13241. * @type {?Node<float>}
  13242. * @default null
  13243. */
  13244. this.backdropAlphaNode = backdropAlphaNode;
  13245. this._value = null;
  13246. }
  13247. /**
  13248. * Returns a lighting context object.
  13249. *
  13250. * @return {{
  13251. * radiance: Node<vec3>,
  13252. * irradiance: Node<vec3>,
  13253. * iblIrradiance: Node<vec3>,
  13254. * ambientOcclusion: Node<float>,
  13255. * reflectedLight: {directDiffuse: Node<vec3>, directSpecular: Node<vec3>, indirectDiffuse: Node<vec3>, indirectSpecular: Node<vec3>},
  13256. * backdrop: Node<vec3>,
  13257. * backdropAlpha: Node<float>
  13258. * }} The lighting context object.
  13259. */
  13260. getContext() {
  13261. const { backdropNode, backdropAlphaNode } = this;
  13262. const directDiffuse = vec3().toVar( 'directDiffuse' ),
  13263. directSpecular = vec3().toVar( 'directSpecular' ),
  13264. indirectDiffuse = vec3().toVar( 'indirectDiffuse' ),
  13265. indirectSpecular = vec3().toVar( 'indirectSpecular' );
  13266. const reflectedLight = {
  13267. directDiffuse,
  13268. directSpecular,
  13269. indirectDiffuse,
  13270. indirectSpecular
  13271. };
  13272. const context = {
  13273. radiance: vec3().toVar( 'radiance' ),
  13274. irradiance: vec3().toVar( 'irradiance' ),
  13275. iblIrradiance: vec3().toVar( 'iblIrradiance' ),
  13276. ambientOcclusion: float( 1 ).toVar( 'ambientOcclusion' ),
  13277. reflectedLight,
  13278. backdrop: backdropNode,
  13279. backdropAlpha: backdropAlphaNode
  13280. };
  13281. return context;
  13282. }
  13283. setup( builder ) {
  13284. this.value = this._value || ( this._value = this.getContext() );
  13285. this.value.lightingModel = this.lightingModel || builder.context.lightingModel;
  13286. return super.setup( builder );
  13287. }
  13288. }
  13289. const lightingContext = /*@__PURE__*/ nodeProxy( LightingContextNode );
  13290. /**
  13291. * A generic class that can be used by nodes which contribute
  13292. * irradiance to the scene. E.g. a light map node can be used
  13293. * as input for this module. Used in {@link NodeMaterial}.
  13294. *
  13295. * @augments LightingNode
  13296. */
  13297. class IrradianceNode extends LightingNode {
  13298. static get type() {
  13299. return 'IrradianceNode';
  13300. }
  13301. /**
  13302. * Constructs a new irradiance node.
  13303. *
  13304. * @param {Node<vec3>} node - A node contributing irradiance.
  13305. */
  13306. constructor( node ) {
  13307. super();
  13308. /**
  13309. * A node contributing irradiance.
  13310. *
  13311. * @type {Node<vec3>}
  13312. */
  13313. this.node = node;
  13314. }
  13315. setup( builder ) {
  13316. builder.context.irradiance.addAssign( this.node );
  13317. }
  13318. }
  13319. const _size$5 = /*@__PURE__*/ new Vector2();
  13320. /**
  13321. * A special type of texture node which represents the data of the current viewport
  13322. * as a texture. The module extracts data from the current bound framebuffer with
  13323. * a copy operation so no extra render pass is required to produce the texture data
  13324. * (which is good for performance). `ViewportTextureNode` can be used as an input for a
  13325. * variety of effects like refractive or transmissive materials.
  13326. *
  13327. * @augments TextureNode
  13328. */
  13329. class ViewportTextureNode extends TextureNode {
  13330. static get type() {
  13331. return 'ViewportTextureNode';
  13332. }
  13333. /**
  13334. * Constructs a new viewport texture node.
  13335. *
  13336. * @param {Node} [uvNode=screenUV] - The uv node.
  13337. * @param {?Node} [levelNode=null] - The level node.
  13338. * @param {?Texture} [framebufferTexture=null] - A framebuffer texture holding the viewport data. If not provided, a framebuffer texture is created automatically.
  13339. */
  13340. constructor( uvNode = screenUV, levelNode = null, framebufferTexture = null ) {
  13341. let defaultFramebuffer = null;
  13342. if ( framebufferTexture === null ) {
  13343. defaultFramebuffer = new FramebufferTexture();
  13344. defaultFramebuffer.minFilter = LinearMipmapLinearFilter;
  13345. framebufferTexture = defaultFramebuffer;
  13346. } else {
  13347. defaultFramebuffer = framebufferTexture;
  13348. }
  13349. super( framebufferTexture, uvNode, levelNode );
  13350. /**
  13351. * Whether to generate mipmaps or not.
  13352. *
  13353. * @type {boolean}
  13354. * @default false
  13355. */
  13356. this.generateMipmaps = false;
  13357. /**
  13358. * The reference framebuffer texture. This is used to store the framebuffer texture
  13359. * for the current render target. If the render target changes, a new framebuffer texture
  13360. * is created automatically.
  13361. *
  13362. * @type {FramebufferTexture}
  13363. * @default null
  13364. */
  13365. this.defaultFramebuffer = defaultFramebuffer;
  13366. /**
  13367. * This flag can be used for type testing.
  13368. *
  13369. * @type {boolean}
  13370. * @readonly
  13371. * @default true
  13372. */
  13373. this.isOutputTextureNode = true;
  13374. /**
  13375. * The `updateBeforeType` is set to `NodeUpdateType.FRAME` since the node renders the
  13376. * scene once per frame in its {@link ViewportTextureNode#updateBefore} method.
  13377. *
  13378. * @type {string}
  13379. * @default 'frame'
  13380. */
  13381. this.updateBeforeType = NodeUpdateType.FRAME;
  13382. /**
  13383. * The framebuffer texture for the current renderer context.
  13384. *
  13385. * @type {WeakMap<RenderTarget, FramebufferTexture>}
  13386. * @private
  13387. */
  13388. this._cacheTextures = new WeakMap();
  13389. }
  13390. /**
  13391. * This methods returns a texture for the given render target reference.
  13392. *
  13393. * To avoid rendering errors, `ViewportTextureNode` must use unique framebuffer textures
  13394. * for different render contexts.
  13395. *
  13396. * @param {?RenderTarget} [reference=null] - The render target reference.
  13397. * @return {Texture} The framebuffer texture.
  13398. */
  13399. getTextureForReference( reference = null ) {
  13400. let defaultFramebuffer;
  13401. let cacheTextures;
  13402. if ( this.referenceNode ) {
  13403. defaultFramebuffer = this.referenceNode.defaultFramebuffer;
  13404. cacheTextures = this.referenceNode._cacheTextures;
  13405. } else {
  13406. defaultFramebuffer = this.defaultFramebuffer;
  13407. cacheTextures = this._cacheTextures;
  13408. }
  13409. if ( reference === null ) {
  13410. return defaultFramebuffer;
  13411. }
  13412. if ( cacheTextures.has( reference ) === false ) {
  13413. const framebufferTexture = defaultFramebuffer.clone();
  13414. cacheTextures.set( reference, framebufferTexture );
  13415. }
  13416. return cacheTextures.get( reference );
  13417. }
  13418. updateReference( frame ) {
  13419. const renderTarget = frame.renderer.getRenderTarget();
  13420. this.value = this.getTextureForReference( renderTarget );
  13421. return this.value;
  13422. }
  13423. updateBefore( frame ) {
  13424. const renderer = frame.renderer;
  13425. const renderTarget = renderer.getRenderTarget();
  13426. if ( renderTarget === null ) {
  13427. renderer.getDrawingBufferSize( _size$5 );
  13428. } else {
  13429. _size$5.set( renderTarget.width, renderTarget.height );
  13430. }
  13431. //
  13432. const framebufferTexture = this.getTextureForReference( renderTarget );
  13433. if ( framebufferTexture.image.width !== _size$5.width || framebufferTexture.image.height !== _size$5.height ) {
  13434. framebufferTexture.image.width = _size$5.width;
  13435. framebufferTexture.image.height = _size$5.height;
  13436. framebufferTexture.needsUpdate = true;
  13437. }
  13438. //
  13439. const currentGenerateMipmaps = framebufferTexture.generateMipmaps;
  13440. framebufferTexture.generateMipmaps = this.generateMipmaps;
  13441. renderer.copyFramebufferToTexture( framebufferTexture );
  13442. framebufferTexture.generateMipmaps = currentGenerateMipmaps;
  13443. }
  13444. clone() {
  13445. const viewportTextureNode = new this.constructor( this.uvNode, this.levelNode, this.value );
  13446. viewportTextureNode.generateMipmaps = this.generateMipmaps;
  13447. return viewportTextureNode;
  13448. }
  13449. }
  13450. /**
  13451. * TSL function for creating a viewport texture node.
  13452. *
  13453. * @tsl
  13454. * @function
  13455. * @param {?Node} [uvNode=screenUV] - The uv node.
  13456. * @param {?Node} [levelNode=null] - The level node.
  13457. * @param {?Texture} [framebufferTexture=null] - A framebuffer texture holding the viewport data. If not provided, a framebuffer texture is created automatically.
  13458. * @returns {ViewportTextureNode}
  13459. */
  13460. const viewportTexture = /*@__PURE__*/ nodeProxy( ViewportTextureNode ).setParameterLength( 0, 3 );
  13461. /**
  13462. * TSL function for creating a viewport texture node with enabled mipmap generation.
  13463. *
  13464. * @tsl
  13465. * @function
  13466. * @param {?Node} [uvNode=screenUV] - The uv node.
  13467. * @param {?Node} [levelNode=null] - The level node.
  13468. * @param {?Texture} [framebufferTexture=null] - A framebuffer texture holding the viewport data. If not provided, a framebuffer texture is created automatically.
  13469. * @returns {ViewportTextureNode}
  13470. */
  13471. const viewportMipTexture = /*@__PURE__*/ nodeProxy( ViewportTextureNode, null, null, { generateMipmaps: true } ).setParameterLength( 0, 3 );
  13472. let _sharedDepthbuffer = null;
  13473. /**
  13474. * Represents the depth of the current viewport as a texture. This module
  13475. * can be used in combination with viewport texture to achieve effects
  13476. * that require depth evaluation.
  13477. *
  13478. * @augments ViewportTextureNode
  13479. */
  13480. class ViewportDepthTextureNode extends ViewportTextureNode {
  13481. static get type() {
  13482. return 'ViewportDepthTextureNode';
  13483. }
  13484. /**
  13485. * Constructs a new viewport depth texture node.
  13486. *
  13487. * @param {Node} [uvNode=screenUV] - The uv node.
  13488. * @param {?Node} [levelNode=null] - The level node.
  13489. */
  13490. constructor( uvNode = screenUV, levelNode = null ) {
  13491. if ( _sharedDepthbuffer === null ) {
  13492. _sharedDepthbuffer = new DepthTexture();
  13493. }
  13494. super( uvNode, levelNode, _sharedDepthbuffer );
  13495. }
  13496. /**
  13497. * Overwritten so the method always returns the unique shared
  13498. * depth texture.
  13499. *
  13500. * @return {DepthTexture} The shared depth texture.
  13501. */
  13502. getTextureForReference() {
  13503. return _sharedDepthbuffer;
  13504. }
  13505. }
  13506. /**
  13507. * TSL function for a viewport depth texture node.
  13508. *
  13509. * @tsl
  13510. * @function
  13511. * @param {?Node} [uvNode=screenUV] - The uv node.
  13512. * @param {?Node} [levelNode=null] - The level node.
  13513. * @returns {ViewportDepthTextureNode}
  13514. */
  13515. const viewportDepthTexture = /*@__PURE__*/ nodeProxy( ViewportDepthTextureNode ).setParameterLength( 0, 2 );
  13516. /**
  13517. * This node offers a collection of features in context of the depth logic in the fragment shader.
  13518. * Depending on {@link ViewportDepthNode#scope}, it can be used to define a depth value for the current
  13519. * fragment or for depth evaluation purposes.
  13520. *
  13521. * @augments Node
  13522. */
  13523. class ViewportDepthNode extends Node {
  13524. static get type() {
  13525. return 'ViewportDepthNode';
  13526. }
  13527. /**
  13528. * Constructs a new viewport depth node.
  13529. *
  13530. * @param {('depth'|'depthBase'|'linearDepth')} scope - The node's scope.
  13531. * @param {?Node} [valueNode=null] - The value node.
  13532. */
  13533. constructor( scope, valueNode = null ) {
  13534. super( 'float' );
  13535. /**
  13536. * The node behaves differently depending on which scope is selected.
  13537. *
  13538. * - `ViewportDepthNode.DEPTH_BASE`: Allows to define a value for the current fragment's depth.
  13539. * - `ViewportDepthNode.DEPTH`: Represents the depth value for the current fragment (`valueNode` is ignored).
  13540. * - `ViewportDepthNode.LINEAR_DEPTH`: Represents the linear (orthographic) depth value of the current fragment.
  13541. * If a `valueNode` is set, the scope can be used to convert perspective depth data to linear data.
  13542. *
  13543. * @type {('depth'|'depthBase'|'linearDepth')}
  13544. */
  13545. this.scope = scope;
  13546. /**
  13547. * Can be used to define a custom depth value.
  13548. * The property is ignored in the `ViewportDepthNode.DEPTH` scope.
  13549. *
  13550. * @type {?Node}
  13551. * @default null
  13552. */
  13553. this.valueNode = valueNode;
  13554. /**
  13555. * This flag can be used for type testing.
  13556. *
  13557. * @type {boolean}
  13558. * @readonly
  13559. * @default true
  13560. */
  13561. this.isViewportDepthNode = true;
  13562. }
  13563. generate( builder ) {
  13564. const { scope } = this;
  13565. if ( scope === ViewportDepthNode.DEPTH_BASE ) {
  13566. return builder.getFragDepth();
  13567. }
  13568. return super.generate( builder );
  13569. }
  13570. setup( { camera } ) {
  13571. const { scope } = this;
  13572. const value = this.valueNode;
  13573. let node = null;
  13574. if ( scope === ViewportDepthNode.DEPTH_BASE ) {
  13575. if ( value !== null ) {
  13576. node = depthBase().assign( value );
  13577. }
  13578. } else if ( scope === ViewportDepthNode.DEPTH ) {
  13579. if ( camera.isPerspectiveCamera ) {
  13580. node = viewZToPerspectiveDepth( positionView.z, cameraNear, cameraFar );
  13581. } else {
  13582. node = viewZToOrthographicDepth( positionView.z, cameraNear, cameraFar );
  13583. }
  13584. } else if ( scope === ViewportDepthNode.LINEAR_DEPTH ) {
  13585. if ( value !== null ) {
  13586. if ( camera.isPerspectiveCamera ) {
  13587. const viewZ = perspectiveDepthToViewZ( value, cameraNear, cameraFar );
  13588. node = viewZToOrthographicDepth( viewZ, cameraNear, cameraFar );
  13589. } else {
  13590. node = value;
  13591. }
  13592. } else {
  13593. node = viewZToOrthographicDepth( positionView.z, cameraNear, cameraFar );
  13594. }
  13595. }
  13596. return node;
  13597. }
  13598. }
  13599. ViewportDepthNode.DEPTH_BASE = 'depthBase';
  13600. ViewportDepthNode.DEPTH = 'depth';
  13601. ViewportDepthNode.LINEAR_DEPTH = 'linearDepth';
  13602. // NOTE: viewZ, the z-coordinate in camera space, is negative for points in front of the camera
  13603. /**
  13604. * TSL function for converting a viewZ value to an orthographic depth value.
  13605. *
  13606. * @tsl
  13607. * @function
  13608. * @param {Node<float>} viewZ - The viewZ node.
  13609. * @param {Node<float>} near - The camera's near value.
  13610. * @param {Node<float>} far - The camera's far value.
  13611. * @returns {Node<float>}
  13612. */
  13613. const viewZToOrthographicDepth = ( viewZ, near, far ) => viewZ.add( near ).div( near.sub( far ) );
  13614. /**
  13615. * TSL function for converting an orthographic depth value to a viewZ value.
  13616. *
  13617. * @tsl
  13618. * @function
  13619. * @param {Node<float>} depth - The orthographic depth.
  13620. * @param {Node<float>} near - The camera's near value.
  13621. * @param {Node<float>} far - The camera's far value.
  13622. * @returns {Node<float>}
  13623. */
  13624. const orthographicDepthToViewZ = ( depth, near, far ) => near.sub( far ).mul( depth ).sub( near );
  13625. /**
  13626. * TSL function for converting a viewZ value to a perspective depth value.
  13627. *
  13628. * Note: {link https://twitter.com/gonnavis/status/1377183786949959682}.
  13629. *
  13630. * @tsl
  13631. * @function
  13632. * @param {Node<float>} viewZ - The viewZ node.
  13633. * @param {Node<float>} near - The camera's near value.
  13634. * @param {Node<float>} far - The camera's far value.
  13635. * @returns {Node<float>}
  13636. */
  13637. const viewZToPerspectiveDepth = ( viewZ, near, far ) => near.add( viewZ ).mul( far ).div( far.sub( near ).mul( viewZ ) );
  13638. /**
  13639. * TSL function for converting a perspective depth value to a viewZ value.
  13640. *
  13641. * @tsl
  13642. * @function
  13643. * @param {Node<float>} depth - The perspective depth.
  13644. * @param {Node<float>} near - The camera's near value.
  13645. * @param {Node<float>} far - The camera's far value.
  13646. * @returns {Node<float>}
  13647. */
  13648. const perspectiveDepthToViewZ = ( depth, near, far ) => near.mul( far ).div( far.sub( near ).mul( depth ).sub( far ) );
  13649. /**
  13650. * TSL function for converting a viewZ value to a logarithmic depth value.
  13651. *
  13652. * @tsl
  13653. * @function
  13654. * @param {Node<float>} viewZ - The viewZ node.
  13655. * @param {Node<float>} near - The camera's near value.
  13656. * @param {Node<float>} far - The camera's far value.
  13657. * @returns {Node<float>}
  13658. */
  13659. const viewZToLogarithmicDepth = ( viewZ, near, far ) => {
  13660. // NOTE: viewZ must be negative--see explanation at the end of this comment block.
  13661. // The final logarithmic depth formula used here is adapted from one described in an
  13662. // article by Thatcher Ulrich (see http://tulrich.com/geekstuff/log_depth_buffer.txt),
  13663. // which was an improvement upon an earlier formula one described in an
  13664. // Outerra article (https://outerra.blogspot.com/2009/08/logarithmic-z-buffer.html).
  13665. // Ulrich's formula is the following:
  13666. // z = K * log( w / cameraNear ) / log( cameraFar / cameraNear )
  13667. // where K = 2^k - 1, and k is the number of bits in the depth buffer.
  13668. // The Outerra variant ignored the camera near plane (it assumed it was 0) and instead
  13669. // opted for a "C-constant" for resolution adjustment of objects near the camera.
  13670. // Outerra states: "Notice that the 'C' variant doesn’t use a near plane distance, it has it
  13671. // set at 0" (quote from https://outerra.blogspot.com/2012/11/maximizing-depth-buffer-range-and.html).
  13672. // Ulrich's variant has the benefit of constant relative precision over the whole near-far range.
  13673. // It was debated here whether Outerra's "C-constant" or Ulrich's "near plane" variant should
  13674. // be used, and ultimately Ulrich's "near plane" version was chosen.
  13675. // Outerra eventually made another improvement to their original "C-constant" variant,
  13676. // but it still does not incorporate the camera near plane (for this version,
  13677. // see https://outerra.blogspot.com/2013/07/logarithmic-depth-buffer-optimizations.html).
  13678. // Here we make 4 changes to Ulrich's formula:
  13679. // 1. Clamp the camera near plane so we don't divide by 0.
  13680. // 2. Use log2 instead of log to avoid an extra multiply (shaders implement log using log2).
  13681. // 3. Assume K is 1 (K = maximum value in depth buffer; see Ulrich's formula above).
  13682. // 4. To maintain consistency with the functions "viewZToOrthographicDepth" and "viewZToPerspectiveDepth",
  13683. // we modify the formula here to use 'viewZ' instead of 'w'. The other functions expect a negative viewZ,
  13684. // so we do the same here, hence the 'viewZ.negate()' call.
  13685. // For visual representation of this depth curve, see https://www.desmos.com/calculator/uyqk0vex1u
  13686. near = near.max( 1e-6 ).toVar();
  13687. const numerator = log2( viewZ.negate().div( near ) );
  13688. const denominator = log2( far.div( near ) );
  13689. return numerator.div( denominator );
  13690. };
  13691. /**
  13692. * TSL function for converting a logarithmic depth value to a viewZ value.
  13693. *
  13694. * @tsl
  13695. * @function
  13696. * @param {Node<float>} depth - The logarithmic depth.
  13697. * @param {Node<float>} near - The camera's near value.
  13698. * @param {Node<float>} far - The camera's far value.
  13699. * @returns {Node<float>}
  13700. */
  13701. const logarithmicDepthToViewZ = ( depth, near, far ) => {
  13702. // NOTE: we add a 'negate()' call to the return value here to maintain consistency with
  13703. // the functions "orthographicDepthToViewZ" and "perspectiveDepthToViewZ" (they return
  13704. // a negative viewZ).
  13705. const exponent = depth.mul( log( far.div( near ) ) );
  13706. return float( Math.E ).pow( exponent ).mul( near ).negate();
  13707. };
  13708. /**
  13709. * TSL function for defining a value for the current fragment's depth.
  13710. *
  13711. * @tsl
  13712. * @function
  13713. * @param {Node<float>} value - The depth value to set.
  13714. * @returns {ViewportDepthNode<float>}
  13715. */
  13716. const depthBase = /*@__PURE__*/ nodeProxy( ViewportDepthNode, ViewportDepthNode.DEPTH_BASE );
  13717. /**
  13718. * TSL object that represents the depth value for the current fragment.
  13719. *
  13720. * @tsl
  13721. * @type {ViewportDepthNode}
  13722. */
  13723. const depth = /*@__PURE__*/ nodeImmutable( ViewportDepthNode, ViewportDepthNode.DEPTH );
  13724. /**
  13725. * TSL function for converting a perspective depth value to linear depth.
  13726. *
  13727. * @tsl
  13728. * @function
  13729. * @param {?Node<float>} [value=null] - The perspective depth. If `null` is provided, the current fragment's depth is used.
  13730. * @returns {ViewportDepthNode<float>}
  13731. */
  13732. const linearDepth = /*@__PURE__*/ nodeProxy( ViewportDepthNode, ViewportDepthNode.LINEAR_DEPTH ).setParameterLength( 0, 1 );
  13733. /**
  13734. * TSL object that represents the linear (orthographic) depth value of the current fragment
  13735. *
  13736. * @tsl
  13737. * @type {ViewportDepthNode}
  13738. */
  13739. const viewportLinearDepth = /*@__PURE__*/ linearDepth( viewportDepthTexture() );
  13740. depth.assign = ( value ) => depthBase( value );
  13741. /**
  13742. * This node is used in {@link NodeMaterial} to setup the clipping
  13743. * which can happen hardware-accelerated (if supported) and optionally
  13744. * use alpha-to-coverage for anti-aliasing clipped edges.
  13745. *
  13746. * @augments Node
  13747. */
  13748. class ClippingNode extends Node {
  13749. static get type() {
  13750. return 'ClippingNode';
  13751. }
  13752. /**
  13753. * Constructs a new clipping node.
  13754. *
  13755. * @param {('default'|'hardware'|'alphaToCoverage')} [scope='default'] - The node's scope. Similar to other nodes,
  13756. * the selected scope influences the behavior of the node and what type of code is generated.
  13757. */
  13758. constructor( scope = ClippingNode.DEFAULT ) {
  13759. super();
  13760. /**
  13761. * The node's scope. Similar to other nodes, the selected scope influences
  13762. * the behavior of the node and what type of code is generated.
  13763. *
  13764. * @type {('default'|'hardware'|'alphaToCoverage')}
  13765. */
  13766. this.scope = scope;
  13767. }
  13768. /**
  13769. * Setups the node depending on the selected scope.
  13770. *
  13771. * @param {NodeBuilder} builder - The current node builder.
  13772. * @return {Node} The result node.
  13773. */
  13774. setup( builder ) {
  13775. super.setup( builder );
  13776. const clippingContext = builder.clippingContext;
  13777. const { intersectionPlanes, unionPlanes } = clippingContext;
  13778. this.hardwareClipping = builder.material.hardwareClipping;
  13779. if ( this.scope === ClippingNode.ALPHA_TO_COVERAGE ) {
  13780. return this.setupAlphaToCoverage( intersectionPlanes, unionPlanes );
  13781. } else if ( this.scope === ClippingNode.HARDWARE ) {
  13782. return this.setupHardwareClipping( unionPlanes, builder );
  13783. } else {
  13784. return this.setupDefault( intersectionPlanes, unionPlanes );
  13785. }
  13786. }
  13787. /**
  13788. * Setups alpha to coverage.
  13789. *
  13790. * @param {Array<Vector4>} intersectionPlanes - The intersection planes.
  13791. * @param {Array<Vector4>} unionPlanes - The union planes.
  13792. * @return {Node} The result node.
  13793. */
  13794. setupAlphaToCoverage( intersectionPlanes, unionPlanes ) {
  13795. return Fn( () => {
  13796. const distanceToPlane = float().toVar( 'distanceToPlane' );
  13797. const distanceGradient = float().toVar( 'distanceToGradient' );
  13798. const clipOpacity = float( 1 ).toVar( 'clipOpacity' );
  13799. const numUnionPlanes = unionPlanes.length;
  13800. if ( this.hardwareClipping === false && numUnionPlanes > 0 ) {
  13801. const clippingPlanes = uniformArray( unionPlanes ).setGroup( renderGroup );
  13802. Loop( numUnionPlanes, ( { i } ) => {
  13803. const plane = clippingPlanes.element( i );
  13804. distanceToPlane.assign( positionView.dot( plane.xyz ).negate().add( plane.w ) );
  13805. distanceGradient.assign( distanceToPlane.fwidth().div( 2.0 ) );
  13806. clipOpacity.mulAssign( smoothstep( distanceGradient.negate(), distanceGradient, distanceToPlane ) );
  13807. } );
  13808. }
  13809. const numIntersectionPlanes = intersectionPlanes.length;
  13810. if ( numIntersectionPlanes > 0 ) {
  13811. const clippingPlanes = uniformArray( intersectionPlanes ).setGroup( renderGroup );
  13812. const intersectionClipOpacity = float( 1 ).toVar( 'intersectionClipOpacity' );
  13813. Loop( numIntersectionPlanes, ( { i } ) => {
  13814. const plane = clippingPlanes.element( i );
  13815. distanceToPlane.assign( positionView.dot( plane.xyz ).negate().add( plane.w ) );
  13816. distanceGradient.assign( distanceToPlane.fwidth().div( 2.0 ) );
  13817. intersectionClipOpacity.mulAssign( smoothstep( distanceGradient.negate(), distanceGradient, distanceToPlane ).oneMinus() );
  13818. } );
  13819. clipOpacity.mulAssign( intersectionClipOpacity.oneMinus() );
  13820. }
  13821. diffuseColor.a.mulAssign( clipOpacity );
  13822. diffuseColor.a.equal( 0.0 ).discard();
  13823. } )();
  13824. }
  13825. /**
  13826. * Setups the default clipping.
  13827. *
  13828. * @param {Array<Vector4>} intersectionPlanes - The intersection planes.
  13829. * @param {Array<Vector4>} unionPlanes - The union planes.
  13830. * @return {Node} The result node.
  13831. */
  13832. setupDefault( intersectionPlanes, unionPlanes ) {
  13833. return Fn( () => {
  13834. const numUnionPlanes = unionPlanes.length;
  13835. if ( this.hardwareClipping === false && numUnionPlanes > 0 ) {
  13836. const clippingPlanes = uniformArray( unionPlanes ).setGroup( renderGroup );
  13837. Loop( numUnionPlanes, ( { i } ) => {
  13838. const plane = clippingPlanes.element( i );
  13839. positionView.dot( plane.xyz ).greaterThan( plane.w ).discard();
  13840. } );
  13841. }
  13842. const numIntersectionPlanes = intersectionPlanes.length;
  13843. if ( numIntersectionPlanes > 0 ) {
  13844. const clippingPlanes = uniformArray( intersectionPlanes ).setGroup( renderGroup );
  13845. const clipped = bool( true ).toVar( 'clipped' );
  13846. Loop( numIntersectionPlanes, ( { i } ) => {
  13847. const plane = clippingPlanes.element( i );
  13848. clipped.assign( positionView.dot( plane.xyz ).greaterThan( plane.w ).and( clipped ) );
  13849. } );
  13850. clipped.discard();
  13851. }
  13852. } )();
  13853. }
  13854. /**
  13855. * Setups hardware clipping.
  13856. *
  13857. * @param {Array<Vector4>} unionPlanes - The union planes.
  13858. * @param {NodeBuilder} builder - The current node builder.
  13859. * @return {Node} The result node.
  13860. */
  13861. setupHardwareClipping( unionPlanes, builder ) {
  13862. const numUnionPlanes = unionPlanes.length;
  13863. builder.enableHardwareClipping( numUnionPlanes );
  13864. return Fn( () => {
  13865. const clippingPlanes = uniformArray( unionPlanes ).setGroup( renderGroup );
  13866. const hw_clip_distances = builtin( builder.getClipDistance() );
  13867. Loop( numUnionPlanes, ( { i } ) => {
  13868. const plane = clippingPlanes.element( i );
  13869. const distance = positionView.dot( plane.xyz ).sub( plane.w ).negate();
  13870. hw_clip_distances.element( i ).assign( distance );
  13871. } );
  13872. } )();
  13873. }
  13874. }
  13875. ClippingNode.ALPHA_TO_COVERAGE = 'alphaToCoverage';
  13876. ClippingNode.DEFAULT = 'default';
  13877. ClippingNode.HARDWARE = 'hardware';
  13878. /**
  13879. * TSL function for setting up the default clipping logic.
  13880. *
  13881. * @tsl
  13882. * @function
  13883. * @returns {ClippingNode}
  13884. */
  13885. const clipping = () => nodeObject( new ClippingNode() );
  13886. /**
  13887. * TSL function for setting up alpha to coverage.
  13888. *
  13889. * @tsl
  13890. * @function
  13891. * @returns {ClippingNode}
  13892. */
  13893. const clippingAlpha = () => nodeObject( new ClippingNode( ClippingNode.ALPHA_TO_COVERAGE ) );
  13894. /**
  13895. * TSL function for setting up hardware-based clipping.
  13896. *
  13897. * @tsl
  13898. * @function
  13899. * @returns {ClippingNode}
  13900. */
  13901. const hardwareClipping = () => nodeObject( new ClippingNode( ClippingNode.HARDWARE ) );
  13902. // See: https://casual-effects.com/research/Wyman2017Hashed/index.html
  13903. const ALPHA_HASH_SCALE = 0.05; // Derived from trials only, and may be changed.
  13904. const hash2D = /*@__PURE__*/ Fn( ( [ value ] ) => {
  13905. 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 ) ) ) ) ) );
  13906. } );
  13907. const hash3D = /*@__PURE__*/ Fn( ( [ value ] ) => {
  13908. return hash2D( vec2( hash2D( value.xy ), value.z ) );
  13909. } );
  13910. const getAlphaHashThreshold = /*@__PURE__*/ Fn( ( [ position ] ) => {
  13911. // Find the discretized derivatives of our coordinates
  13912. const maxDeriv = max$1(
  13913. length( dFdx( position.xyz ) ),
  13914. length( dFdy( position.xyz ) )
  13915. );
  13916. const pixScale = float( 1 ).div( float( ALPHA_HASH_SCALE ).mul( maxDeriv ) ).toVar( 'pixScale' );
  13917. // Find two nearest log-discretized noise scales
  13918. const pixScales = vec2(
  13919. exp2( floor( log2( pixScale ) ) ),
  13920. exp2( ceil( log2( pixScale ) ) )
  13921. );
  13922. // Compute alpha thresholds at our two noise scales
  13923. const alpha = vec2(
  13924. hash3D( floor( pixScales.x.mul( position.xyz ) ) ),
  13925. hash3D( floor( pixScales.y.mul( position.xyz ) ) ),
  13926. );
  13927. // Factor to interpolate lerp with
  13928. const lerpFactor = fract( log2( pixScale ) );
  13929. // Interpolate alpha threshold from noise at two scales
  13930. const x = add( mul( lerpFactor.oneMinus(), alpha.x ), mul( lerpFactor, alpha.y ) );
  13931. // Pass into CDF to compute uniformly distrib threshold
  13932. const a = min$1( lerpFactor, lerpFactor.oneMinus() );
  13933. const cases = vec3(
  13934. x.mul( x ).div( mul( 2.0, a ).mul( sub( 1.0, a ) ) ),
  13935. x.sub( mul( 0.5, a ) ).div( sub( 1.0, a ) ),
  13936. sub( 1.0, sub( 1.0, x ).mul( sub( 1.0, x ) ).div( mul( 2.0, a ).mul( sub( 1.0, a ) ) ) ) );
  13937. // Find our final, uniformly distributed alpha threshold (ατ)
  13938. const threshold = x.lessThan( a.oneMinus() ).select( x.lessThan( a ).select( cases.x, cases.y ), cases.z );
  13939. // Avoids ατ == 0. Could also do ατ =1-ατ
  13940. return clamp( threshold, 1.0e-6, 1.0 );
  13941. } ).setLayout( {
  13942. name: 'getAlphaHashThreshold',
  13943. type: 'float',
  13944. inputs: [
  13945. { name: 'position', type: 'vec3' }
  13946. ]
  13947. } );
  13948. /**
  13949. * An attribute node for representing vertex colors.
  13950. *
  13951. * @augments AttributeNode
  13952. */
  13953. class VertexColorNode extends AttributeNode {
  13954. static get type() {
  13955. return 'VertexColorNode';
  13956. }
  13957. /**
  13958. * Constructs a new vertex color node.
  13959. *
  13960. * @param {number} index - The attribute index.
  13961. */
  13962. constructor( index ) {
  13963. super( null, 'vec4' );
  13964. /**
  13965. * This flag can be used for type testing.
  13966. *
  13967. * @type {boolean}
  13968. * @readonly
  13969. * @default true
  13970. */
  13971. this.isVertexColorNode = true;
  13972. /**
  13973. * The attribute index to enable more than one sets of vertex colors.
  13974. *
  13975. * @type {number}
  13976. * @default 0
  13977. */
  13978. this.index = index;
  13979. }
  13980. /**
  13981. * Overwrites the default implementation by honoring the attribute index.
  13982. *
  13983. * @param {NodeBuilder} builder - The current node builder.
  13984. * @return {string} The attribute name.
  13985. */
  13986. getAttributeName( /*builder*/ ) {
  13987. const index = this.index;
  13988. return 'color' + ( index > 0 ? index : '' );
  13989. }
  13990. generate( builder ) {
  13991. const attributeName = this.getAttributeName( builder );
  13992. const geometryAttribute = builder.hasGeometryAttribute( attributeName );
  13993. let result;
  13994. if ( geometryAttribute === true ) {
  13995. result = super.generate( builder );
  13996. } else {
  13997. // Vertex color fallback should be white
  13998. result = builder.generateConst( this.nodeType, new Vector4( 1, 1, 1, 1 ) );
  13999. }
  14000. return result;
  14001. }
  14002. serialize( data ) {
  14003. super.serialize( data );
  14004. data.index = this.index;
  14005. }
  14006. deserialize( data ) {
  14007. super.deserialize( data );
  14008. this.index = data.index;
  14009. }
  14010. }
  14011. /**
  14012. * TSL function for creating a reference node.
  14013. *
  14014. * @tsl
  14015. * @function
  14016. * @param {number} [index=0] - The attribute index.
  14017. * @returns {VertexColorNode}
  14018. */
  14019. const vertexColor = ( index = 0 ) => nodeObject( new VertexColorNode( index ) );
  14020. /**
  14021. * Represents a "Color Burn" blend mode.
  14022. *
  14023. * It's designed to darken the base layer's colors based on the color of the blend layer.
  14024. * It significantly increases the contrast of the base layer, making the colors more vibrant and saturated.
  14025. * The darker the color in the blend layer, the stronger the darkening and contrast effect on the base layer.
  14026. *
  14027. * @tsl
  14028. * @function
  14029. * @param {Node<vec3>} base - The base color.
  14030. * @param {Node<vec3>} blend - The blend color. A white (#ffffff) blend color does not alter the base color.
  14031. * @return {Node<vec3>} The result.
  14032. */
  14033. const blendBurn = /*@__PURE__*/ Fn( ( [ base, blend ] ) => {
  14034. return min$1( 1.0, base.oneMinus().div( blend ) ).oneMinus();
  14035. } ).setLayout( {
  14036. name: 'blendBurn',
  14037. type: 'vec3',
  14038. inputs: [
  14039. { name: 'base', type: 'vec3' },
  14040. { name: 'blend', type: 'vec3' }
  14041. ]
  14042. } );
  14043. /**
  14044. * Represents a "Color Dodge" blend mode.
  14045. *
  14046. * It's designed to lighten the base layer's colors based on the color of the blend layer.
  14047. * It significantly increases the brightness of the base layer, making the colors lighter and more vibrant.
  14048. * The brighter the color in the blend layer, the stronger the lightening and contrast effect on the base layer.
  14049. *
  14050. * @tsl
  14051. * @function
  14052. * @param {Node<vec3>} base - The base color.
  14053. * @param {Node<vec3>} blend - The blend color. A black (#000000) blend color does not alter the base color.
  14054. * @return {Node<vec3>} The result.
  14055. */
  14056. const blendDodge = /*@__PURE__*/ Fn( ( [ base, blend ] ) => {
  14057. return min$1( base.div( blend.oneMinus() ), 1.0 );
  14058. } ).setLayout( {
  14059. name: 'blendDodge',
  14060. type: 'vec3',
  14061. inputs: [
  14062. { name: 'base', type: 'vec3' },
  14063. { name: 'blend', type: 'vec3' }
  14064. ]
  14065. } );
  14066. /**
  14067. * Represents a "Screen" blend mode.
  14068. *
  14069. * Similar to `blendDodge()`, this mode also lightens the base layer's colors based on the color of the blend layer.
  14070. * The "Screen" blend mode is better for general brightening whereas the "Dodge" results in more subtle and nuanced
  14071. * effects.
  14072. *
  14073. * @tsl
  14074. * @function
  14075. * @param {Node<vec3>} base - The base color.
  14076. * @param {Node<vec3>} blend - The blend color. A black (#000000) blend color does not alter the base color.
  14077. * @return {Node<vec3>} The result.
  14078. */
  14079. const blendScreen = /*@__PURE__*/ Fn( ( [ base, blend ] ) => {
  14080. return base.oneMinus().mul( blend.oneMinus() ).oneMinus();
  14081. } ).setLayout( {
  14082. name: 'blendScreen',
  14083. type: 'vec3',
  14084. inputs: [
  14085. { name: 'base', type: 'vec3' },
  14086. { name: 'blend', type: 'vec3' }
  14087. ]
  14088. } );
  14089. /**
  14090. * Represents a "Overlay" blend mode.
  14091. *
  14092. * It's designed to increase the contrast of the base layer based on the color of the blend layer.
  14093. * It amplifies the existing colors and contrast in the base layer, making lighter areas lighter and darker areas darker.
  14094. * The color of the blend layer significantly influences the resulting contrast and color shift in the base layer.
  14095. *
  14096. * @tsl
  14097. * @function
  14098. * @param {Node<vec3>} base - The base color.
  14099. * @param {Node<vec3>} blend - The blend color
  14100. * @return {Node<vec3>} The result.
  14101. */
  14102. const blendOverlay = /*@__PURE__*/ Fn( ( [ base, blend ] ) => {
  14103. return mix( base.mul( 2.0 ).mul( blend ), base.oneMinus().mul( 2.0 ).mul( blend.oneMinus() ).oneMinus(), step( 0.5, base ) );
  14104. } ).setLayout( {
  14105. name: 'blendOverlay',
  14106. type: 'vec3',
  14107. inputs: [
  14108. { name: 'base', type: 'vec3' },
  14109. { name: 'blend', type: 'vec3' }
  14110. ]
  14111. } );
  14112. /**
  14113. * This function blends two color based on their alpha values by replicating the behavior of `THREE.NormalBlending`.
  14114. * It assumes both input colors have non-premultiplied alpha.
  14115. *
  14116. * @tsl
  14117. * @function
  14118. * @param {Node<vec4>} base - The base color.
  14119. * @param {Node<vec4>} blend - The blend color
  14120. * @return {Node<vec4>} The result.
  14121. */
  14122. const blendColor = /*@__PURE__*/ Fn( ( [ base, blend ] ) => {
  14123. const outAlpha = blend.a.add( base.a.mul( blend.a.oneMinus() ) );
  14124. return vec4( blend.rgb.mul( blend.a ).add( base.rgb.mul( base.a ).mul( blend.a.oneMinus() ) ).div( outAlpha ), outAlpha );
  14125. } ).setLayout( {
  14126. name: 'blendColor',
  14127. type: 'vec4',
  14128. inputs: [
  14129. { name: 'base', type: 'vec4' },
  14130. { name: 'blend', type: 'vec4' }
  14131. ]
  14132. } );
  14133. /**
  14134. * Premultiplies the RGB channels of a color by its alpha channel.
  14135. *
  14136. * This function is useful for converting a non-premultiplied alpha color
  14137. * into a premultiplied alpha format, where the RGB values are scaled
  14138. * by the alpha value. Premultiplied alpha is often used in graphics
  14139. * rendering for certain operations, such as compositing and image processing.
  14140. *
  14141. * @tsl
  14142. * @function
  14143. * @param {Node<vec4>} color - The input color with non-premultiplied alpha.
  14144. * @return {Node<vec4>} The color with premultiplied alpha.
  14145. */
  14146. const premultiplyAlpha = /*@__PURE__*/ Fn( ( [ color ] ) => {
  14147. return vec4( color.rgb.mul( color.a ), color.a );
  14148. }, { color: 'vec4', return: 'vec4' } );
  14149. /**
  14150. * Unpremultiplies the RGB channels of a color by its alpha channel.
  14151. *
  14152. * This function is useful for converting a premultiplied alpha color
  14153. * back into a non-premultiplied alpha format, where the RGB values are
  14154. * divided by the alpha value. Unpremultiplied alpha is often used in graphics
  14155. * rendering for certain operations, such as compositing and image processing.
  14156. *
  14157. * @tsl
  14158. * @function
  14159. * @param {Node<vec4>} color - The input color with premultiplied alpha.
  14160. * @return {Node<vec4>} The color with non-premultiplied alpha.
  14161. */
  14162. const unpremultiplyAlpha = /*@__PURE__*/ Fn( ( [ color ] ) => {
  14163. If( color.a.equal( 0.0 ), () => vec4( 0.0 ) );
  14164. return vec4( color.rgb.div( color.a ), color.a );
  14165. }, { color: 'vec4', return: 'vec4' } );
  14166. // Deprecated
  14167. /**
  14168. * @tsl
  14169. * @function
  14170. * @deprecated since r171. Use {@link blendBurn} instead.
  14171. *
  14172. * @param {...any} params
  14173. * @returns {Function}
  14174. */
  14175. const burn = ( ...params ) => { // @deprecated, r171
  14176. warn( 'TSL: "burn" has been renamed. Use "blendBurn" instead.' );
  14177. return blendBurn( params );
  14178. };
  14179. /**
  14180. * @tsl
  14181. * @function
  14182. * @deprecated since r171. Use {@link blendDodge} instead.
  14183. *
  14184. * @param {...any} params
  14185. * @returns {Function}
  14186. */
  14187. const dodge = ( ...params ) => { // @deprecated, r171
  14188. warn( 'TSL: "dodge" has been renamed. Use "blendDodge" instead.' );
  14189. return blendDodge( params );
  14190. };
  14191. /**
  14192. * @tsl
  14193. * @function
  14194. * @deprecated since r171. Use {@link blendScreen} instead.
  14195. *
  14196. * @param {...any} params
  14197. * @returns {Function}
  14198. */
  14199. const screen = ( ...params ) => { // @deprecated, r171
  14200. warn( 'TSL: "screen" has been renamed. Use "blendScreen" instead.' );
  14201. return blendScreen( params );
  14202. };
  14203. /**
  14204. * @tsl
  14205. * @function
  14206. * @deprecated since r171. Use {@link blendOverlay} instead.
  14207. *
  14208. * @param {...any} params
  14209. * @returns {Function}
  14210. */
  14211. const overlay = ( ...params ) => { // @deprecated, r171
  14212. warn( 'TSL: "overlay" has been renamed. Use "blendOverlay" instead.' );
  14213. return blendOverlay( params );
  14214. };
  14215. /**
  14216. * Base class for all node materials.
  14217. *
  14218. * @augments Material
  14219. */
  14220. class NodeMaterial extends Material {
  14221. static get type() {
  14222. return 'NodeMaterial';
  14223. }
  14224. /**
  14225. * Represents the type of the node material.
  14226. *
  14227. * @type {string}
  14228. */
  14229. get type() {
  14230. return this.constructor.type;
  14231. }
  14232. set type( _value ) { /* */ }
  14233. /**
  14234. * Constructs a new node material.
  14235. */
  14236. constructor() {
  14237. super();
  14238. /**
  14239. * This flag can be used for type testing.
  14240. *
  14241. * @type {boolean}
  14242. * @readonly
  14243. * @default true
  14244. */
  14245. this.isNodeMaterial = true;
  14246. /**
  14247. * Whether this material is affected by fog or not.
  14248. *
  14249. * @type {boolean}
  14250. * @default true
  14251. */
  14252. this.fog = true;
  14253. /**
  14254. * Whether this material is affected by lights or not.
  14255. *
  14256. * @type {boolean}
  14257. * @default false
  14258. */
  14259. this.lights = false;
  14260. /**
  14261. * Whether this material uses hardware clipping or not.
  14262. * This property is managed by the engine and should not be
  14263. * modified by apps.
  14264. *
  14265. * @type {boolean}
  14266. * @default false
  14267. */
  14268. this.hardwareClipping = false;
  14269. /**
  14270. * Node materials which set their `lights` property to `true`
  14271. * are affected by all lights of the scene. Sometimes selective
  14272. * lighting is wanted which means only _some_ lights in the scene
  14273. * affect a material. This can be achieved by creating an instance
  14274. * of {@link LightsNode} with a list of selective
  14275. * lights and assign the node to this property.
  14276. *
  14277. * ```js
  14278. * const customLightsNode = lights( [ light1, light2 ] );
  14279. * material.lightsNode = customLightsNode;
  14280. * ```
  14281. *
  14282. * @type {?LightsNode}
  14283. * @default null
  14284. */
  14285. this.lightsNode = null;
  14286. /**
  14287. * The environment of node materials can be defined by an environment
  14288. * map assigned to the `envMap` property or by `Scene.environment`
  14289. * if the node material is a PBR material. This node property allows to overwrite
  14290. * the default behavior and define the environment with a custom node.
  14291. *
  14292. * ```js
  14293. * material.envNode = pmremTexture( renderTarget.texture );
  14294. * ```
  14295. *
  14296. * @type {?Node<vec3>}
  14297. * @default null
  14298. */
  14299. this.envNode = null;
  14300. /**
  14301. * The lighting of node materials might be influenced by ambient occlusion.
  14302. * The default AO is inferred from an ambient occlusion map assigned to `aoMap`
  14303. * and the respective `aoMapIntensity`. This node property allows to overwrite
  14304. * the default and define the ambient occlusion with a custom node instead.
  14305. *
  14306. * If you don't want to overwrite the diffuse color but modify the existing
  14307. * values instead, use {@link materialAO}.
  14308. *
  14309. * @type {?Node<float>}
  14310. * @default null
  14311. */
  14312. this.aoNode = null;
  14313. /**
  14314. * The diffuse color of node materials is by default inferred from the
  14315. * `color` and `map` properties. This node property allows to overwrite the default
  14316. * and define the diffuse color with a node instead.
  14317. *
  14318. * ```js
  14319. * material.colorNode = color( 0xff0000 ); // define red color
  14320. * ```
  14321. *
  14322. * If you don't want to overwrite the diffuse color but modify the existing
  14323. * values instead, use {@link materialColor}.
  14324. *
  14325. * ```js
  14326. * material.colorNode = materialColor.mul( color( 0xff0000 ) ); // give diffuse colors a red tint
  14327. * ```
  14328. *
  14329. * @type {?Node<vec3>}
  14330. * @default null
  14331. */
  14332. this.colorNode = null;
  14333. /**
  14334. * The normals of node materials are by default inferred from the `normalMap`/`normalScale`
  14335. * or `bumpMap`/`bumpScale` properties. This node property allows to overwrite the default
  14336. * and define the normals with a node instead.
  14337. *
  14338. * If you don't want to overwrite the normals but modify the existing values instead,
  14339. * use {@link materialNormal}.
  14340. *
  14341. * @type {?Node<vec3>}
  14342. * @default null
  14343. */
  14344. this.normalNode = null;
  14345. /**
  14346. * The opacity of node materials is by default inferred from the `opacity`
  14347. * and `alphaMap` properties. This node property allows to overwrite the default
  14348. * and define the opacity with a node instead.
  14349. *
  14350. * If you don't want to overwrite the opacity but modify the existing
  14351. * value instead, use {@link materialOpacity}.
  14352. *
  14353. * @type {?Node<float>}
  14354. * @default null
  14355. */
  14356. this.opacityNode = null;
  14357. /**
  14358. * This node can be used to implement a variety of filter-like effects. The idea is
  14359. * to store the current rendering into a texture e.g. via `viewportSharedTexture()`, use it
  14360. * to create an arbitrary effect and then assign the node composition to this property.
  14361. * Everything behind the object using this material will now be affected by a filter.
  14362. *
  14363. * ```js
  14364. * const material = new NodeMaterial()
  14365. * material.transparent = true;
  14366. *
  14367. * // everything behind the object will be monochromatic
  14368. * material.backdropNode = saturation( viewportSharedTexture().rgb, 0 );
  14369. * ```
  14370. *
  14371. * Backdrop computations are part of the lighting so only lit materials can use this property.
  14372. *
  14373. * @type {?Node<vec3>}
  14374. * @default null
  14375. */
  14376. this.backdropNode = null;
  14377. /**
  14378. * This node allows to modulate the influence of `backdropNode` to the outgoing light.
  14379. *
  14380. * @type {?Node<float>}
  14381. * @default null
  14382. */
  14383. this.backdropAlphaNode = null;
  14384. /**
  14385. * The alpha test of node materials is by default inferred from the `alphaTest`
  14386. * property. This node property allows to overwrite the default and define the
  14387. * alpha test with a node instead.
  14388. *
  14389. * If you don't want to overwrite the alpha test but modify the existing
  14390. * value instead, use {@link materialAlphaTest}.
  14391. *
  14392. * @type {?Node<float>}
  14393. * @default null
  14394. */
  14395. this.alphaTestNode = null;
  14396. /**
  14397. * Discards the fragment if the mask value is `false`.
  14398. *
  14399. * @type {?Node<bool>}
  14400. * @default null
  14401. */
  14402. this.maskNode = null;
  14403. /**
  14404. * The local vertex positions are computed based on multiple factors like the
  14405. * attribute data, morphing or skinning. This node property allows to overwrite
  14406. * the default and define local vertex positions with nodes instead.
  14407. *
  14408. * If you don't want to overwrite the vertex positions but modify the existing
  14409. * values instead, use {@link positionLocal}.
  14410. *
  14411. *```js
  14412. * material.positionNode = positionLocal.add( displace );
  14413. * ```
  14414. *
  14415. * @type {?Node<vec3>}
  14416. * @default null
  14417. */
  14418. this.positionNode = null;
  14419. /**
  14420. * This node property is intended for logic which modifies geometry data once or per animation step.
  14421. * Apps usually place such logic randomly in initialization routines or in the animation loop.
  14422. * `geometryNode` is intended as a dedicated API so there is an intended spot where geometry modifications
  14423. * can be implemented.
  14424. *
  14425. * The idea is to assign a `Fn` definition that holds the geometry modification logic. A typical example
  14426. * would be a GPU based particle system that provides a node material for usage on app level. The particle
  14427. * simulation would be implemented as compute shaders and managed inside a `Fn` function. This function is
  14428. * eventually assigned to `geometryNode`.
  14429. *
  14430. * @type {?Function}
  14431. * @default null
  14432. */
  14433. this.geometryNode = null;
  14434. /**
  14435. * Allows to overwrite depth values in the fragment shader.
  14436. *
  14437. * @type {?Node<float>}
  14438. * @default null
  14439. */
  14440. this.depthNode = null;
  14441. /**
  14442. * Allows to overwrite the position used for shadow map rendering which
  14443. * is by default {@link positionWorld}, the vertex position
  14444. * in world space.
  14445. *
  14446. * @type {?Node<float>}
  14447. * @default null
  14448. */
  14449. this.receivedShadowPositionNode = null;
  14450. /**
  14451. * Allows to overwrite the geometry position used for shadow map projection which
  14452. * is by default {@link positionLocal}, the vertex position in local space.
  14453. *
  14454. * @type {?Node<float>}
  14455. * @default null
  14456. */
  14457. this.castShadowPositionNode = null;
  14458. /**
  14459. * This node can be used to influence how an object using this node material
  14460. * receive shadows.
  14461. *
  14462. * ```js
  14463. * const totalShadows = float( 1 ).toVar();
  14464. * material.receivedShadowNode = Fn( ( [ shadow ] ) => {
  14465. * totalShadows.mulAssign( shadow );
  14466. * //return float( 1 ); // bypass received shadows
  14467. * return shadow.mix( color( 0xff0000 ), 1 ); // modify shadow color
  14468. * } );
  14469. *
  14470. * @type {?(Function|FunctionNode<vec4>)}
  14471. * @default null
  14472. */
  14473. this.receivedShadowNode = null;
  14474. /**
  14475. * This node can be used to influence how an object using this node material
  14476. * casts shadows. To apply a color to shadows, you can simply do:
  14477. *
  14478. * ```js
  14479. * material.castShadowNode = vec4( 1, 0, 0, 1 );
  14480. * ```
  14481. *
  14482. * Which can be nice to fake colored shadows of semi-transparent objects. It
  14483. * is also common to use the property with `Fn` function so checks are performed
  14484. * per fragment.
  14485. *
  14486. * ```js
  14487. * materialCustomShadow.castShadowNode = Fn( () => {
  14488. * hash( vertexIndex ).greaterThan( 0.5 ).discard();
  14489. * return materialColor;
  14490. * } )();
  14491. * ```
  14492. *
  14493. * @type {?Node<vec4>}
  14494. * @default null
  14495. */
  14496. this.castShadowNode = null;
  14497. /**
  14498. * This node can be used to define the final output of the material.
  14499. *
  14500. * TODO: Explain the differences to `fragmentNode`.
  14501. *
  14502. * @type {?Node<vec4>}
  14503. * @default null
  14504. */
  14505. this.outputNode = null;
  14506. /**
  14507. * MRT configuration is done on renderer or pass level. This node allows to
  14508. * overwrite what values are written into MRT targets on material level. This
  14509. * can be useful for implementing selective FX features that should only affect
  14510. * specific objects.
  14511. *
  14512. * @type {?MRTNode}
  14513. * @default null
  14514. */
  14515. this.mrtNode = null;
  14516. /**
  14517. * This node property can be used if you need complete freedom in implementing
  14518. * the fragment shader. Assigning a node will replace the built-in material
  14519. * logic used in the fragment stage.
  14520. *
  14521. * @type {?Node<vec4>}
  14522. * @default null
  14523. */
  14524. this.fragmentNode = null;
  14525. /**
  14526. * This node property can be used if you need complete freedom in implementing
  14527. * the vertex shader. Assigning a node will replace the built-in material logic
  14528. * used in the vertex stage.
  14529. *
  14530. * @type {?Node<vec4>}
  14531. * @default null
  14532. */
  14533. this.vertexNode = null;
  14534. /**
  14535. * This node can be used as a global context management component for this material.
  14536. *
  14537. * @type {?ContextNode}
  14538. * @default null
  14539. */
  14540. this.contextNode = null;
  14541. // Deprecated properties
  14542. Object.defineProperty( this, 'shadowPositionNode', { // @deprecated, r176
  14543. get: () => {
  14544. return this.receivedShadowPositionNode;
  14545. },
  14546. set: ( value ) => {
  14547. warn( 'NodeMaterial: ".shadowPositionNode" was renamed to ".receivedShadowPositionNode".' );
  14548. this.receivedShadowPositionNode = value;
  14549. }
  14550. } );
  14551. }
  14552. /**
  14553. * Returns an array of child nodes for this material.
  14554. *
  14555. * @private
  14556. * @returns {Array<{property: string, childNode: Node}>}
  14557. */
  14558. _getNodeChildren() {
  14559. const children = [];
  14560. for ( const property of Object.getOwnPropertyNames( this ) ) {
  14561. if ( property.startsWith( '_' ) === true ) continue;
  14562. const object = this[ property ];
  14563. if ( object && object.isNode === true ) {
  14564. children.push( { property, childNode: object } );
  14565. }
  14566. }
  14567. return children;
  14568. }
  14569. /**
  14570. * Allows to define a custom cache key that influence the material key computation
  14571. * for render objects.
  14572. *
  14573. * @return {string} The custom cache key.
  14574. */
  14575. customProgramCacheKey() {
  14576. const values = [];
  14577. for ( const { property, childNode } of this._getNodeChildren() ) {
  14578. values.push( hashString( property.slice( 0, -4 ) ), childNode.getCacheKey() );
  14579. }
  14580. return this.type + hashArray( values );
  14581. }
  14582. /**
  14583. * Builds this material with the given node builder.
  14584. *
  14585. * @param {NodeBuilder} builder - The current node builder.
  14586. */
  14587. build( builder ) {
  14588. this.setup( builder );
  14589. }
  14590. /**
  14591. * Setups a node material observer with the given builder.
  14592. *
  14593. * @param {NodeBuilder} builder - The current node builder.
  14594. * @return {NodeMaterialObserver} The node material observer.
  14595. */
  14596. setupObserver( builder ) {
  14597. return new NodeMaterialObserver( builder );
  14598. }
  14599. /**
  14600. * Setups the vertex and fragment stage of this node material.
  14601. *
  14602. * @param {NodeBuilder} builder - The current node builder.
  14603. */
  14604. setup( builder ) {
  14605. builder.context.setupNormal = () => subBuild( this.setupNormal( builder ), 'NORMAL', 'vec3' );
  14606. builder.context.setupPositionView = () => this.setupPositionView( builder );
  14607. builder.context.setupModelViewProjection = () => this.setupModelViewProjection( builder );
  14608. const renderer = builder.renderer;
  14609. const renderTarget = renderer.getRenderTarget();
  14610. // < CONTEXT >
  14611. if ( renderer.contextNode.isContextNode === true ) {
  14612. builder.context = { ...builder.context, ...renderer.contextNode.getFlowContextData() };
  14613. } else {
  14614. error( 'NodeMaterial: "renderer.contextNode" must be an instance of `context()`.' );
  14615. }
  14616. if ( this.contextNode !== null ) {
  14617. if ( this.contextNode.isContextNode === true ) {
  14618. builder.context = { ...builder.context, ...this.contextNode.getFlowContextData() };
  14619. } else {
  14620. error( 'NodeMaterial: "material.contextNode" must be an instance of `context()`.' );
  14621. }
  14622. }
  14623. // < VERTEX STAGE >
  14624. builder.addStack();
  14625. const mvp = subBuild( this.setupVertex( builder ), 'VERTEX' );
  14626. const vertexNode = this.vertexNode || mvp;
  14627. builder.stack.outputNode = vertexNode;
  14628. this.setupHardwareClipping( builder );
  14629. if ( this.geometryNode !== null ) {
  14630. builder.stack.outputNode = builder.stack.outputNode.bypass( this.geometryNode );
  14631. }
  14632. builder.addFlow( 'vertex', builder.removeStack() );
  14633. // < FRAGMENT STAGE >
  14634. builder.addStack();
  14635. let resultNode;
  14636. const clippingNode = this.setupClipping( builder );
  14637. if ( this.depthWrite === true || this.depthTest === true ) {
  14638. // only write depth if depth buffer is configured
  14639. if ( renderTarget !== null ) {
  14640. if ( renderTarget.depthBuffer === true ) this.setupDepth( builder );
  14641. } else {
  14642. if ( renderer.depth === true ) this.setupDepth( builder );
  14643. }
  14644. }
  14645. if ( this.fragmentNode === null ) {
  14646. this.setupDiffuseColor( builder );
  14647. this.setupVariants( builder );
  14648. const outgoingLightNode = this.setupLighting( builder );
  14649. if ( clippingNode !== null ) builder.stack.addToStack( clippingNode );
  14650. // force unsigned floats - useful for RenderTargets
  14651. const basicOutput = vec4( outgoingLightNode, diffuseColor.a ).max( 0 );
  14652. resultNode = this.setupOutput( builder, basicOutput );
  14653. // OUTPUT NODE
  14654. output.assign( resultNode );
  14655. //
  14656. const isCustomOutput = this.outputNode !== null;
  14657. if ( isCustomOutput ) resultNode = this.outputNode;
  14658. //
  14659. if ( builder.context.getOutput ) {
  14660. resultNode = builder.context.getOutput( resultNode, builder );
  14661. }
  14662. // MRT
  14663. if ( renderTarget !== null ) {
  14664. const mrt = renderer.getMRT();
  14665. const materialMRT = this.mrtNode;
  14666. if ( mrt !== null ) {
  14667. if ( isCustomOutput ) output.assign( resultNode );
  14668. resultNode = mrt;
  14669. if ( materialMRT !== null ) {
  14670. resultNode = mrt.merge( materialMRT );
  14671. }
  14672. } else if ( materialMRT !== null ) {
  14673. resultNode = materialMRT;
  14674. }
  14675. }
  14676. } else {
  14677. let fragmentNode = this.fragmentNode;
  14678. if ( fragmentNode.isOutputStructNode !== true ) {
  14679. fragmentNode = vec4( fragmentNode );
  14680. }
  14681. resultNode = this.setupOutput( builder, fragmentNode );
  14682. }
  14683. builder.stack.outputNode = resultNode;
  14684. builder.addFlow( 'fragment', builder.removeStack() );
  14685. // < OBSERVER >
  14686. builder.observer = this.setupObserver( builder );
  14687. }
  14688. /**
  14689. * Setups the clipping node.
  14690. *
  14691. * @param {NodeBuilder} builder - The current node builder.
  14692. * @return {ClippingNode} The clipping node.
  14693. */
  14694. setupClipping( builder ) {
  14695. if ( builder.clippingContext === null ) return null;
  14696. const { unionPlanes, intersectionPlanes } = builder.clippingContext;
  14697. let result = null;
  14698. if ( unionPlanes.length > 0 || intersectionPlanes.length > 0 ) {
  14699. const samples = builder.renderer.currentSamples;
  14700. if ( this.alphaToCoverage && samples > 1 ) {
  14701. // to be added to flow when the color/alpha value has been determined
  14702. result = clippingAlpha();
  14703. } else {
  14704. builder.stack.addToStack( clipping() );
  14705. }
  14706. }
  14707. return result;
  14708. }
  14709. /**
  14710. * Setups the hardware clipping if available on the current device.
  14711. *
  14712. * @param {NodeBuilder} builder - The current node builder.
  14713. */
  14714. setupHardwareClipping( builder ) {
  14715. this.hardwareClipping = false;
  14716. if ( builder.clippingContext === null ) return;
  14717. const candidateCount = builder.clippingContext.unionPlanes.length;
  14718. // 8 planes supported by WebGL ANGLE_clip_cull_distance and WebGPU clip-distances
  14719. if ( candidateCount > 0 && candidateCount <= 8 && builder.isAvailable( 'clipDistance' ) ) {
  14720. builder.stack.addToStack( hardwareClipping() );
  14721. this.hardwareClipping = true;
  14722. }
  14723. return;
  14724. }
  14725. /**
  14726. * Setups the depth of this material.
  14727. *
  14728. * @param {NodeBuilder} builder - The current node builder.
  14729. */
  14730. setupDepth( builder ) {
  14731. const { renderer, camera } = builder;
  14732. // Depth
  14733. let depthNode = this.depthNode;
  14734. if ( depthNode === null ) {
  14735. const mrt = renderer.getMRT();
  14736. if ( mrt && mrt.has( 'depth' ) ) {
  14737. depthNode = mrt.get( 'depth' );
  14738. } else if ( renderer.logarithmicDepthBuffer === true ) {
  14739. if ( camera.isPerspectiveCamera ) {
  14740. depthNode = viewZToLogarithmicDepth( positionView.z, cameraNear, cameraFar );
  14741. } else {
  14742. depthNode = viewZToOrthographicDepth( positionView.z, cameraNear, cameraFar );
  14743. }
  14744. }
  14745. }
  14746. if ( depthNode !== null ) {
  14747. depth.assign( depthNode ).toStack();
  14748. }
  14749. }
  14750. /**
  14751. * Setups the position node in view space. This method exists
  14752. * so derived node materials can modify the implementation e.g. sprite materials.
  14753. *
  14754. * @param {NodeBuilder} builder - The current node builder.
  14755. * @return {Node<vec3>} The position in view space.
  14756. */
  14757. setupPositionView( /*builder*/ ) {
  14758. return modelViewMatrix.mul( positionLocal ).xyz;
  14759. }
  14760. /**
  14761. * Setups the position in clip space.
  14762. *
  14763. * @param {NodeBuilder} builder - The current node builder.
  14764. * @return {Node<vec4>} The position in view space.
  14765. */
  14766. setupModelViewProjection( /*builder*/ ) {
  14767. return cameraProjectionMatrix.mul( positionView );
  14768. }
  14769. /**
  14770. * Setups the logic for the vertex stage.
  14771. *
  14772. * @param {NodeBuilder} builder - The current node builder.
  14773. * @return {Node<vec4>} The position in clip space.
  14774. */
  14775. setupVertex( builder ) {
  14776. builder.addStack();
  14777. this.setupPosition( builder );
  14778. builder.context.vertex = builder.removeStack();
  14779. return modelViewProjection;
  14780. }
  14781. /**
  14782. * Setups the computation of the position in local space.
  14783. *
  14784. * @param {NodeBuilder} builder - The current node builder.
  14785. * @return {Node<vec3>} The position in local space.
  14786. */
  14787. setupPosition( builder ) {
  14788. const { object, geometry } = builder;
  14789. if ( geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color ) {
  14790. morphReference( object ).toStack();
  14791. }
  14792. if ( object.isSkinnedMesh === true ) {
  14793. skinning( object ).toStack();
  14794. }
  14795. if ( this.displacementMap ) {
  14796. const displacementMap = materialReference( 'displacementMap', 'texture' );
  14797. const displacementScale = materialReference( 'displacementScale', 'float' );
  14798. const displacementBias = materialReference( 'displacementBias', 'float' );
  14799. positionLocal.addAssign( normalLocal.normalize().mul( ( displacementMap.x.mul( displacementScale ).add( displacementBias ) ) ) );
  14800. }
  14801. if ( object.isBatchedMesh ) {
  14802. batch( object ).toStack();
  14803. }
  14804. if ( ( object.isInstancedMesh && object.instanceMatrix && object.instanceMatrix.isInstancedBufferAttribute === true ) ) {
  14805. instancedMesh( object ).toStack();
  14806. }
  14807. if ( this.positionNode !== null ) {
  14808. positionLocal.assign( subBuild( this.positionNode, 'POSITION', 'vec3' ) );
  14809. }
  14810. return positionLocal;
  14811. }
  14812. /**
  14813. * Setups the computation of the material's diffuse color.
  14814. *
  14815. * @param {NodeBuilder} builder - The current node builder.
  14816. * @param {BufferGeometry} geometry - The geometry.
  14817. */
  14818. setupDiffuseColor( builder ) {
  14819. const { object, geometry } = builder;
  14820. // MASK
  14821. if ( this.maskNode !== null ) {
  14822. // Discard if the mask is `false`
  14823. bool( this.maskNode ).not().discard();
  14824. }
  14825. // COLOR
  14826. let colorNode = this.colorNode ? vec4( this.colorNode ) : materialColor;
  14827. // VERTEX COLORS
  14828. if ( this.vertexColors === true && geometry.hasAttribute( 'color' ) ) {
  14829. colorNode = colorNode.mul( vertexColor() );
  14830. }
  14831. // INSTANCED COLORS
  14832. if ( object.instanceColor ) {
  14833. const instanceColor = varyingProperty( 'vec3', 'vInstanceColor' );
  14834. colorNode = instanceColor.mul( colorNode );
  14835. }
  14836. if ( object.isBatchedMesh && object._colorsTexture ) {
  14837. const batchColor = varyingProperty( 'vec3', 'vBatchColor' );
  14838. colorNode = batchColor.mul( colorNode );
  14839. }
  14840. // DIFFUSE COLOR
  14841. diffuseColor.assign( colorNode );
  14842. // OPACITY
  14843. const opacityNode = this.opacityNode ? float( this.opacityNode ) : materialOpacity;
  14844. diffuseColor.a.assign( diffuseColor.a.mul( opacityNode ) );
  14845. // ALPHA TEST
  14846. let alphaTestNode = null;
  14847. if ( this.alphaTestNode !== null || this.alphaTest > 0 ) {
  14848. alphaTestNode = this.alphaTestNode !== null ? float( this.alphaTestNode ) : materialAlphaTest;
  14849. if ( this.alphaToCoverage === true ) {
  14850. diffuseColor.a = smoothstep( alphaTestNode, alphaTestNode.add( fwidth( diffuseColor.a ) ), diffuseColor.a );
  14851. diffuseColor.a.lessThanEqual( 0 ).discard();
  14852. } else {
  14853. diffuseColor.a.lessThanEqual( alphaTestNode ).discard();
  14854. }
  14855. }
  14856. // ALPHA HASH
  14857. if ( this.alphaHash === true ) {
  14858. diffuseColor.a.lessThan( getAlphaHashThreshold( positionLocal ) ).discard();
  14859. }
  14860. // OPAQUE
  14861. if ( builder.isOpaque() ) {
  14862. diffuseColor.a.assign( 1.0 );
  14863. }
  14864. }
  14865. /**
  14866. * Abstract interface method that can be implemented by derived materials
  14867. * to setup material-specific node variables.
  14868. *
  14869. * @abstract
  14870. * @param {NodeBuilder} builder - The current node builder.
  14871. */
  14872. setupVariants( /*builder*/ ) {
  14873. // Interface function.
  14874. }
  14875. /**
  14876. * Setups the outgoing light node variable
  14877. *
  14878. * @return {Node<vec3>} The outgoing light node.
  14879. */
  14880. setupOutgoingLight() {
  14881. return ( this.lights === true ) ? vec3( 0 ) : diffuseColor.rgb;
  14882. }
  14883. /**
  14884. * Setups the normal node from the material.
  14885. *
  14886. * @return {Node<vec3>} The normal node.
  14887. */
  14888. setupNormal() {
  14889. return this.normalNode ? vec3( this.normalNode ) : materialNormal;
  14890. }
  14891. /**
  14892. * Setups the environment node from the material.
  14893. *
  14894. * @param {NodeBuilder} builder - The current node builder.
  14895. * @return {Node<vec4>} The environment node.
  14896. */
  14897. setupEnvironment( /*builder*/ ) {
  14898. let node = null;
  14899. if ( this.envNode ) {
  14900. node = this.envNode;
  14901. } else if ( this.envMap ) {
  14902. node = this.envMap.isCubeTexture ? materialReference( 'envMap', 'cubeTexture' ) : materialReference( 'envMap', 'texture' );
  14903. }
  14904. return node;
  14905. }
  14906. /**
  14907. * Setups the light map node from the material.
  14908. *
  14909. * @param {NodeBuilder} builder - The current node builder.
  14910. * @return {Node<vec3>} The light map node.
  14911. */
  14912. setupLightMap( builder ) {
  14913. let node = null;
  14914. if ( builder.material.lightMap ) {
  14915. node = new IrradianceNode( materialLightMap );
  14916. }
  14917. return node;
  14918. }
  14919. /**
  14920. * Setups the lights node based on the scene, environment and material.
  14921. *
  14922. * @param {NodeBuilder} builder - The current node builder.
  14923. * @return {LightsNode} The lights node.
  14924. */
  14925. setupLights( builder ) {
  14926. const materialLightsNode = [];
  14927. //
  14928. const envNode = this.setupEnvironment( builder );
  14929. if ( envNode && envNode.isLightingNode ) {
  14930. materialLightsNode.push( envNode );
  14931. }
  14932. const lightMapNode = this.setupLightMap( builder );
  14933. if ( lightMapNode && lightMapNode.isLightingNode ) {
  14934. materialLightsNode.push( lightMapNode );
  14935. }
  14936. let aoNode = this.aoNode;
  14937. if ( aoNode === null && builder.material.aoMap ) {
  14938. aoNode = materialAO;
  14939. }
  14940. if ( builder.context.getAO ) {
  14941. aoNode = builder.context.getAO( aoNode, builder );
  14942. }
  14943. if ( aoNode ) {
  14944. materialLightsNode.push( new AONode( aoNode ) );
  14945. }
  14946. let lightsN = this.lightsNode || builder.lightsNode;
  14947. if ( materialLightsNode.length > 0 ) {
  14948. lightsN = builder.renderer.lighting.createNode( [ ...lightsN.getLights(), ...materialLightsNode ] );
  14949. }
  14950. return lightsN;
  14951. }
  14952. /**
  14953. * This method should be implemented by most derived materials
  14954. * since it defines the material's lighting model.
  14955. *
  14956. * @abstract
  14957. * @param {NodeBuilder} builder - The current node builder.
  14958. * @return {LightingModel} The lighting model.
  14959. */
  14960. setupLightingModel( /*builder*/ ) {
  14961. // Interface function.
  14962. }
  14963. /**
  14964. * Setups the outgoing light node.
  14965. *
  14966. * @param {NodeBuilder} builder - The current node builder.
  14967. * @return {Node<vec3>} The outgoing light node.
  14968. */
  14969. setupLighting( builder ) {
  14970. const { material } = builder;
  14971. const { backdropNode, backdropAlphaNode, emissiveNode } = this;
  14972. // OUTGOING LIGHT
  14973. const lights = this.lights === true || this.lightsNode !== null;
  14974. const lightsNode = lights ? this.setupLights( builder ) : null;
  14975. let outgoingLightNode = this.setupOutgoingLight( builder );
  14976. if ( lightsNode && lightsNode.getScope().hasLights ) {
  14977. const lightingModel = this.setupLightingModel( builder ) || null;
  14978. outgoingLightNode = lightingContext( lightsNode, lightingModel, backdropNode, backdropAlphaNode );
  14979. } else if ( backdropNode !== null ) {
  14980. outgoingLightNode = vec3( backdropAlphaNode !== null ? mix( outgoingLightNode, backdropNode, backdropAlphaNode ) : backdropNode );
  14981. }
  14982. // EMISSIVE
  14983. if ( ( emissiveNode && emissiveNode.isNode === true ) || ( material.emissive && material.emissive.isColor === true ) ) {
  14984. emissive.assign( vec3( emissiveNode ? emissiveNode : materialEmissive ) );
  14985. outgoingLightNode = outgoingLightNode.add( emissive );
  14986. }
  14987. return outgoingLightNode;
  14988. }
  14989. /**
  14990. * Setup the fog.
  14991. *
  14992. * @param {NodeBuilder} builder - The current node builder.
  14993. * @param {Node<vec4>} outputNode - The existing output node.
  14994. * @return {Node<vec4>} The output node.
  14995. */
  14996. setupFog( builder, outputNode ) {
  14997. const fogNode = builder.fogNode;
  14998. if ( fogNode ) {
  14999. output.assign( outputNode );
  15000. outputNode = vec4( fogNode.toVar() );
  15001. }
  15002. return outputNode;
  15003. }
  15004. /**
  15005. * Setups premultiplied alpha.
  15006. *
  15007. * @param {NodeBuilder} builder - The current node builder.
  15008. * @param {Node<vec4>} outputNode - The existing output node.
  15009. * @return {Node<vec4>} The output node.
  15010. */
  15011. setupPremultipliedAlpha( builder, outputNode ) {
  15012. return premultiplyAlpha( outputNode );
  15013. }
  15014. /**
  15015. * Setups the output node.
  15016. *
  15017. * @param {NodeBuilder} builder - The current node builder.
  15018. * @param {Node<vec4>} outputNode - The existing output node.
  15019. * @return {Node<vec4>} The output node.
  15020. */
  15021. setupOutput( builder, outputNode ) {
  15022. // FOG
  15023. if ( this.fog === true ) {
  15024. outputNode = this.setupFog( builder, outputNode );
  15025. }
  15026. // PREMULTIPLIED ALPHA
  15027. if ( this.premultipliedAlpha === true ) {
  15028. outputNode = this.setupPremultipliedAlpha( builder, outputNode );
  15029. }
  15030. return outputNode;
  15031. }
  15032. /**
  15033. * Most classic material types have a node pendant e.g. for `MeshBasicMaterial`
  15034. * there is `MeshBasicNodeMaterial`. This utility method is intended for
  15035. * defining all material properties of the classic type in the node type.
  15036. *
  15037. * @param {Material} material - The material to copy properties with their values to this node material.
  15038. */
  15039. setDefaultValues( material ) {
  15040. // This approach is to reuse the native refreshUniforms*
  15041. // and turn available the use of features like transmission and environment in core
  15042. for ( const property in material ) {
  15043. const value = material[ property ];
  15044. if ( this[ property ] === undefined ) {
  15045. this[ property ] = value;
  15046. if ( value && value.clone ) this[ property ] = value.clone();
  15047. }
  15048. }
  15049. const descriptors = Object.getOwnPropertyDescriptors( material.constructor.prototype );
  15050. for ( const key in descriptors ) {
  15051. if ( Object.getOwnPropertyDescriptor( this.constructor.prototype, key ) === undefined &&
  15052. descriptors[ key ].get !== undefined ) {
  15053. Object.defineProperty( this.constructor.prototype, key, descriptors[ key ] );
  15054. }
  15055. }
  15056. }
  15057. /**
  15058. * Serializes this material to JSON.
  15059. *
  15060. * @param {?(Object|string)} meta - The meta information for serialization.
  15061. * @return {Object} The serialized node.
  15062. */
  15063. toJSON( meta ) {
  15064. const isRoot = ( meta === undefined || typeof meta === 'string' );
  15065. if ( isRoot ) {
  15066. meta = {
  15067. textures: {},
  15068. images: {},
  15069. nodes: {}
  15070. };
  15071. }
  15072. const data = Material.prototype.toJSON.call( this, meta );
  15073. data.inputNodes = {};
  15074. for ( const { property, childNode } of this._getNodeChildren() ) {
  15075. data.inputNodes[ property ] = childNode.toJSON( meta ).uuid;
  15076. }
  15077. // TODO: Copied from Object3D.toJSON
  15078. function extractFromCache( cache ) {
  15079. const values = [];
  15080. for ( const key in cache ) {
  15081. const data = cache[ key ];
  15082. delete data.metadata;
  15083. values.push( data );
  15084. }
  15085. return values;
  15086. }
  15087. if ( isRoot ) {
  15088. const textures = extractFromCache( meta.textures );
  15089. const images = extractFromCache( meta.images );
  15090. const nodes = extractFromCache( meta.nodes );
  15091. if ( textures.length > 0 ) data.textures = textures;
  15092. if ( images.length > 0 ) data.images = images;
  15093. if ( nodes.length > 0 ) data.nodes = nodes;
  15094. }
  15095. return data;
  15096. }
  15097. /**
  15098. * Copies the properties of the given node material to this instance.
  15099. *
  15100. * @param {NodeMaterial} source - The material to copy.
  15101. * @return {NodeMaterial} A reference to this node material.
  15102. */
  15103. copy( source ) {
  15104. this.lightsNode = source.lightsNode;
  15105. this.envNode = source.envNode;
  15106. this.aoNode = source.aoNode;
  15107. this.colorNode = source.colorNode;
  15108. this.normalNode = source.normalNode;
  15109. this.opacityNode = source.opacityNode;
  15110. this.backdropNode = source.backdropNode;
  15111. this.backdropAlphaNode = source.backdropAlphaNode;
  15112. this.alphaTestNode = source.alphaTestNode;
  15113. this.maskNode = source.maskNode;
  15114. this.positionNode = source.positionNode;
  15115. this.geometryNode = source.geometryNode;
  15116. this.depthNode = source.depthNode;
  15117. this.receivedShadowPositionNode = source.receivedShadowPositionNode;
  15118. this.castShadowPositionNode = source.castShadowPositionNode;
  15119. this.receivedShadowNode = source.receivedShadowNode;
  15120. this.castShadowNode = source.castShadowNode;
  15121. this.outputNode = source.outputNode;
  15122. this.mrtNode = source.mrtNode;
  15123. this.fragmentNode = source.fragmentNode;
  15124. this.vertexNode = source.vertexNode;
  15125. this.contextNode = source.contextNode;
  15126. return super.copy( source );
  15127. }
  15128. }
  15129. const _defaultValues$d = /*@__PURE__*/ new LineBasicMaterial();
  15130. /**
  15131. * Node material version of {@link LineBasicMaterial}.
  15132. *
  15133. * @augments NodeMaterial
  15134. */
  15135. class LineBasicNodeMaterial extends NodeMaterial {
  15136. static get type() {
  15137. return 'LineBasicNodeMaterial';
  15138. }
  15139. /**
  15140. * Constructs a new line basic node material.
  15141. *
  15142. * @param {Object} [parameters] - The configuration parameter.
  15143. */
  15144. constructor( parameters ) {
  15145. super();
  15146. /**
  15147. * This flag can be used for type testing.
  15148. *
  15149. * @type {boolean}
  15150. * @readonly
  15151. * @default true
  15152. */
  15153. this.isLineBasicNodeMaterial = true;
  15154. this.setDefaultValues( _defaultValues$d );
  15155. this.setValues( parameters );
  15156. }
  15157. }
  15158. const _defaultValues$c = /*@__PURE__*/ new LineDashedMaterial();
  15159. /**
  15160. * Node material version of {@link LineDashedMaterial}.
  15161. *
  15162. * @augments NodeMaterial
  15163. */
  15164. class LineDashedNodeMaterial extends NodeMaterial {
  15165. static get type() {
  15166. return 'LineDashedNodeMaterial';
  15167. }
  15168. /**
  15169. * Constructs a new line dashed node material.
  15170. *
  15171. * @param {Object} [parameters] - The configuration parameter.
  15172. */
  15173. constructor( parameters ) {
  15174. super();
  15175. /**
  15176. * This flag can be used for type testing.
  15177. *
  15178. * @type {boolean}
  15179. * @readonly
  15180. * @default true
  15181. */
  15182. this.isLineDashedNodeMaterial = true;
  15183. this.setDefaultValues( _defaultValues$c );
  15184. /**
  15185. * The dash offset.
  15186. *
  15187. * @type {number}
  15188. * @default 0
  15189. */
  15190. this.dashOffset = 0;
  15191. /**
  15192. * The offset of dash materials is by default inferred from the `dashOffset`
  15193. * property. This node property allows to overwrite the default
  15194. * and define the offset with a node instead.
  15195. *
  15196. * If you don't want to overwrite the offset but modify the existing
  15197. * value instead, use {@link materialLineDashOffset}.
  15198. *
  15199. * @type {?Node<float>}
  15200. * @default null
  15201. */
  15202. this.offsetNode = null;
  15203. /**
  15204. * The scale of dash materials is by default inferred from the `scale`
  15205. * property. This node property allows to overwrite the default
  15206. * and define the scale with a node instead.
  15207. *
  15208. * If you don't want to overwrite the scale but modify the existing
  15209. * value instead, use {@link materialLineScale}.
  15210. *
  15211. * @type {?Node<float>}
  15212. * @default null
  15213. */
  15214. this.dashScaleNode = null;
  15215. /**
  15216. * The dash size of dash materials is by default inferred from the `dashSize`
  15217. * property. This node property allows to overwrite the default
  15218. * and define the dash size with a node instead.
  15219. *
  15220. * If you don't want to overwrite the dash size but modify the existing
  15221. * value instead, use {@link materialLineDashSize}.
  15222. *
  15223. * @type {?Node<float>}
  15224. * @default null
  15225. */
  15226. this.dashSizeNode = null;
  15227. /**
  15228. * The gap size of dash materials is by default inferred from the `gapSize`
  15229. * property. This node property allows to overwrite the default
  15230. * and define the gap size with a node instead.
  15231. *
  15232. * If you don't want to overwrite the gap size but modify the existing
  15233. * value instead, use {@link materialLineGapSize}.
  15234. *
  15235. * @type {?Node<float>}
  15236. * @default null
  15237. */
  15238. this.gapSizeNode = null;
  15239. this.setValues( parameters );
  15240. }
  15241. /**
  15242. * Setups the dash specific node variables.
  15243. *
  15244. * @param {NodeBuilder} builder - The current node builder.
  15245. */
  15246. setupVariants( /* builder */ ) {
  15247. const offsetNode = this.offsetNode ? float( this.offsetNode ) : materialLineDashOffset;
  15248. const dashScaleNode = this.dashScaleNode ? float( this.dashScaleNode ) : materialLineScale;
  15249. const dashSizeNode = this.dashSizeNode ? float( this.dashSizeNode ) : materialLineDashSize;
  15250. const gapSizeNode = this.gapSizeNode ? float( this.gapSizeNode ) : materialLineGapSize;
  15251. dashSize.assign( dashSizeNode );
  15252. gapSize.assign( gapSizeNode );
  15253. const vLineDistance = varying( attribute( 'lineDistance' ).mul( dashScaleNode ) );
  15254. const vLineDistanceOffset = offsetNode ? vLineDistance.add( offsetNode ) : vLineDistance;
  15255. vLineDistanceOffset.mod( dashSize.add( gapSize ) ).greaterThan( dashSize ).discard();
  15256. }
  15257. }
  15258. let _sharedFramebuffer = null;
  15259. /**
  15260. * `ViewportTextureNode` creates an internal texture for each node instance. This module
  15261. * shares a texture across all instances of `ViewportSharedTextureNode`. It should
  15262. * be the first choice when using data of the default/screen framebuffer for performance reasons.
  15263. *
  15264. * @augments ViewportTextureNode
  15265. */
  15266. class ViewportSharedTextureNode extends ViewportTextureNode {
  15267. static get type() {
  15268. return 'ViewportSharedTextureNode';
  15269. }
  15270. /**
  15271. * Constructs a new viewport shared texture node.
  15272. *
  15273. * @param {Node} [uvNode=screenUV] - The uv node.
  15274. * @param {?Node} [levelNode=null] - The level node.
  15275. */
  15276. constructor( uvNode = screenUV, levelNode = null ) {
  15277. if ( _sharedFramebuffer === null ) {
  15278. _sharedFramebuffer = new FramebufferTexture();
  15279. }
  15280. super( uvNode, levelNode, _sharedFramebuffer );
  15281. }
  15282. /**
  15283. * Overwritten so the method always returns the unique shared
  15284. * framebuffer texture.
  15285. *
  15286. * @return {FramebufferTexture} The shared framebuffer texture.
  15287. */
  15288. getTextureForReference() {
  15289. return _sharedFramebuffer;
  15290. }
  15291. updateReference() {
  15292. return this;
  15293. }
  15294. }
  15295. /**
  15296. * TSL function for creating a shared viewport texture node.
  15297. *
  15298. * @tsl
  15299. * @function
  15300. * @param {?Node} [uvNode=screenUV] - The uv node.
  15301. * @param {?Node} [levelNode=null] - The level node.
  15302. * @returns {ViewportSharedTextureNode}
  15303. */
  15304. const viewportSharedTexture = /*@__PURE__*/ nodeProxy( ViewportSharedTextureNode ).setParameterLength( 0, 2 );
  15305. const _defaultValues$b = /*@__PURE__*/ new LineDashedMaterial();
  15306. /**
  15307. * This node material can be used to render lines with a size larger than one
  15308. * by representing them as instanced meshes.
  15309. *
  15310. * @augments NodeMaterial
  15311. */
  15312. class Line2NodeMaterial extends NodeMaterial {
  15313. static get type() {
  15314. return 'Line2NodeMaterial';
  15315. }
  15316. /**
  15317. * Constructs a new node material for wide line rendering.
  15318. *
  15319. * @param {Object} [parameters={}] - The configuration parameter.
  15320. */
  15321. constructor( parameters = {} ) {
  15322. super();
  15323. /**
  15324. * This flag can be used for type testing.
  15325. *
  15326. * @type {boolean}
  15327. * @readonly
  15328. * @default true
  15329. */
  15330. this.isLine2NodeMaterial = true;
  15331. this.setDefaultValues( _defaultValues$b );
  15332. /**
  15333. * Whether vertex colors should be used or not.
  15334. *
  15335. * @type {boolean}
  15336. * @default false
  15337. */
  15338. this.useColor = parameters.vertexColors;
  15339. /**
  15340. * The dash offset.
  15341. *
  15342. * @type {number}
  15343. * @default 0
  15344. */
  15345. this.dashOffset = 0;
  15346. /**
  15347. * Defines the lines color.
  15348. *
  15349. * @type {?Node<vec3>}
  15350. * @default null
  15351. */
  15352. this.lineColorNode = null;
  15353. /**
  15354. * Defines the offset.
  15355. *
  15356. * @type {?Node<float>}
  15357. * @default null
  15358. */
  15359. this.offsetNode = null;
  15360. /**
  15361. * Defines the dash scale.
  15362. *
  15363. * @type {?Node<float>}
  15364. * @default null
  15365. */
  15366. this.dashScaleNode = null;
  15367. /**
  15368. * Defines the dash size.
  15369. *
  15370. * @type {?Node<float>}
  15371. * @default null
  15372. */
  15373. this.dashSizeNode = null;
  15374. /**
  15375. * Defines the gap size.
  15376. *
  15377. * @type {?Node<float>}
  15378. * @default null
  15379. */
  15380. this.gapSizeNode = null;
  15381. /**
  15382. * Blending is set to `NoBlending` since transparency
  15383. * is not supported, yet.
  15384. *
  15385. * @type {number}
  15386. * @default 0
  15387. */
  15388. this.blending = NoBlending;
  15389. this._useDash = parameters.dashed;
  15390. this._useAlphaToCoverage = true;
  15391. this._useWorldUnits = false;
  15392. this.setValues( parameters );
  15393. }
  15394. /**
  15395. * Setups the vertex and fragment stage of this node material.
  15396. *
  15397. * @param {NodeBuilder} builder - The current node builder.
  15398. */
  15399. setup( builder ) {
  15400. const { renderer } = builder;
  15401. const useAlphaToCoverage = this._useAlphaToCoverage;
  15402. const useColor = this.useColor;
  15403. const useDash = this._useDash;
  15404. const useWorldUnits = this._useWorldUnits;
  15405. const trimSegment = Fn( ( { start, end } ) => {
  15406. const a = cameraProjectionMatrix.element( 2 ).element( 2 ); // 3nd entry in 3th column
  15407. const b = cameraProjectionMatrix.element( 3 ).element( 2 ); // 3nd entry in 4th column
  15408. const nearEstimate = b.mul( -0.5 ).div( a );
  15409. const alpha = nearEstimate.sub( start.z ).div( end.z.sub( start.z ) );
  15410. return vec4( mix( start.xyz, end.xyz, alpha ), end.w );
  15411. } ).setLayout( {
  15412. name: 'trimSegment',
  15413. type: 'vec4',
  15414. inputs: [
  15415. { name: 'start', type: 'vec4' },
  15416. { name: 'end', type: 'vec4' }
  15417. ]
  15418. } );
  15419. this.vertexNode = Fn( () => {
  15420. const instanceStart = attribute( 'instanceStart' );
  15421. const instanceEnd = attribute( 'instanceEnd' );
  15422. // camera space
  15423. const start = vec4( modelViewMatrix.mul( vec4( instanceStart, 1.0 ) ) ).toVar( 'start' );
  15424. const end = vec4( modelViewMatrix.mul( vec4( instanceEnd, 1.0 ) ) ).toVar( 'end' );
  15425. if ( useDash ) {
  15426. const dashScaleNode = this.dashScaleNode ? float( this.dashScaleNode ) : materialLineScale;
  15427. const offsetNode = this.offsetNode ? float( this.offsetNode ) : materialLineDashOffset;
  15428. const instanceDistanceStart = attribute( 'instanceDistanceStart' );
  15429. const instanceDistanceEnd = attribute( 'instanceDistanceEnd' );
  15430. let lineDistance = positionGeometry.y.lessThan( 0.5 ).select( dashScaleNode.mul( instanceDistanceStart ), dashScaleNode.mul( instanceDistanceEnd ) );
  15431. lineDistance = lineDistance.add( offsetNode );
  15432. varyingProperty( 'float', 'lineDistance' ).assign( lineDistance );
  15433. }
  15434. if ( useWorldUnits ) {
  15435. varyingProperty( 'vec3', 'worldStart' ).assign( start.xyz );
  15436. varyingProperty( 'vec3', 'worldEnd' ).assign( end.xyz );
  15437. }
  15438. const aspect = viewport.z.div( viewport.w );
  15439. // special case for perspective projection, and segments that terminate either in, or behind, the camera plane
  15440. // clearly the gpu firmware has a way of addressing this issue when projecting into ndc space
  15441. // but we need to perform ndc-space calculations in the shader, so we must address this issue directly
  15442. // perhaps there is a more elegant solution -- WestLangley
  15443. const perspective = cameraProjectionMatrix.element( 2 ).element( 3 ).equal( -1 ); // 4th entry in the 3rd column
  15444. If( perspective, () => {
  15445. If( start.z.lessThan( 0.0 ).and( end.z.greaterThan( 0.0 ) ), () => {
  15446. end.assign( trimSegment( { start: start, end: end } ) );
  15447. } ).ElseIf( end.z.lessThan( 0.0 ).and( start.z.greaterThanEqual( 0.0 ) ), () => {
  15448. start.assign( trimSegment( { start: end, end: start } ) );
  15449. } );
  15450. } );
  15451. // clip space
  15452. const clipStart = cameraProjectionMatrix.mul( start );
  15453. const clipEnd = cameraProjectionMatrix.mul( end );
  15454. // ndc space
  15455. const ndcStart = clipStart.xyz.div( clipStart.w );
  15456. const ndcEnd = clipEnd.xyz.div( clipEnd.w );
  15457. // direction
  15458. const dir = ndcEnd.xy.sub( ndcStart.xy ).toVar();
  15459. // account for clip-space aspect ratio
  15460. dir.x.assign( dir.x.mul( aspect ) );
  15461. dir.assign( dir.normalize() );
  15462. const clip = vec4().toVar();
  15463. if ( useWorldUnits ) {
  15464. // get the offset direction as perpendicular to the view vector
  15465. const worldDir = end.xyz.sub( start.xyz ).normalize();
  15466. const tmpFwd = mix( start.xyz, end.xyz, 0.5 ).normalize();
  15467. const worldUp = worldDir.cross( tmpFwd ).normalize();
  15468. const worldFwd = worldDir.cross( worldUp );
  15469. const worldPos = varyingProperty( 'vec4', 'worldPos' );
  15470. worldPos.assign( positionGeometry.y.lessThan( 0.5 ).select( start, end ) );
  15471. // height offset
  15472. const hw = materialLineWidth.mul( 0.5 );
  15473. worldPos.addAssign( vec4( positionGeometry.x.lessThan( 0.0 ).select( worldUp.mul( hw ), worldUp.mul( hw ).negate() ), 0 ) );
  15474. // don't extend the line if we're rendering dashes because we
  15475. // won't be rendering the endcaps
  15476. if ( ! useDash ) {
  15477. // cap extension
  15478. worldPos.addAssign( vec4( positionGeometry.y.lessThan( 0.5 ).select( worldDir.mul( hw ).negate(), worldDir.mul( hw ) ), 0 ) );
  15479. // add width to the box
  15480. worldPos.addAssign( vec4( worldFwd.mul( hw ), 0 ) );
  15481. // endcaps
  15482. If( positionGeometry.y.greaterThan( 1.0 ).or( positionGeometry.y.lessThan( 0.0 ) ), () => {
  15483. worldPos.subAssign( vec4( worldFwd.mul( 2.0 ).mul( hw ), 0 ) );
  15484. } );
  15485. }
  15486. // project the worldpos
  15487. clip.assign( cameraProjectionMatrix.mul( worldPos ) );
  15488. // shift the depth of the projected points so the line
  15489. // segments overlap neatly
  15490. const clipPose = vec3().toVar();
  15491. clipPose.assign( positionGeometry.y.lessThan( 0.5 ).select( ndcStart, ndcEnd ) );
  15492. clip.z.assign( clipPose.z.mul( clip.w ) );
  15493. } else {
  15494. const offset = vec2( dir.y, dir.x.negate() ).toVar( 'offset' );
  15495. // undo aspect ratio adjustment
  15496. dir.x.assign( dir.x.div( aspect ) );
  15497. offset.x.assign( offset.x.div( aspect ) );
  15498. // sign flip
  15499. offset.assign( positionGeometry.x.lessThan( 0.0 ).select( offset.negate(), offset ) );
  15500. // endcaps
  15501. If( positionGeometry.y.lessThan( 0.0 ), () => {
  15502. offset.assign( offset.sub( dir ) );
  15503. } ).ElseIf( positionGeometry.y.greaterThan( 1.0 ), () => {
  15504. offset.assign( offset.add( dir ) );
  15505. } );
  15506. // adjust for linewidth
  15507. offset.assign( offset.mul( materialLineWidth ) );
  15508. // adjust for clip-space to screen-space conversion // maybe resolution should be based on viewport ...
  15509. offset.assign( offset.div( viewport.w.div( screenDPR ) ) );
  15510. // select end
  15511. clip.assign( positionGeometry.y.lessThan( 0.5 ).select( clipStart, clipEnd ) );
  15512. // back to clip space
  15513. offset.assign( offset.mul( clip.w ) );
  15514. clip.assign( clip.add( vec4( offset, 0, 0 ) ) );
  15515. }
  15516. return clip;
  15517. } )();
  15518. const closestLineToLine = Fn( ( { p1, p2, p3, p4 } ) => {
  15519. const p13 = p1.sub( p3 );
  15520. const p43 = p4.sub( p3 );
  15521. const p21 = p2.sub( p1 );
  15522. const d1343 = p13.dot( p43 );
  15523. const d4321 = p43.dot( p21 );
  15524. const d1321 = p13.dot( p21 );
  15525. const d4343 = p43.dot( p43 );
  15526. const d2121 = p21.dot( p21 );
  15527. const denom = d2121.mul( d4343 ).sub( d4321.mul( d4321 ) );
  15528. const numer = d1343.mul( d4321 ).sub( d1321.mul( d4343 ) );
  15529. const mua = numer.div( denom ).clamp();
  15530. const mub = d1343.add( d4321.mul( mua ) ).div( d4343 ).clamp();
  15531. return vec2( mua, mub );
  15532. } );
  15533. this.colorNode = Fn( () => {
  15534. const vUv = uv$1();
  15535. if ( useDash ) {
  15536. const dashSizeNode = this.dashSizeNode ? float( this.dashSizeNode ) : materialLineDashSize;
  15537. const gapSizeNode = this.gapSizeNode ? float( this.gapSizeNode ) : materialLineGapSize;
  15538. dashSize.assign( dashSizeNode );
  15539. gapSize.assign( gapSizeNode );
  15540. const vLineDistance = varyingProperty( 'float', 'lineDistance' );
  15541. vUv.y.lessThan( -1 ).or( vUv.y.greaterThan( 1.0 ) ).discard(); // discard endcaps
  15542. vLineDistance.mod( dashSize.add( gapSize ) ).greaterThan( dashSize ).discard(); // todo - FIX
  15543. }
  15544. const alpha = float( 1 ).toVar( 'alpha' );
  15545. if ( useWorldUnits ) {
  15546. const worldStart = varyingProperty( 'vec3', 'worldStart' );
  15547. const worldEnd = varyingProperty( 'vec3', 'worldEnd' );
  15548. // Find the closest points on the view ray and the line segment
  15549. const rayEnd = varyingProperty( 'vec4', 'worldPos' ).xyz.normalize().mul( 1e5 );
  15550. const lineDir = worldEnd.sub( worldStart );
  15551. const params = closestLineToLine( { p1: worldStart, p2: worldEnd, p3: vec3( 0.0, 0.0, 0.0 ), p4: rayEnd } );
  15552. const p1 = worldStart.add( lineDir.mul( params.x ) );
  15553. const p2 = rayEnd.mul( params.y );
  15554. const delta = p1.sub( p2 );
  15555. const len = delta.length();
  15556. const norm = len.div( materialLineWidth );
  15557. if ( ! useDash ) {
  15558. if ( useAlphaToCoverage && renderer.currentSamples > 0 ) {
  15559. const dnorm = norm.fwidth();
  15560. alpha.assign( smoothstep( dnorm.negate().add( 0.5 ), dnorm.add( 0.5 ), norm ).oneMinus() );
  15561. } else {
  15562. norm.greaterThan( 0.5 ).discard();
  15563. }
  15564. }
  15565. } else {
  15566. // round endcaps
  15567. if ( useAlphaToCoverage && renderer.currentSamples > 0 ) {
  15568. const a = vUv.x;
  15569. const b = vUv.y.greaterThan( 0.0 ).select( vUv.y.sub( 1.0 ), vUv.y.add( 1.0 ) );
  15570. const len2 = a.mul( a ).add( b.mul( b ) );
  15571. const dlen = float( len2.fwidth() ).toVar( 'dlen' );
  15572. If( vUv.y.abs().greaterThan( 1.0 ), () => {
  15573. alpha.assign( smoothstep( dlen.oneMinus(), dlen.add( 1 ), len2 ).oneMinus() );
  15574. } );
  15575. } else {
  15576. If( vUv.y.abs().greaterThan( 1.0 ), () => {
  15577. const a = vUv.x;
  15578. const b = vUv.y.greaterThan( 0.0 ).select( vUv.y.sub( 1.0 ), vUv.y.add( 1.0 ) );
  15579. const len2 = a.mul( a ).add( b.mul( b ) );
  15580. len2.greaterThan( 1.0 ).discard();
  15581. } );
  15582. }
  15583. }
  15584. let lineColorNode;
  15585. if ( this.lineColorNode ) {
  15586. lineColorNode = this.lineColorNode;
  15587. } else {
  15588. if ( useColor ) {
  15589. const instanceColorStart = attribute( 'instanceColorStart' );
  15590. const instanceColorEnd = attribute( 'instanceColorEnd' );
  15591. const instanceColor = positionGeometry.y.lessThan( 0.5 ).select( instanceColorStart, instanceColorEnd );
  15592. lineColorNode = instanceColor.mul( materialColor );
  15593. } else {
  15594. lineColorNode = materialColor;
  15595. }
  15596. }
  15597. return vec4( lineColorNode, alpha );
  15598. } )();
  15599. if ( this.transparent ) {
  15600. const opacityNode = this.opacityNode ? float( this.opacityNode ) : materialOpacity;
  15601. this.outputNode = vec4( this.colorNode.rgb.mul( opacityNode ).add( viewportSharedTexture().rgb.mul( opacityNode.oneMinus() ) ), this.colorNode.a );
  15602. }
  15603. super.setup( builder );
  15604. }
  15605. /**
  15606. * Whether the lines should sized in world units or not.
  15607. * When set to `false` the unit is pixel.
  15608. *
  15609. * @type {boolean}
  15610. * @default false
  15611. */
  15612. get worldUnits() {
  15613. return this._useWorldUnits;
  15614. }
  15615. set worldUnits( value ) {
  15616. if ( this._useWorldUnits !== value ) {
  15617. this._useWorldUnits = value;
  15618. this.needsUpdate = true;
  15619. }
  15620. }
  15621. /**
  15622. * Whether the lines should be dashed or not.
  15623. *
  15624. * @type {boolean}
  15625. * @default false
  15626. */
  15627. get dashed() {
  15628. return this._useDash;
  15629. }
  15630. set dashed( value ) {
  15631. if ( this._useDash !== value ) {
  15632. this._useDash = value;
  15633. this.needsUpdate = true;
  15634. }
  15635. }
  15636. /**
  15637. * Whether alpha to coverage should be used or not.
  15638. *
  15639. * @type {boolean}
  15640. * @default true
  15641. */
  15642. get alphaToCoverage() {
  15643. return this._useAlphaToCoverage;
  15644. }
  15645. set alphaToCoverage( value ) {
  15646. if ( this._useAlphaToCoverage !== value ) {
  15647. this._useAlphaToCoverage = value;
  15648. this.needsUpdate = true;
  15649. }
  15650. }
  15651. }
  15652. const _defaultValues$a = /*@__PURE__*/ new MeshNormalMaterial();
  15653. /**
  15654. * Node material version of {@link MeshNormalMaterial}.
  15655. *
  15656. * @augments NodeMaterial
  15657. */
  15658. class MeshNormalNodeMaterial extends NodeMaterial {
  15659. static get type() {
  15660. return 'MeshNormalNodeMaterial';
  15661. }
  15662. /**
  15663. * Constructs a new mesh normal node material.
  15664. *
  15665. * @param {Object} [parameters] - The configuration parameter.
  15666. */
  15667. constructor( parameters ) {
  15668. super();
  15669. /**
  15670. * This flag can be used for type testing.
  15671. *
  15672. * @type {boolean}
  15673. * @readonly
  15674. * @default true
  15675. */
  15676. this.isMeshNormalNodeMaterial = true;
  15677. this.setDefaultValues( _defaultValues$a );
  15678. this.setValues( parameters );
  15679. }
  15680. /**
  15681. * Overwrites the default implementation by computing the diffuse color
  15682. * based on the normal data.
  15683. */
  15684. setupDiffuseColor() {
  15685. const opacityNode = this.opacityNode ? float( this.opacityNode ) : materialOpacity;
  15686. // By convention, a normal packed to RGB is in sRGB color space. Convert it to working color space.
  15687. diffuseColor.assign( colorSpaceToWorking( vec4( directionToColor( normalView ), opacityNode ), SRGBColorSpace ) );
  15688. }
  15689. }
  15690. /**
  15691. * TSL function for creating an equirect uv node.
  15692. *
  15693. * Can be used to compute texture coordinates for projecting an
  15694. * equirectangular texture onto a mesh for using it as the scene's
  15695. * background.
  15696. *
  15697. * ```js
  15698. * scene.backgroundNode = texture( equirectTexture, equirectUV() );
  15699. * ```
  15700. *
  15701. * @tsl
  15702. * @function
  15703. * @param {?Node<vec3>} [dirNode=positionWorldDirection] - A direction vector for sampling which is by default `positionWorldDirection`.
  15704. * @returns {Node<vec2>}
  15705. */
  15706. const equirectUV = /*@__PURE__*/ Fn( ( [ dir = positionWorldDirection ] ) => {
  15707. const u = dir.z.atan( dir.x ).mul( 1 / ( Math.PI * 2 ) ).add( 0.5 );
  15708. const v = dir.y.clamp( -1, 1.0 ).asin().mul( 1 / Math.PI ).add( 0.5 );
  15709. return vec2( u, v );
  15710. } );
  15711. // @TODO: Consider rename WebGLCubeRenderTarget to just CubeRenderTarget
  15712. /**
  15713. * This class represents a cube render target. It is a special version
  15714. * of `WebGLCubeRenderTarget` which is compatible with `WebGPURenderer`.
  15715. *
  15716. * @augments WebGLCubeRenderTarget
  15717. */
  15718. class CubeRenderTarget extends WebGLCubeRenderTarget {
  15719. /**
  15720. * Constructs a new cube render target.
  15721. *
  15722. * @param {number} [size=1] - The size of the render target.
  15723. * @param {RenderTarget~Options} [options] - The configuration object.
  15724. */
  15725. constructor( size = 1, options = {} ) {
  15726. super( size, options );
  15727. /**
  15728. * This flag can be used for type testing.
  15729. *
  15730. * @type {boolean}
  15731. * @readonly
  15732. * @default true
  15733. */
  15734. this.isCubeRenderTarget = true;
  15735. }
  15736. /**
  15737. * Converts the given equirectangular texture to a cube map.
  15738. *
  15739. * @param {Renderer} renderer - The renderer.
  15740. * @param {Texture} texture - The equirectangular texture.
  15741. * @return {CubeRenderTarget} A reference to this cube render target.
  15742. */
  15743. fromEquirectangularTexture( renderer, texture$1 ) {
  15744. const currentMinFilter = texture$1.minFilter;
  15745. const currentGenerateMipmaps = texture$1.generateMipmaps;
  15746. texture$1.generateMipmaps = true;
  15747. this.texture.type = texture$1.type;
  15748. this.texture.colorSpace = texture$1.colorSpace;
  15749. this.texture.generateMipmaps = texture$1.generateMipmaps;
  15750. this.texture.minFilter = texture$1.minFilter;
  15751. this.texture.magFilter = texture$1.magFilter;
  15752. const geometry = new BoxGeometry( 5, 5, 5 );
  15753. const uvNode = equirectUV( positionWorldDirection );
  15754. const material = new NodeMaterial();
  15755. material.colorNode = texture( texture$1, uvNode, 0 );
  15756. material.side = BackSide;
  15757. material.blending = NoBlending;
  15758. const mesh = new Mesh( geometry, material );
  15759. const scene = new Scene();
  15760. scene.add( mesh );
  15761. // Avoid blurred poles
  15762. if ( texture$1.minFilter === LinearMipmapLinearFilter ) texture$1.minFilter = LinearFilter;
  15763. const camera = new CubeCamera( 1, 10, this );
  15764. const currentMRT = renderer.getMRT();
  15765. renderer.setMRT( null );
  15766. camera.update( renderer, scene );
  15767. renderer.setMRT( currentMRT );
  15768. texture$1.minFilter = currentMinFilter;
  15769. texture$1.currentGenerateMipmaps = currentGenerateMipmaps;
  15770. mesh.geometry.dispose();
  15771. mesh.material.dispose();
  15772. return this;
  15773. }
  15774. }
  15775. const _cache$1 = new WeakMap();
  15776. /**
  15777. * This node can be used to automatically convert environment maps in the
  15778. * equirectangular format into the cube map format.
  15779. *
  15780. * @augments TempNode
  15781. */
  15782. class CubeMapNode extends TempNode {
  15783. static get type() {
  15784. return 'CubeMapNode';
  15785. }
  15786. /**
  15787. * Constructs a new cube map node.
  15788. *
  15789. * @param {Node} envNode - The node representing the environment map.
  15790. */
  15791. constructor( envNode ) {
  15792. super( 'vec3' );
  15793. /**
  15794. * The node representing the environment map.
  15795. *
  15796. * @type {Node}
  15797. */
  15798. this.envNode = envNode;
  15799. /**
  15800. * A reference to the internal cube texture.
  15801. *
  15802. * @private
  15803. * @type {?CubeTexture}
  15804. * @default null
  15805. */
  15806. this._cubeTexture = null;
  15807. /**
  15808. * A reference to the internal cube texture node.
  15809. *
  15810. * @private
  15811. * @type {CubeTextureNode}
  15812. */
  15813. this._cubeTextureNode = cubeTexture( null );
  15814. const defaultTexture = new CubeTexture();
  15815. defaultTexture.isRenderTargetTexture = true;
  15816. /**
  15817. * A default cube texture that acts as a placeholder.
  15818. * It is used when the conversion from equirectangular to cube
  15819. * map has not finished yet for a given texture.
  15820. *
  15821. * @private
  15822. * @type {CubeTexture}
  15823. */
  15824. this._defaultTexture = defaultTexture;
  15825. /**
  15826. * The `updateBeforeType` is set to `NodeUpdateType.RENDER` since the node updates
  15827. * the texture once per render in its {@link CubeMapNode#updateBefore} method.
  15828. *
  15829. * @type {string}
  15830. * @default 'render'
  15831. */
  15832. this.updateBeforeType = NodeUpdateType.RENDER;
  15833. }
  15834. updateBefore( frame ) {
  15835. const { renderer, material } = frame;
  15836. const envNode = this.envNode;
  15837. if ( envNode.isTextureNode || envNode.isMaterialReferenceNode ) {
  15838. const texture = ( envNode.isTextureNode ) ? envNode.value : material[ envNode.property ];
  15839. if ( texture && texture.isTexture ) {
  15840. const mapping = texture.mapping;
  15841. if ( mapping === EquirectangularReflectionMapping || mapping === EquirectangularRefractionMapping ) {
  15842. // check for converted cubemap map
  15843. if ( _cache$1.has( texture ) ) {
  15844. const cubeMap = _cache$1.get( texture );
  15845. mapTextureMapping( cubeMap, texture.mapping );
  15846. this._cubeTexture = cubeMap;
  15847. } else {
  15848. // create cube map from equirectangular map
  15849. const image = texture.image;
  15850. if ( isEquirectangularMapReady$1( image ) ) {
  15851. const renderTarget = new CubeRenderTarget( image.height );
  15852. renderTarget.fromEquirectangularTexture( renderer, texture );
  15853. mapTextureMapping( renderTarget.texture, texture.mapping );
  15854. this._cubeTexture = renderTarget.texture;
  15855. _cache$1.set( texture, renderTarget.texture );
  15856. texture.addEventListener( 'dispose', onTextureDispose );
  15857. } else {
  15858. // default cube texture as fallback when equirectangular texture is not yet loaded
  15859. this._cubeTexture = this._defaultTexture;
  15860. }
  15861. }
  15862. //
  15863. this._cubeTextureNode.value = this._cubeTexture;
  15864. } else {
  15865. // envNode already refers to a cube map
  15866. this._cubeTextureNode = this.envNode;
  15867. }
  15868. }
  15869. }
  15870. }
  15871. setup( builder ) {
  15872. this.updateBefore( builder );
  15873. return this._cubeTextureNode;
  15874. }
  15875. }
  15876. /**
  15877. * Returns true if the given equirectangular image has been fully loaded
  15878. * and is ready for further processing.
  15879. *
  15880. * @private
  15881. * @param {Image} image - The equirectangular image to check.
  15882. * @return {boolean} Whether the image is ready or not.
  15883. */
  15884. function isEquirectangularMapReady$1( image ) {
  15885. if ( image === null || image === undefined ) return false;
  15886. return image.height > 0;
  15887. }
  15888. /**
  15889. * This function is executed when `dispose()` is called on the equirectangular
  15890. * texture. In this case, the generated cube map with its render target
  15891. * is deleted as well.
  15892. *
  15893. * @private
  15894. * @param {Object} event - The event object.
  15895. */
  15896. function onTextureDispose( event ) {
  15897. const texture = event.target;
  15898. texture.removeEventListener( 'dispose', onTextureDispose );
  15899. const renderTarget = _cache$1.get( texture );
  15900. if ( renderTarget !== undefined ) {
  15901. _cache$1.delete( texture );
  15902. renderTarget.dispose();
  15903. }
  15904. }
  15905. /**
  15906. * This function makes sure the generated cube map uses the correct
  15907. * texture mapping that corresponds to the equirectangular original.
  15908. *
  15909. * @private
  15910. * @param {Texture} texture - The cube texture.
  15911. * @param {number} mapping - The original texture mapping.
  15912. */
  15913. function mapTextureMapping( texture, mapping ) {
  15914. if ( mapping === EquirectangularReflectionMapping ) {
  15915. texture.mapping = CubeReflectionMapping;
  15916. } else if ( mapping === EquirectangularRefractionMapping ) {
  15917. texture.mapping = CubeRefractionMapping;
  15918. }
  15919. }
  15920. /**
  15921. * TSL function for creating a cube map node.
  15922. *
  15923. * @tsl
  15924. * @function
  15925. * @param {Node} envNode - The node representing the environment map.
  15926. * @returns {CubeMapNode}
  15927. */
  15928. const cubeMapNode = /*@__PURE__*/ nodeProxy( CubeMapNode ).setParameterLength( 1 );
  15929. /**
  15930. * Represents a basic model for Image-based lighting (IBL). The environment
  15931. * is defined via environment maps in the equirectangular or cube map format.
  15932. * `BasicEnvironmentNode` is intended for non-PBR materials like {@link MeshBasicNodeMaterial}
  15933. * or {@link MeshPhongNodeMaterial}.
  15934. *
  15935. * @augments LightingNode
  15936. */
  15937. class BasicEnvironmentNode extends LightingNode {
  15938. static get type() {
  15939. return 'BasicEnvironmentNode';
  15940. }
  15941. /**
  15942. * Constructs a new basic environment node.
  15943. *
  15944. * @param {Node} [envNode=null] - A node representing the environment.
  15945. */
  15946. constructor( envNode = null ) {
  15947. super();
  15948. /**
  15949. * A node representing the environment.
  15950. *
  15951. * @type {Node}
  15952. * @default null
  15953. */
  15954. this.envNode = envNode;
  15955. }
  15956. setup( builder ) {
  15957. // environment property is used in the finish() method of BasicLightingModel
  15958. builder.context.environment = cubeMapNode( this.envNode );
  15959. }
  15960. }
  15961. /**
  15962. * A specific version of {@link IrradianceNode} that is only relevant
  15963. * for {@link MeshBasicNodeMaterial}. Since the material is unlit, it
  15964. * requires a special scaling factor for the light map.
  15965. *
  15966. * @augments LightingNode
  15967. */
  15968. class BasicLightMapNode extends LightingNode {
  15969. static get type() {
  15970. return 'BasicLightMapNode';
  15971. }
  15972. /**
  15973. * Constructs a new basic light map node.
  15974. *
  15975. * @param {?Node<vec3>} [lightMapNode=null] - The light map node.
  15976. */
  15977. constructor( lightMapNode = null ) {
  15978. super();
  15979. /**
  15980. * The light map node.
  15981. *
  15982. * @type {?Node<vec3>}
  15983. */
  15984. this.lightMapNode = lightMapNode;
  15985. }
  15986. setup( builder ) {
  15987. // irradianceLightMap property is used in the indirectDiffuse() method of BasicLightingModel
  15988. const RECIPROCAL_PI = float( 1 / Math.PI );
  15989. builder.context.irradianceLightMap = this.lightMapNode.mul( RECIPROCAL_PI );
  15990. }
  15991. }
  15992. /**
  15993. * Abstract class for implementing lighting models. The module defines
  15994. * multiple methods that concrete lighting models can implement. These
  15995. * methods are executed at different points during the light evaluation
  15996. * process.
  15997. */
  15998. class LightingModel {
  15999. /**
  16000. * This method is intended for setting up lighting model and context data
  16001. * which are later used in the evaluation process.
  16002. *
  16003. * @abstract
  16004. * @param {NodeBuilder} builder - The current node builder.
  16005. */
  16006. start( builder ) {
  16007. // lights ( direct )
  16008. builder.lightsNode.setupLights( builder, builder.lightsNode.getLightNodes( builder ) );
  16009. // indirect
  16010. this.indirect( builder );
  16011. }
  16012. /**
  16013. * This method is intended for executing final tasks like final updates
  16014. * to the outgoing light.
  16015. *
  16016. * @abstract
  16017. * @param {NodeBuilder} builder - The current node builder.
  16018. */
  16019. finish( /*builder*/ ) { }
  16020. /**
  16021. * This method is intended for implementing the direct light term and
  16022. * executed during the build process of directional, point and spot light nodes.
  16023. *
  16024. * @abstract
  16025. * @param {Object} lightData - The light data.
  16026. * @param {NodeBuilder} builder - The current node builder.
  16027. */
  16028. direct( /*lightData, builder*/ ) { }
  16029. /**
  16030. * This method is intended for implementing the direct light term for
  16031. * rect area light nodes.
  16032. *
  16033. * @abstract
  16034. * @param {Object} lightData - The light data.
  16035. * @param {NodeBuilder} builder - The current node builder.
  16036. */
  16037. directRectArea( /*lightData, builder*/ ) {}
  16038. /**
  16039. * This method is intended for implementing the indirect light term.
  16040. *
  16041. * @abstract
  16042. * @param {NodeBuilder} builder - The current node builder.
  16043. */
  16044. indirect( /*builder*/ ) { }
  16045. /**
  16046. * This method is intended for implementing the ambient occlusion term.
  16047. * Unlike other methods, this method must be called manually by the lighting
  16048. * model in its indirect term.
  16049. *
  16050. * @abstract
  16051. * @param {NodeBuilder} builder - The current node builder.
  16052. */
  16053. ambientOcclusion( /*input, stack, builder*/ ) { }
  16054. }
  16055. /**
  16056. * Represents the lighting model for unlit materials. The only light contribution
  16057. * is baked indirect lighting modulated with ambient occlusion and the material's
  16058. * diffuse color. Environment mapping is supported. Used in {@link MeshBasicNodeMaterial}.
  16059. *
  16060. * @augments LightingModel
  16061. */
  16062. class BasicLightingModel extends LightingModel {
  16063. /**
  16064. * Constructs a new basic lighting model.
  16065. */
  16066. constructor() {
  16067. super();
  16068. }
  16069. /**
  16070. * Implements the baked indirect lighting with its modulation.
  16071. *
  16072. * @param {NodeBuilder} builder - The current node builder.
  16073. */
  16074. indirect( { context } ) {
  16075. const ambientOcclusion = context.ambientOcclusion;
  16076. const reflectedLight = context.reflectedLight;
  16077. const irradianceLightMap = context.irradianceLightMap;
  16078. reflectedLight.indirectDiffuse.assign( vec4( 0.0 ) );
  16079. // accumulation (baked indirect lighting only)
  16080. if ( irradianceLightMap ) {
  16081. reflectedLight.indirectDiffuse.addAssign( irradianceLightMap );
  16082. } else {
  16083. reflectedLight.indirectDiffuse.addAssign( vec4( 1.0, 1.0, 1.0, 0.0 ) );
  16084. }
  16085. // modulation
  16086. reflectedLight.indirectDiffuse.mulAssign( ambientOcclusion );
  16087. reflectedLight.indirectDiffuse.mulAssign( diffuseColor.rgb );
  16088. }
  16089. /**
  16090. * Implements the environment mapping.
  16091. *
  16092. * @param {NodeBuilder} builder - The current node builder.
  16093. */
  16094. finish( builder ) {
  16095. const { material, context } = builder;
  16096. const outgoingLight = context.outgoingLight;
  16097. const envNode = builder.context.environment;
  16098. if ( envNode ) {
  16099. switch ( material.combine ) {
  16100. case MultiplyOperation:
  16101. outgoingLight.rgb.assign( mix( outgoingLight.rgb, outgoingLight.rgb.mul( envNode.rgb ), materialSpecularStrength.mul( materialReflectivity ) ) );
  16102. break;
  16103. case MixOperation:
  16104. outgoingLight.rgb.assign( mix( outgoingLight.rgb, envNode.rgb, materialSpecularStrength.mul( materialReflectivity ) ) );
  16105. break;
  16106. case AddOperation:
  16107. outgoingLight.rgb.addAssign( envNode.rgb.mul( materialSpecularStrength.mul( materialReflectivity ) ) );
  16108. break;
  16109. default:
  16110. warn( 'BasicLightingModel: Unsupported .combine value:', material.combine );
  16111. break;
  16112. }
  16113. }
  16114. }
  16115. }
  16116. const _defaultValues$9 = /*@__PURE__*/ new MeshBasicMaterial();
  16117. /**
  16118. * Node material version of {@link MeshBasicMaterial}.
  16119. *
  16120. * @augments NodeMaterial
  16121. */
  16122. class MeshBasicNodeMaterial extends NodeMaterial {
  16123. static get type() {
  16124. return 'MeshBasicNodeMaterial';
  16125. }
  16126. /**
  16127. * Constructs a new mesh basic node material.
  16128. *
  16129. * @param {Object} [parameters] - The configuration parameter.
  16130. */
  16131. constructor( parameters ) {
  16132. super();
  16133. /**
  16134. * This flag can be used for type testing.
  16135. *
  16136. * @type {boolean}
  16137. * @readonly
  16138. * @default true
  16139. */
  16140. this.isMeshBasicNodeMaterial = true;
  16141. /**
  16142. * Although the basic material is by definition unlit, we set
  16143. * this property to `true` since we use a lighting model to compute
  16144. * the outgoing light of the fragment shader.
  16145. *
  16146. * @type {boolean}
  16147. * @default true
  16148. */
  16149. this.lights = true;
  16150. this.setDefaultValues( _defaultValues$9 );
  16151. this.setValues( parameters );
  16152. }
  16153. /**
  16154. * Basic materials are not affected by normal and bump maps so we
  16155. * return by default {@link normalViewGeometry}.
  16156. *
  16157. * @return {Node<vec3>} The normal node.
  16158. */
  16159. setupNormal() {
  16160. return directionToFaceDirection( normalViewGeometry ); // see #28839
  16161. }
  16162. /**
  16163. * Overwritten since this type of material uses {@link BasicEnvironmentNode}
  16164. * to implement the default environment mapping.
  16165. *
  16166. * @param {NodeBuilder} builder - The current node builder.
  16167. * @return {?BasicEnvironmentNode<vec3>} The environment node.
  16168. */
  16169. setupEnvironment( builder ) {
  16170. const envNode = super.setupEnvironment( builder );
  16171. return envNode ? new BasicEnvironmentNode( envNode ) : null;
  16172. }
  16173. /**
  16174. * This method must be overwritten since light maps are evaluated
  16175. * with a special scaling factor for basic materials.
  16176. *
  16177. * @param {NodeBuilder} builder - The current node builder.
  16178. * @return {?BasicLightMapNode<vec3>} The light map node.
  16179. */
  16180. setupLightMap( builder ) {
  16181. let node = null;
  16182. if ( builder.material.lightMap ) {
  16183. node = new BasicLightMapNode( materialLightMap );
  16184. }
  16185. return node;
  16186. }
  16187. /**
  16188. * The material overwrites this method because `lights` is set to `true` but
  16189. * we still want to return the diffuse color as the outgoing light.
  16190. *
  16191. * @return {Node<vec3>} The outgoing light node.
  16192. */
  16193. setupOutgoingLight() {
  16194. return diffuseColor.rgb;
  16195. }
  16196. /**
  16197. * Setups the lighting model.
  16198. *
  16199. * @return {BasicLightingModel} The lighting model.
  16200. */
  16201. setupLightingModel() {
  16202. return new BasicLightingModel();
  16203. }
  16204. }
  16205. const F_Schlick = /*@__PURE__*/ Fn( ( { f0, f90, dotVH } ) => {
  16206. // Original approximation by Christophe Schlick '94
  16207. // float fresnel = pow( 1.0 - dotVH, 5.0 );
  16208. // Optimized variant (presented by Epic at SIGGRAPH '13)
  16209. // https://cdn2.unrealengine.com/Resources/files/2013SiggraphPresentationsNotes-26915738.pdf
  16210. const fresnel = dotVH.mul( -5.55473 ).sub( 6.98316 ).mul( dotVH ).exp2();
  16211. return f0.mul( fresnel.oneMinus() ).add( f90.mul( fresnel ) );
  16212. } ); // validated
  16213. const BRDF_Lambert = /*@__PURE__*/ Fn( ( inputs ) => {
  16214. return inputs.diffuseColor.mul( 1 / Math.PI ); // punctual light
  16215. } ); // validated
  16216. const G_BlinnPhong_Implicit = () => float( 0.25 );
  16217. const D_BlinnPhong = /*@__PURE__*/ Fn( ( { dotNH } ) => {
  16218. return shininess.mul( float( 0.5 ) ).add( 1.0 ).mul( float( 1 / Math.PI ) ).mul( dotNH.pow( shininess ) );
  16219. } );
  16220. const BRDF_BlinnPhong = /*@__PURE__*/ Fn( ( { lightDirection } ) => {
  16221. const halfDir = lightDirection.add( positionViewDirection ).normalize();
  16222. const dotNH = normalView.dot( halfDir ).clamp();
  16223. const dotVH = positionViewDirection.dot( halfDir ).clamp();
  16224. const F = F_Schlick( { f0: specularColor, f90: 1.0, dotVH } );
  16225. const G = G_BlinnPhong_Implicit();
  16226. const D = D_BlinnPhong( { dotNH } );
  16227. return F.mul( G ).mul( D );
  16228. } );
  16229. /**
  16230. * Represents the lighting model for a phong material. Used in {@link MeshPhongNodeMaterial}.
  16231. *
  16232. * @augments BasicLightingModel
  16233. */
  16234. class PhongLightingModel extends BasicLightingModel {
  16235. /**
  16236. * Constructs a new phong lighting model.
  16237. *
  16238. * @param {boolean} [specular=true] - Whether specular is supported or not.
  16239. */
  16240. constructor( specular = true ) {
  16241. super();
  16242. /**
  16243. * Whether specular is supported or not. Set this to `false` if you are
  16244. * looking for a Lambert-like material meaning a material for non-shiny
  16245. * surfaces, without specular highlights.
  16246. *
  16247. * @type {boolean}
  16248. * @default true
  16249. */
  16250. this.specular = specular;
  16251. }
  16252. /**
  16253. * Implements the direct lighting. The specular portion is optional an can be controlled
  16254. * with the {@link PhongLightingModel#specular} flag.
  16255. *
  16256. * @param {Object} lightData - The light data.
  16257. */
  16258. direct( { lightDirection, lightColor, reflectedLight } ) {
  16259. const dotNL = normalView.dot( lightDirection ).clamp();
  16260. const irradiance = dotNL.mul( lightColor );
  16261. reflectedLight.directDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor: diffuseColor.rgb } ) ) );
  16262. if ( this.specular === true ) {
  16263. reflectedLight.directSpecular.addAssign( irradiance.mul( BRDF_BlinnPhong( { lightDirection } ) ).mul( materialSpecularStrength ) );
  16264. }
  16265. }
  16266. /**
  16267. * Implements the indirect lighting.
  16268. *
  16269. * @param {NodeBuilder} builder - The current node builder.
  16270. */
  16271. indirect( builder ) {
  16272. const { ambientOcclusion, irradiance, reflectedLight } = builder.context;
  16273. reflectedLight.indirectDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor } ) ) );
  16274. reflectedLight.indirectDiffuse.mulAssign( ambientOcclusion );
  16275. }
  16276. }
  16277. const _defaultValues$8 = /*@__PURE__*/ new MeshLambertMaterial();
  16278. /**
  16279. * Node material version of {@link MeshLambertMaterial}.
  16280. *
  16281. * @augments NodeMaterial
  16282. */
  16283. class MeshLambertNodeMaterial extends NodeMaterial {
  16284. static get type() {
  16285. return 'MeshLambertNodeMaterial';
  16286. }
  16287. /**
  16288. * Constructs a new mesh lambert node material.
  16289. *
  16290. * @param {Object} [parameters] - The configuration parameter.
  16291. */
  16292. constructor( parameters ) {
  16293. super();
  16294. /**
  16295. * This flag can be used for type testing.
  16296. *
  16297. * @type {boolean}
  16298. * @readonly
  16299. * @default true
  16300. */
  16301. this.isMeshLambertNodeMaterial = true;
  16302. /**
  16303. * Set to `true` because lambert materials react on lights.
  16304. *
  16305. * @type {boolean}
  16306. * @default true
  16307. */
  16308. this.lights = true;
  16309. this.setDefaultValues( _defaultValues$8 );
  16310. this.setValues( parameters );
  16311. }
  16312. /**
  16313. * Overwritten since this type of material uses {@link BasicEnvironmentNode}
  16314. * to implement the default environment mapping.
  16315. *
  16316. * @param {NodeBuilder} builder - The current node builder.
  16317. * @return {?BasicEnvironmentNode<vec3>} The environment node.
  16318. */
  16319. setupEnvironment( builder ) {
  16320. const envNode = super.setupEnvironment( builder );
  16321. return envNode ? new BasicEnvironmentNode( envNode ) : null;
  16322. }
  16323. /**
  16324. * Setups the lighting model.
  16325. *
  16326. * @return {PhongLightingModel} The lighting model.
  16327. */
  16328. setupLightingModel( /*builder*/ ) {
  16329. return new PhongLightingModel( false ); // ( specular ) -> force lambert
  16330. }
  16331. }
  16332. const _defaultValues$7 = /*@__PURE__*/ new MeshPhongMaterial();
  16333. /**
  16334. * Node material version of {@link MeshPhongMaterial}.
  16335. *
  16336. * @augments NodeMaterial
  16337. */
  16338. class MeshPhongNodeMaterial extends NodeMaterial {
  16339. static get type() {
  16340. return 'MeshPhongNodeMaterial';
  16341. }
  16342. /**
  16343. * Constructs a new mesh lambert node material.
  16344. *
  16345. * @param {Object} [parameters] - The configuration parameter.
  16346. */
  16347. constructor( parameters ) {
  16348. super();
  16349. /**
  16350. * This flag can be used for type testing.
  16351. *
  16352. * @type {boolean}
  16353. * @readonly
  16354. * @default true
  16355. */
  16356. this.isMeshPhongNodeMaterial = true;
  16357. /**
  16358. * Set to `true` because phong materials react on lights.
  16359. *
  16360. * @type {boolean}
  16361. * @default true
  16362. */
  16363. this.lights = true;
  16364. /**
  16365. * The shininess of phong materials is by default inferred from the `shininess`
  16366. * property. This node property allows to overwrite the default
  16367. * and define the shininess with a node instead.
  16368. *
  16369. * If you don't want to overwrite the shininess but modify the existing
  16370. * value instead, use {@link materialShininess}.
  16371. *
  16372. * @type {?Node<float>}
  16373. * @default null
  16374. */
  16375. this.shininessNode = null;
  16376. /**
  16377. * The specular color of phong materials is by default inferred from the
  16378. * `specular` property. This node property allows to overwrite the default
  16379. * and define the specular color with a node instead.
  16380. *
  16381. * If you don't want to overwrite the specular color but modify the existing
  16382. * value instead, use {@link materialSpecular}.
  16383. *
  16384. * @type {?Node<vec3>}
  16385. * @default null
  16386. */
  16387. this.specularNode = null;
  16388. this.setDefaultValues( _defaultValues$7 );
  16389. this.setValues( parameters );
  16390. }
  16391. /**
  16392. * Overwritten since this type of material uses {@link BasicEnvironmentNode}
  16393. * to implement the default environment mapping.
  16394. *
  16395. * @param {NodeBuilder} builder - The current node builder.
  16396. * @return {?BasicEnvironmentNode<vec3>} The environment node.
  16397. */
  16398. setupEnvironment( builder ) {
  16399. const envNode = super.setupEnvironment( builder );
  16400. return envNode ? new BasicEnvironmentNode( envNode ) : null;
  16401. }
  16402. /**
  16403. * Setups the lighting model.
  16404. *
  16405. * @return {PhongLightingModel} The lighting model.
  16406. */
  16407. setupLightingModel( /*builder*/ ) {
  16408. return new PhongLightingModel();
  16409. }
  16410. /**
  16411. * Setups the phong specific node variables.
  16412. *
  16413. * @param {NodeBuilder} builder - The current node builder.
  16414. */
  16415. setupVariants( /*builder*/ ) {
  16416. // SHININESS
  16417. const shininessNode = ( this.shininessNode ? float( this.shininessNode ) : materialShininess ).max( 1e-4 ); // to prevent pow( 0.0, 0.0 )
  16418. shininess.assign( shininessNode );
  16419. // SPECULAR COLOR
  16420. const specularNode = this.specularNode || materialSpecular;
  16421. specularColor.assign( specularNode );
  16422. }
  16423. copy( source ) {
  16424. this.shininessNode = source.shininessNode;
  16425. this.specularNode = source.specularNode;
  16426. return super.copy( source );
  16427. }
  16428. }
  16429. const getGeometryRoughness = /*@__PURE__*/ Fn( ( builder ) => {
  16430. if ( builder.geometry.hasAttribute( 'normal' ) === false ) {
  16431. return float( 0 );
  16432. }
  16433. const dxy = normalViewGeometry.dFdx().abs().max( normalViewGeometry.dFdy().abs() );
  16434. const geometryRoughness = dxy.x.max( dxy.y ).max( dxy.z );
  16435. return geometryRoughness;
  16436. } );
  16437. const getRoughness = /*@__PURE__*/ Fn( ( inputs ) => {
  16438. const { roughness } = inputs;
  16439. const geometryRoughness = getGeometryRoughness();
  16440. let roughnessFactor = roughness.max( 0.0525 ); // 0.0525 corresponds to the base mip of a 256 cubemap.
  16441. roughnessFactor = roughnessFactor.add( geometryRoughness );
  16442. roughnessFactor = roughnessFactor.min( 1.0 );
  16443. return roughnessFactor;
  16444. } );
  16445. // Moving Frostbite to Physically Based Rendering 3.0 - page 12, listing 2
  16446. // https://seblagarde.files.wordpress.com/2015/07/course_notes_moving_frostbite_to_pbr_v32.pdf
  16447. const V_GGX_SmithCorrelated = /*@__PURE__*/ Fn( ( { alpha, dotNL, dotNV } ) => {
  16448. const a2 = alpha.pow2();
  16449. const gv = dotNL.mul( a2.add( a2.oneMinus().mul( dotNV.pow2() ) ).sqrt() );
  16450. const gl = dotNV.mul( a2.add( a2.oneMinus().mul( dotNL.pow2() ) ).sqrt() );
  16451. return div( 0.5, gv.add( gl ).max( EPSILON ) );
  16452. } ).setLayout( {
  16453. name: 'V_GGX_SmithCorrelated',
  16454. type: 'float',
  16455. inputs: [
  16456. { name: 'alpha', type: 'float' },
  16457. { name: 'dotNL', type: 'float' },
  16458. { name: 'dotNV', type: 'float' }
  16459. ]
  16460. } ); // validated
  16461. // https://google.github.io/filament/Filament.md.html#materialsystem/anisotropicmodel/anisotropicspecularbrdf
  16462. const V_GGX_SmithCorrelated_Anisotropic = /*@__PURE__*/ Fn( ( { alphaT, alphaB, dotTV, dotBV, dotTL, dotBL, dotNV, dotNL } ) => {
  16463. const gv = dotNL.mul( vec3( alphaT.mul( dotTV ), alphaB.mul( dotBV ), dotNV ).length() );
  16464. const gl = dotNV.mul( vec3( alphaT.mul( dotTL ), alphaB.mul( dotBL ), dotNL ).length() );
  16465. const v = div( 0.5, gv.add( gl ) );
  16466. return v;
  16467. } ).setLayout( {
  16468. name: 'V_GGX_SmithCorrelated_Anisotropic',
  16469. type: 'float',
  16470. inputs: [
  16471. { name: 'alphaT', type: 'float', qualifier: 'in' },
  16472. { name: 'alphaB', type: 'float', qualifier: 'in' },
  16473. { name: 'dotTV', type: 'float', qualifier: 'in' },
  16474. { name: 'dotBV', type: 'float', qualifier: 'in' },
  16475. { name: 'dotTL', type: 'float', qualifier: 'in' },
  16476. { name: 'dotBL', type: 'float', qualifier: 'in' },
  16477. { name: 'dotNV', type: 'float', qualifier: 'in' },
  16478. { name: 'dotNL', type: 'float', qualifier: 'in' }
  16479. ]
  16480. } );
  16481. // Microfacet Models for Refraction through Rough Surfaces - equation (33)
  16482. // http://graphicrants.blogspot.com/2013/08/specular-brdf-reference.html
  16483. // alpha is "roughness squared" in Disney’s reparameterization
  16484. const D_GGX = /*@__PURE__*/ Fn( ( { alpha, dotNH } ) => {
  16485. const a2 = alpha.pow2();
  16486. const denom = dotNH.pow2().mul( a2.oneMinus() ).oneMinus(); // avoid alpha = 0 with dotNH = 1
  16487. return a2.div( denom.pow2() ).mul( 1 / Math.PI );
  16488. } ).setLayout( {
  16489. name: 'D_GGX',
  16490. type: 'float',
  16491. inputs: [
  16492. { name: 'alpha', type: 'float' },
  16493. { name: 'dotNH', type: 'float' }
  16494. ]
  16495. } ); // validated
  16496. const RECIPROCAL_PI = /*@__PURE__*/ float( 1 / Math.PI );
  16497. // https://google.github.io/filament/Filament.md.html#materialsystem/anisotropicmodel/anisotropicspecularbrdf
  16498. const D_GGX_Anisotropic = /*@__PURE__*/ Fn( ( { alphaT, alphaB, dotNH, dotTH, dotBH } ) => {
  16499. const a2 = alphaT.mul( alphaB );
  16500. const v = vec3( alphaB.mul( dotTH ), alphaT.mul( dotBH ), a2.mul( dotNH ) );
  16501. const v2 = v.dot( v );
  16502. const w2 = a2.div( v2 );
  16503. return RECIPROCAL_PI.mul( a2.mul( w2.pow2() ) );
  16504. } ).setLayout( {
  16505. name: 'D_GGX_Anisotropic',
  16506. type: 'float',
  16507. inputs: [
  16508. { name: 'alphaT', type: 'float', qualifier: 'in' },
  16509. { name: 'alphaB', type: 'float', qualifier: 'in' },
  16510. { name: 'dotNH', type: 'float', qualifier: 'in' },
  16511. { name: 'dotTH', type: 'float', qualifier: 'in' },
  16512. { name: 'dotBH', type: 'float', qualifier: 'in' }
  16513. ]
  16514. } );
  16515. // GGX Distribution, Schlick Fresnel, GGX_SmithCorrelated Visibility
  16516. const BRDF_GGX = /*@__PURE__*/ Fn( ( { lightDirection, f0, f90, roughness, f, normalView: normalView$1 = normalView, USE_IRIDESCENCE, USE_ANISOTROPY } ) => {
  16517. const alpha = roughness.pow2(); // UE4's roughness
  16518. const halfDir = lightDirection.add( positionViewDirection ).normalize();
  16519. const dotNL = normalView$1.dot( lightDirection ).clamp();
  16520. const dotNV = normalView$1.dot( positionViewDirection ).clamp(); // @ TODO: Move to core dotNV
  16521. const dotNH = normalView$1.dot( halfDir ).clamp();
  16522. const dotVH = positionViewDirection.dot( halfDir ).clamp();
  16523. let F = F_Schlick( { f0, f90, dotVH } );
  16524. let V, D;
  16525. if ( defined( USE_IRIDESCENCE ) ) {
  16526. F = iridescence.mix( F, f );
  16527. }
  16528. if ( defined( USE_ANISOTROPY ) ) {
  16529. const dotTL = anisotropyT.dot( lightDirection );
  16530. const dotTV = anisotropyT.dot( positionViewDirection );
  16531. const dotTH = anisotropyT.dot( halfDir );
  16532. const dotBL = anisotropyB.dot( lightDirection );
  16533. const dotBV = anisotropyB.dot( positionViewDirection );
  16534. const dotBH = anisotropyB.dot( halfDir );
  16535. V = V_GGX_SmithCorrelated_Anisotropic( { alphaT, alphaB: alpha, dotTV, dotBV, dotTL, dotBL, dotNV, dotNL } );
  16536. D = D_GGX_Anisotropic( { alphaT, alphaB: alpha, dotNH, dotTH, dotBH } );
  16537. } else {
  16538. V = V_GGX_SmithCorrelated( { alpha, dotNL, dotNV } );
  16539. D = D_GGX( { alpha, dotNH } );
  16540. }
  16541. return F.mul( V ).mul( D );
  16542. } ); // validated
  16543. /**
  16544. * Precomputed DFG LUT for Image-Based Lighting
  16545. * Resolution: 16x16
  16546. * Samples: 4096 per texel
  16547. * Format: RG16F (2 half floats per texel: scale, bias)
  16548. */
  16549. const DATA = new Uint16Array( [
  16550. 0x30b5, 0x3ad1, 0x314c, 0x3a4d, 0x33d2, 0x391c, 0x35ef, 0x3828, 0x37f3, 0x36a6, 0x38d1, 0x3539, 0x3979, 0x3410, 0x39f8, 0x3252, 0x3a53, 0x30f0, 0x3a94, 0x2fc9, 0x3abf, 0x2e35, 0x3ada, 0x2d05, 0x3ae8, 0x2c1f, 0x3aed, 0x2ae0, 0x3aea, 0x29d1, 0x3ae1, 0x28ff,
  16551. 0x3638, 0x38e4, 0x364a, 0x38ce, 0x3699, 0x385e, 0x374e, 0x372c, 0x3839, 0x35a4, 0x38dc, 0x3462, 0x396e, 0x32c4, 0x39de, 0x3134, 0x3a2b, 0x3003, 0x3a59, 0x2e3a, 0x3a6d, 0x2ce1, 0x3a6e, 0x2bba, 0x3a5f, 0x2a33, 0x3a49, 0x290a, 0x3a2d, 0x2826, 0x3a0a, 0x26e8,
  16552. 0x3894, 0x36d7, 0x3897, 0x36c9, 0x38a3, 0x3675, 0x38bc, 0x35ac, 0x38ee, 0x349c, 0x393e, 0x3332, 0x3997, 0x3186, 0x39e2, 0x3038, 0x3a13, 0x2e75, 0x3a29, 0x2cf5, 0x3a2d, 0x2bac, 0x3a21, 0x29ff, 0x3a04, 0x28bc, 0x39dc, 0x2790, 0x39ad, 0x261a, 0x3978, 0x24fa,
  16553. 0x39ac, 0x34a8, 0x39ac, 0x34a3, 0x39ae, 0x3480, 0x39ae, 0x3423, 0x39b1, 0x330e, 0x39c2, 0x31a9, 0x39e0, 0x3063, 0x39fc, 0x2eb5, 0x3a0c, 0x2d1d, 0x3a14, 0x2bcf, 0x3a07, 0x29ff, 0x39e9, 0x28a3, 0x39be, 0x273c, 0x3989, 0x25b3, 0x394a, 0x2488, 0x3907, 0x2345,
  16554. 0x3a77, 0x3223, 0x3a76, 0x321f, 0x3a73, 0x3204, 0x3a6a, 0x31b3, 0x3a58, 0x3114, 0x3a45, 0x303b, 0x3a34, 0x2eb6, 0x3a26, 0x2d31, 0x3a1e, 0x2bef, 0x3a0b, 0x2a0d, 0x39ec, 0x28a1, 0x39c0, 0x271b, 0x3987, 0x2580, 0x3944, 0x2449, 0x38fa, 0x22bd, 0x38ac, 0x2155,
  16555. 0x3b07, 0x2fca, 0x3b06, 0x2fca, 0x3b00, 0x2fb8, 0x3af4, 0x2f7c, 0x3adb, 0x2eea, 0x3ab4, 0x2e00, 0x3a85, 0x2cec, 0x3a5e, 0x2bc5, 0x3a36, 0x2a00, 0x3a0d, 0x2899, 0x39dc, 0x2707, 0x39a0, 0x2562, 0x395a, 0x2424, 0x390b, 0x2268, 0x38b7, 0x20fd, 0x385f, 0x1fd1,
  16556. 0x3b69, 0x2cb9, 0x3b68, 0x2cbb, 0x3b62, 0x2cbb, 0x3b56, 0x2cae, 0x3b3b, 0x2c78, 0x3b0d, 0x2c0a, 0x3acf, 0x2ae3, 0x3a92, 0x2998, 0x3a54, 0x2867, 0x3a17, 0x26d0, 0x39d3, 0x253c, 0x3989, 0x2402, 0x3935, 0x2226, 0x38dc, 0x20bd, 0x387d, 0x1f54, 0x381d, 0x1db3,
  16557. 0x3ba9, 0x296b, 0x3ba8, 0x296f, 0x3ba3, 0x297b, 0x3b98, 0x2987, 0x3b7f, 0x2976, 0x3b4e, 0x2927, 0x3b0e, 0x2895, 0x3ac2, 0x27b7, 0x3a73, 0x263b, 0x3a23, 0x24e7, 0x39d0, 0x239b, 0x3976, 0x21d9, 0x3917, 0x207e, 0x38b2, 0x1ee7, 0x384b, 0x1d53, 0x37c7, 0x1c1e,
  16558. 0x3bd2, 0x25cb, 0x3bd1, 0x25d3, 0x3bcd, 0x25f0, 0x3bc2, 0x261f, 0x3bad, 0x2645, 0x3b7d, 0x262d, 0x3b3e, 0x25c4, 0x3aec, 0x250f, 0x3a93, 0x243a, 0x3a32, 0x22ce, 0x39d0, 0x215b, 0x3969, 0x202a, 0x38fe, 0x1e6e, 0x388f, 0x1cf1, 0x381f, 0x1b9b, 0x3762, 0x19dd,
  16559. 0x3be9, 0x21ab, 0x3be9, 0x21b7, 0x3be5, 0x21e5, 0x3bdd, 0x2241, 0x3bc9, 0x22a7, 0x3ba0, 0x22ec, 0x3b62, 0x22cd, 0x3b0f, 0x2247, 0x3aae, 0x2175, 0x3a44, 0x2088, 0x39d4, 0x1f49, 0x3960, 0x1dbe, 0x38e9, 0x1c77, 0x3870, 0x1ae8, 0x37f1, 0x1953, 0x3708, 0x181b,
  16560. 0x3bf6, 0x1cea, 0x3bf6, 0x1cfb, 0x3bf3, 0x1d38, 0x3bec, 0x1dbd, 0x3bda, 0x1e7c, 0x3bb7, 0x1f25, 0x3b7d, 0x1f79, 0x3b2c, 0x1f4c, 0x3ac6, 0x1ea6, 0x3a55, 0x1dbb, 0x39da, 0x1cbd, 0x395a, 0x1b9d, 0x38d8, 0x1a00, 0x3855, 0x18ac, 0x37ab, 0x173c, 0x36b7, 0x1598,
  16561. 0x3bfc, 0x1736, 0x3bfc, 0x1759, 0x3bf9, 0x17e7, 0x3bf4, 0x1896, 0x3be4, 0x1997, 0x3bc6, 0x1aa8, 0x3b91, 0x1b84, 0x3b43, 0x1bd2, 0x3ade, 0x1b8a, 0x3a65, 0x1acd, 0x39e2, 0x19d3, 0x3957, 0x18cd, 0x38ca, 0x17b3, 0x383e, 0x1613, 0x376d, 0x14bf, 0x366f, 0x135e,
  16562. 0x3bff, 0x101b, 0x3bff, 0x1039, 0x3bfc, 0x10c8, 0x3bf9, 0x1226, 0x3bea, 0x1428, 0x3bcf, 0x1584, 0x3b9f, 0x16c5, 0x3b54, 0x179a, 0x3af0, 0x17ce, 0x3a76, 0x1771, 0x39ea, 0x16a4, 0x3956, 0x15a7, 0x38bf, 0x14a7, 0x3829, 0x1379, 0x3735, 0x11ea, 0x362d, 0x10a1,
  16563. 0x3c00, 0x061b, 0x3c00, 0x066a, 0x3bfe, 0x081c, 0x3bfa, 0x0a4c, 0x3bed, 0x0d16, 0x3bd5, 0x0fb3, 0x3ba9, 0x114d, 0x3b63, 0x127c, 0x3b01, 0x132f, 0x3a85, 0x1344, 0x39f4, 0x12d2, 0x3957, 0x120d, 0x38b5, 0x1122, 0x3817, 0x103c, 0x3703, 0x0ed3, 0x35f0, 0x0d6d,
  16564. 0x3c00, 0x007a, 0x3c00, 0x0089, 0x3bfe, 0x011d, 0x3bfb, 0x027c, 0x3bf0, 0x04fa, 0x3bda, 0x0881, 0x3bb1, 0x0acd, 0x3b6f, 0x0c97, 0x3b10, 0x0d7b, 0x3a93, 0x0df1, 0x39fe, 0x0def, 0x3959, 0x0d8a, 0x38af, 0x0ce9, 0x3808, 0x0c31, 0x36d5, 0x0af0, 0x35b9, 0x09a3,
  16565. 0x3c00, 0x0000, 0x3c00, 0x0001, 0x3bff, 0x0015, 0x3bfb, 0x0059, 0x3bf2, 0x00fd, 0x3bdd, 0x01df, 0x3bb7, 0x031c, 0x3b79, 0x047c, 0x3b1d, 0x05d4, 0x3aa0, 0x06d5, 0x3a08, 0x075a, 0x395d, 0x075e, 0x38aa, 0x06f7, 0x37f4, 0x0648, 0x36ac, 0x0576, 0x3586, 0x049f
  16566. ] );
  16567. let lut = null;
  16568. const DFGLUT = /*@__PURE__*/ Fn( ( { roughness, dotNV } ) => {
  16569. if ( lut === null ) {
  16570. lut = new DataTexture( DATA, 16, 16, RGFormat, HalfFloatType );
  16571. lut.name = 'DFG_LUT';
  16572. lut.minFilter = LinearFilter;
  16573. lut.magFilter = LinearFilter;
  16574. lut.wrapS = ClampToEdgeWrapping;
  16575. lut.wrapT = ClampToEdgeWrapping;
  16576. lut.generateMipmaps = false;
  16577. lut.needsUpdate = true;
  16578. }
  16579. const uv = vec2( roughness, dotNV );
  16580. return texture( lut, uv ).rg;
  16581. } );
  16582. // GGX BRDF with multi-scattering energy compensation for direct lighting
  16583. // This provides more accurate energy conservation, especially for rough materials
  16584. // Based on "Practical Multiple Scattering Compensation for Microfacet Models"
  16585. // https://blog.selfshadow.com/publications/turquin/ms_comp_final.pdf
  16586. const BRDF_GGX_Multiscatter = /*@__PURE__*/ Fn( ( { lightDirection, f0, f90, roughness: _roughness, f, USE_IRIDESCENCE, USE_ANISOTROPY } ) => {
  16587. // Single-scattering BRDF (standard GGX)
  16588. const singleScatter = BRDF_GGX( { lightDirection, f0, f90, roughness: _roughness, f, USE_IRIDESCENCE, USE_ANISOTROPY } );
  16589. // Multi-scattering compensation
  16590. const dotNL = normalView.dot( lightDirection ).clamp();
  16591. const dotNV = normalView.dot( positionViewDirection ).clamp();
  16592. // Precomputed DFG values for view and light directions
  16593. const dfgV = DFGLUT( { roughness: _roughness, dotNV } );
  16594. const dfgL = DFGLUT( { roughness: _roughness, dotNV: dotNL } );
  16595. // Single-scattering energy for view and light
  16596. const FssEss_V = f0.mul( dfgV.x ).add( f90.mul( dfgV.y ) );
  16597. const FssEss_L = f0.mul( dfgL.x ).add( f90.mul( dfgL.y ) );
  16598. const Ess_V = dfgV.x.add( dfgV.y );
  16599. const Ess_L = dfgL.x.add( dfgL.y );
  16600. // Energy lost to multiple scattering
  16601. const Ems_V = float( 1.0 ).sub( Ess_V );
  16602. const Ems_L = float( 1.0 ).sub( Ess_L );
  16603. // Average Fresnel reflectance
  16604. const Favg = f0.add( f0.oneMinus().mul( 0.047619 ) ); // 1/21
  16605. // Multiple scattering contribution
  16606. // Uses geometric mean of view and light contributions for better energy distribution
  16607. 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 ) );
  16608. // Energy compensation factor
  16609. const compensationFactor = Ems_V.mul( Ems_L );
  16610. const multiScatter = Fms.mul( compensationFactor );
  16611. return singleScatter.add( multiScatter );
  16612. } );
  16613. const EnvironmentBRDF = /*@__PURE__*/ Fn( ( inputs ) => {
  16614. const { dotNV, specularColor, specularF90, roughness } = inputs;
  16615. const fab = DFGLUT( { dotNV, roughness } );
  16616. return specularColor.mul( fab.x ).add( specularF90.mul( fab.y ) );
  16617. } );
  16618. const Schlick_to_F0 = /*@__PURE__*/ Fn( ( { f, f90, dotVH } ) => {
  16619. const x = dotVH.oneMinus().saturate();
  16620. const x2 = x.mul( x );
  16621. const x5 = x.mul( x2, x2 ).clamp( 0, .9999 );
  16622. return f.sub( vec3( f90 ).mul( x5 ) ).div( x5.oneMinus() );
  16623. } ).setLayout( {
  16624. name: 'Schlick_to_F0',
  16625. type: 'vec3',
  16626. inputs: [
  16627. { name: 'f', type: 'vec3' },
  16628. { name: 'f90', type: 'float' },
  16629. { name: 'dotVH', type: 'float' }
  16630. ]
  16631. } );
  16632. // https://github.com/google/filament/blob/master/shaders/src/brdf.fs
  16633. const D_Charlie = /*@__PURE__*/ Fn( ( { roughness, dotNH } ) => {
  16634. const alpha = roughness.pow2();
  16635. // Estevez and Kulla 2017, "Production Friendly Microfacet Sheen BRDF"
  16636. const invAlpha = float( 1.0 ).div( alpha );
  16637. const cos2h = dotNH.pow2();
  16638. const sin2h = cos2h.oneMinus().max( 0.0078125 ); // 2^(-14/2), so sin2h^2 > 0 in fp16
  16639. return float( 2.0 ).add( invAlpha ).mul( sin2h.pow( invAlpha.mul( 0.5 ) ) ).div( 2.0 * Math.PI );
  16640. } ).setLayout( {
  16641. name: 'D_Charlie',
  16642. type: 'float',
  16643. inputs: [
  16644. { name: 'roughness', type: 'float' },
  16645. { name: 'dotNH', type: 'float' }
  16646. ]
  16647. } );
  16648. // https://github.com/google/filament/blob/master/shaders/src/brdf.fs
  16649. const V_Neubelt = /*@__PURE__*/ Fn( ( { dotNV, dotNL } ) => {
  16650. // Neubelt and Pettineo 2013, "Crafting a Next-gen Material Pipeline for The Order: 1886"
  16651. return float( 1.0 ).div( float( 4.0 ).mul( dotNL.add( dotNV ).sub( dotNL.mul( dotNV ) ) ) );
  16652. } ).setLayout( {
  16653. name: 'V_Neubelt',
  16654. type: 'float',
  16655. inputs: [
  16656. { name: 'dotNV', type: 'float' },
  16657. { name: 'dotNL', type: 'float' }
  16658. ]
  16659. } );
  16660. const BRDF_Sheen = /*@__PURE__*/ Fn( ( { lightDirection } ) => {
  16661. const halfDir = lightDirection.add( positionViewDirection ).normalize();
  16662. const dotNL = normalView.dot( lightDirection ).clamp();
  16663. const dotNV = normalView.dot( positionViewDirection ).clamp();
  16664. const dotNH = normalView.dot( halfDir ).clamp();
  16665. const D = D_Charlie( { roughness: sheenRoughness, dotNH } );
  16666. const V = V_Neubelt( { dotNV, dotNL } );
  16667. return sheen.mul( D ).mul( V );
  16668. } );
  16669. // Rect Area Light
  16670. // Real-Time Polygonal-Light Shading with Linearly Transformed Cosines
  16671. // by Eric Heitz, Jonathan Dupuy, Stephen Hill and David Neubelt
  16672. // code: https://github.com/selfshadow/ltc_code/
  16673. const LTC_Uv = /*@__PURE__*/ Fn( ( { N, V, roughness } ) => {
  16674. const LUT_SIZE = 64.0;
  16675. const LUT_SCALE = ( LUT_SIZE - 1.0 ) / LUT_SIZE;
  16676. const LUT_BIAS = 0.5 / LUT_SIZE;
  16677. const dotNV = N.dot( V ).saturate();
  16678. // texture parameterized by sqrt( GGX alpha ) and sqrt( 1 - cos( theta ) )
  16679. const uv = vec2( roughness, dotNV.oneMinus().sqrt() );
  16680. uv.assign( uv.mul( LUT_SCALE ).add( LUT_BIAS ) );
  16681. return uv;
  16682. } ).setLayout( {
  16683. name: 'LTC_Uv',
  16684. type: 'vec2',
  16685. inputs: [
  16686. { name: 'N', type: 'vec3' },
  16687. { name: 'V', type: 'vec3' },
  16688. { name: 'roughness', type: 'float' }
  16689. ]
  16690. } );
  16691. const LTC_ClippedSphereFormFactor = /*@__PURE__*/ Fn( ( { f } ) => {
  16692. // Real-Time Area Lighting: a Journey from Research to Production (p.102)
  16693. // An approximation of the form factor of a horizon-clipped rectangle.
  16694. const l = f.length();
  16695. return max$1( l.mul( l ).add( f.z ).div( l.add( 1.0 ) ), 0 );
  16696. } ).setLayout( {
  16697. name: 'LTC_ClippedSphereFormFactor',
  16698. type: 'float',
  16699. inputs: [
  16700. { name: 'f', type: 'vec3' }
  16701. ]
  16702. } );
  16703. const LTC_EdgeVectorFormFactor = /*@__PURE__*/ Fn( ( { v1, v2 } ) => {
  16704. const x = v1.dot( v2 );
  16705. const y = x.abs().toVar();
  16706. // rational polynomial approximation to theta / sin( theta ) / 2PI
  16707. const a = y.mul( 0.0145206 ).add( 0.4965155 ).mul( y ).add( 0.8543985 ).toVar();
  16708. const b = y.add( 4.1616724 ).mul( y ).add( 3.4175940 ).toVar();
  16709. const v = a.div( b );
  16710. const theta_sintheta = x.greaterThan( 0.0 ).select( v, max$1( x.mul( x ).oneMinus(), 1e-7 ).inverseSqrt().mul( 0.5 ).sub( v ) );
  16711. return v1.cross( v2 ).mul( theta_sintheta );
  16712. } ).setLayout( {
  16713. name: 'LTC_EdgeVectorFormFactor',
  16714. type: 'vec3',
  16715. inputs: [
  16716. { name: 'v1', type: 'vec3' },
  16717. { name: 'v2', type: 'vec3' }
  16718. ]
  16719. } );
  16720. const LTC_Evaluate = /*@__PURE__*/ Fn( ( { N, V, P, mInv, p0, p1, p2, p3 } ) => {
  16721. // bail if point is on back side of plane of light
  16722. // assumes ccw winding order of light vertices
  16723. const v1 = p1.sub( p0 ).toVar();
  16724. const v2 = p3.sub( p0 ).toVar();
  16725. const lightNormal = v1.cross( v2 );
  16726. const result = vec3().toVar();
  16727. If( lightNormal.dot( P.sub( p0 ) ).greaterThanEqual( 0.0 ), () => {
  16728. // construct orthonormal basis around N
  16729. const T1 = V.sub( N.mul( V.dot( N ) ) ).normalize();
  16730. const T2 = N.cross( T1 ).negate(); // negated from paper; possibly due to a different handedness of world coordinate system
  16731. // compute transform
  16732. const mat = mInv.mul( mat3( T1, T2, N ).transpose() ).toVar();
  16733. // transform rect
  16734. // & project rect onto sphere
  16735. const coords0 = mat.mul( p0.sub( P ) ).normalize().toVar();
  16736. const coords1 = mat.mul( p1.sub( P ) ).normalize().toVar();
  16737. const coords2 = mat.mul( p2.sub( P ) ).normalize().toVar();
  16738. const coords3 = mat.mul( p3.sub( P ) ).normalize().toVar();
  16739. // calculate vector form factor
  16740. const vectorFormFactor = vec3( 0 ).toVar();
  16741. vectorFormFactor.addAssign( LTC_EdgeVectorFormFactor( { v1: coords0, v2: coords1 } ) );
  16742. vectorFormFactor.addAssign( LTC_EdgeVectorFormFactor( { v1: coords1, v2: coords2 } ) );
  16743. vectorFormFactor.addAssign( LTC_EdgeVectorFormFactor( { v1: coords2, v2: coords3 } ) );
  16744. vectorFormFactor.addAssign( LTC_EdgeVectorFormFactor( { v1: coords3, v2: coords0 } ) );
  16745. // adjust for horizon clipping
  16746. result.assign( vec3( LTC_ClippedSphereFormFactor( { f: vectorFormFactor } ) ) );
  16747. } );
  16748. return result;
  16749. } ).setLayout( {
  16750. name: 'LTC_Evaluate',
  16751. type: 'vec3',
  16752. inputs: [
  16753. { name: 'N', type: 'vec3' },
  16754. { name: 'V', type: 'vec3' },
  16755. { name: 'P', type: 'vec3' },
  16756. { name: 'mInv', type: 'mat3' },
  16757. { name: 'p0', type: 'vec3' },
  16758. { name: 'p1', type: 'vec3' },
  16759. { name: 'p2', type: 'vec3' },
  16760. { name: 'p3', type: 'vec3' }
  16761. ]
  16762. } );
  16763. const LTC_Evaluate_Volume = /*@__PURE__*/ Fn( ( { P, p0, p1, p2, p3 } ) => {
  16764. // bail if point is on back side of plane of light
  16765. // assumes ccw winding order of light vertices
  16766. const v1 = p1.sub( p0 ).toVar();
  16767. const v2 = p3.sub( p0 ).toVar();
  16768. const lightNormal = v1.cross( v2 );
  16769. const result = vec3().toVar();
  16770. If( lightNormal.dot( P.sub( p0 ) ).greaterThanEqual( 0.0 ), () => {
  16771. // transform rect
  16772. // & project rect onto sphere
  16773. const coords0 = p0.sub( P ).normalize().toVar();
  16774. const coords1 = p1.sub( P ).normalize().toVar();
  16775. const coords2 = p2.sub( P ).normalize().toVar();
  16776. const coords3 = p3.sub( P ).normalize().toVar();
  16777. // calculate vector form factor
  16778. const vectorFormFactor = vec3( 0 ).toVar();
  16779. vectorFormFactor.addAssign( LTC_EdgeVectorFormFactor( { v1: coords0, v2: coords1 } ) );
  16780. vectorFormFactor.addAssign( LTC_EdgeVectorFormFactor( { v1: coords1, v2: coords2 } ) );
  16781. vectorFormFactor.addAssign( LTC_EdgeVectorFormFactor( { v1: coords2, v2: coords3 } ) );
  16782. vectorFormFactor.addAssign( LTC_EdgeVectorFormFactor( { v1: coords3, v2: coords0 } ) );
  16783. // adjust for horizon clipping
  16784. result.assign( vec3( LTC_ClippedSphereFormFactor( { f: vectorFormFactor.abs() } ) ) );
  16785. } );
  16786. return result;
  16787. } ).setLayout( {
  16788. name: 'LTC_Evaluate',
  16789. type: 'vec3',
  16790. inputs: [
  16791. { name: 'P', type: 'vec3' },
  16792. { name: 'p0', type: 'vec3' },
  16793. { name: 'p1', type: 'vec3' },
  16794. { name: 'p2', type: 'vec3' },
  16795. { name: 'p3', type: 'vec3' }
  16796. ]
  16797. } );
  16798. // Mipped Bicubic Texture Filtering by N8
  16799. // https://www.shadertoy.com/view/Dl2SDW
  16800. const bC = 1.0 / 6.0;
  16801. const w0 = ( a ) => mul( bC, mul( a, mul( a, a.negate().add( 3.0 ) ).sub( 3.0 ) ).add( 1.0 ) );
  16802. const w1 = ( a ) => mul( bC, mul( a, mul( a, mul( 3.0, a ).sub( 6.0 ) ) ).add( 4.0 ) );
  16803. const w2 = ( a ) => mul( bC, mul( a, mul( a, mul( -3, a ).add( 3.0 ) ).add( 3.0 ) ).add( 1.0 ) );
  16804. const w3 = ( a ) => mul( bC, pow( a, 3 ) );
  16805. const g0 = ( a ) => w0( a ).add( w1( a ) );
  16806. const g1 = ( a ) => w2( a ).add( w3( a ) );
  16807. // h0 and h1 are the two offset functions
  16808. const h0 = ( a ) => add( -1, w1( a ).div( w0( a ).add( w1( a ) ) ) );
  16809. const h1 = ( a ) => add( 1.0, w3( a ).div( w2( a ).add( w3( a ) ) ) );
  16810. const bicubic = ( textureNode, texelSize, lod ) => {
  16811. const uv = textureNode.uvNode;
  16812. const uvScaled = mul( uv, texelSize.zw ).add( 0.5 );
  16813. const iuv = floor( uvScaled );
  16814. const fuv = fract( uvScaled );
  16815. const g0x = g0( fuv.x );
  16816. const g1x = g1( fuv.x );
  16817. const h0x = h0( fuv.x );
  16818. const h1x = h1( fuv.x );
  16819. const h0y = h0( fuv.y );
  16820. const h1y = h1( fuv.y );
  16821. const p0 = vec2( iuv.x.add( h0x ), iuv.y.add( h0y ) ).sub( 0.5 ).mul( texelSize.xy );
  16822. const p1 = vec2( iuv.x.add( h1x ), iuv.y.add( h0y ) ).sub( 0.5 ).mul( texelSize.xy );
  16823. const p2 = vec2( iuv.x.add( h0x ), iuv.y.add( h1y ) ).sub( 0.5 ).mul( texelSize.xy );
  16824. const p3 = vec2( iuv.x.add( h1x ), iuv.y.add( h1y ) ).sub( 0.5 ).mul( texelSize.xy );
  16825. const a = g0( fuv.y ).mul( add( g0x.mul( textureNode.sample( p0 ).level( lod ) ), g1x.mul( textureNode.sample( p1 ).level( lod ) ) ) );
  16826. const b = g1( fuv.y ).mul( add( g0x.mul( textureNode.sample( p2 ).level( lod ) ), g1x.mul( textureNode.sample( p3 ).level( lod ) ) ) );
  16827. return a.add( b );
  16828. };
  16829. /**
  16830. * Applies mipped bicubic texture filtering to the given texture node.
  16831. *
  16832. * @tsl
  16833. * @function
  16834. * @param {TextureNode} textureNode - The texture node that should be filtered.
  16835. * @param {Node<float>} lodNode - Defines the LOD to sample from.
  16836. * @return {Node} The filtered texture sample.
  16837. */
  16838. const textureBicubicLevel = /*@__PURE__*/ Fn( ( [ textureNode, lodNode ] ) => {
  16839. const fLodSize = vec2( textureNode.size( int( lodNode ) ) );
  16840. const cLodSize = vec2( textureNode.size( int( lodNode.add( 1.0 ) ) ) );
  16841. const fLodSizeInv = div( 1.0, fLodSize );
  16842. const cLodSizeInv = div( 1.0, cLodSize );
  16843. const fSample = bicubic( textureNode, vec4( fLodSizeInv, fLodSize ), floor( lodNode ) );
  16844. const cSample = bicubic( textureNode, vec4( cLodSizeInv, cLodSize ), ceil( lodNode ) );
  16845. return fract( lodNode ).mix( fSample, cSample );
  16846. } );
  16847. /**
  16848. * Applies mipped bicubic texture filtering to the given texture node.
  16849. *
  16850. * @tsl
  16851. * @function
  16852. * @param {TextureNode} textureNode - The texture node that should be filtered.
  16853. * @param {Node<float>} [strength] - Defines the strength of the bicubic filtering.
  16854. * @return {Node} The filtered texture sample.
  16855. */
  16856. const textureBicubic = /*@__PURE__*/ Fn( ( [ textureNode, strength ] ) => {
  16857. const lod = strength.mul( maxMipLevel( textureNode ) );
  16858. return textureBicubicLevel( textureNode, lod );
  16859. } );
  16860. //
  16861. // Transmission
  16862. //
  16863. const getVolumeTransmissionRay = /*@__PURE__*/ Fn( ( [ n, v, thickness, ior, modelMatrix ] ) => {
  16864. // Direction of refracted light.
  16865. const refractionVector = vec3( refract( v.negate(), normalize( n ), div( 1.0, ior ) ) );
  16866. // Compute rotation-independent scaling of the model matrix.
  16867. const modelScale = vec3(
  16868. length( modelMatrix[ 0 ].xyz ),
  16869. length( modelMatrix[ 1 ].xyz ),
  16870. length( modelMatrix[ 2 ].xyz )
  16871. );
  16872. // The thickness is specified in local space.
  16873. return normalize( refractionVector ).mul( thickness.mul( modelScale ) );
  16874. } ).setLayout( {
  16875. name: 'getVolumeTransmissionRay',
  16876. type: 'vec3',
  16877. inputs: [
  16878. { name: 'n', type: 'vec3' },
  16879. { name: 'v', type: 'vec3' },
  16880. { name: 'thickness', type: 'float' },
  16881. { name: 'ior', type: 'float' },
  16882. { name: 'modelMatrix', type: 'mat4' }
  16883. ]
  16884. } );
  16885. const applyIorToRoughness = /*@__PURE__*/ Fn( ( [ roughness, ior ] ) => {
  16886. // Scale roughness with IOR so that an IOR of 1.0 results in no microfacet refraction and
  16887. // an IOR of 1.5 results in the default amount of microfacet refraction.
  16888. return roughness.mul( clamp( ior.mul( 2.0 ).sub( 2.0 ), 0.0, 1.0 ) );
  16889. } ).setLayout( {
  16890. name: 'applyIorToRoughness',
  16891. type: 'float',
  16892. inputs: [
  16893. { name: 'roughness', type: 'float' },
  16894. { name: 'ior', type: 'float' }
  16895. ]
  16896. } );
  16897. const viewportBackSideTexture = /*@__PURE__*/ viewportMipTexture();
  16898. const viewportFrontSideTexture = /*@__PURE__*/ viewportMipTexture();
  16899. const getTransmissionSample = /*@__PURE__*/ Fn( ( [ fragCoord, roughness, ior ], { material } ) => {
  16900. const vTexture = material.side === BackSide ? viewportBackSideTexture : viewportFrontSideTexture;
  16901. const transmissionSample = vTexture.sample( fragCoord );
  16902. //const transmissionSample = viewportMipTexture( fragCoord );
  16903. const lod = log2( screenSize.x ).mul( applyIorToRoughness( roughness, ior ) );
  16904. return textureBicubicLevel( transmissionSample, lod );
  16905. } );
  16906. const volumeAttenuation = /*@__PURE__*/ Fn( ( [ transmissionDistance, attenuationColor, attenuationDistance ] ) => {
  16907. If( attenuationDistance.notEqual( 0 ), () => {
  16908. // Compute light attenuation using Beer's law.
  16909. const attenuationCoefficient = log( attenuationColor ).negate().div( attenuationDistance );
  16910. const transmittance = exp( attenuationCoefficient.negate().mul( transmissionDistance ) );
  16911. return transmittance;
  16912. } );
  16913. // Attenuation distance is +∞, i.e. the transmitted color is not attenuated at all.
  16914. return vec3( 1.0 );
  16915. } ).setLayout( {
  16916. name: 'volumeAttenuation',
  16917. type: 'vec3',
  16918. inputs: [
  16919. { name: 'transmissionDistance', type: 'float' },
  16920. { name: 'attenuationColor', type: 'vec3' },
  16921. { name: 'attenuationDistance', type: 'float' }
  16922. ]
  16923. } );
  16924. const getIBLVolumeRefraction = /*@__PURE__*/ Fn( ( [ n, v, roughness, diffuseColor, specularColor, specularF90, position, modelMatrix, viewMatrix, projMatrix, ior, thickness, attenuationColor, attenuationDistance, dispersion ] ) => {
  16925. let transmittedLight, transmittance;
  16926. if ( dispersion ) {
  16927. transmittedLight = vec4().toVar();
  16928. transmittance = vec3().toVar();
  16929. const halfSpread = ior.sub( 1.0 ).mul( dispersion.mul( 0.025 ) );
  16930. const iors = vec3( ior.sub( halfSpread ), ior, ior.add( halfSpread ) );
  16931. Loop( { start: 0, end: 3 }, ( { i } ) => {
  16932. const ior = iors.element( i );
  16933. const transmissionRay = getVolumeTransmissionRay( n, v, thickness, ior, modelMatrix );
  16934. const refractedRayExit = position.add( transmissionRay );
  16935. // Project refracted vector on the framebuffer, while mapping to normalized device coordinates.
  16936. const ndcPos = projMatrix.mul( viewMatrix.mul( vec4( refractedRayExit, 1.0 ) ) );
  16937. const refractionCoords = vec2( ndcPos.xy.div( ndcPos.w ) ).toVar();
  16938. refractionCoords.addAssign( 1.0 );
  16939. refractionCoords.divAssign( 2.0 );
  16940. refractionCoords.assign( vec2( refractionCoords.x, refractionCoords.y.oneMinus() ) ); // webgpu
  16941. // Sample framebuffer to get pixel the refracted ray hits.
  16942. const transmissionSample = getTransmissionSample( refractionCoords, roughness, ior );
  16943. transmittedLight.element( i ).assign( transmissionSample.element( i ) );
  16944. transmittedLight.a.addAssign( transmissionSample.a );
  16945. transmittance.element( i ).assign( diffuseColor.element( i ).mul( volumeAttenuation( length( transmissionRay ), attenuationColor, attenuationDistance ).element( i ) ) );
  16946. } );
  16947. transmittedLight.a.divAssign( 3.0 );
  16948. } else {
  16949. const transmissionRay = getVolumeTransmissionRay( n, v, thickness, ior, modelMatrix );
  16950. const refractedRayExit = position.add( transmissionRay );
  16951. // Project refracted vector on the framebuffer, while mapping to normalized device coordinates.
  16952. const ndcPos = projMatrix.mul( viewMatrix.mul( vec4( refractedRayExit, 1.0 ) ) );
  16953. const refractionCoords = vec2( ndcPos.xy.div( ndcPos.w ) ).toVar();
  16954. refractionCoords.addAssign( 1.0 );
  16955. refractionCoords.divAssign( 2.0 );
  16956. refractionCoords.assign( vec2( refractionCoords.x, refractionCoords.y.oneMinus() ) ); // webgpu
  16957. // Sample framebuffer to get pixel the refracted ray hits.
  16958. transmittedLight = getTransmissionSample( refractionCoords, roughness, ior );
  16959. transmittance = diffuseColor.mul( volumeAttenuation( length( transmissionRay ), attenuationColor, attenuationDistance ) );
  16960. }
  16961. const attenuatedColor = transmittance.rgb.mul( transmittedLight.rgb );
  16962. const dotNV = n.dot( v ).clamp();
  16963. // Get the specular component.
  16964. const F = vec3( EnvironmentBRDF( { // n, v, specularColor, specularF90, roughness
  16965. dotNV,
  16966. specularColor,
  16967. specularF90,
  16968. roughness
  16969. } ) );
  16970. // As less light is transmitted, the opacity should be increased. This simple approximation does a decent job
  16971. // of modulating a CSS background, and has no effect when the buffer is opaque, due to a solid object or clear color.
  16972. const transmittanceFactor = transmittance.r.add( transmittance.g, transmittance.b ).div( 3.0 );
  16973. return vec4( F.oneMinus().mul( attenuatedColor ), transmittedLight.a.oneMinus().mul( transmittanceFactor ).oneMinus() );
  16974. } );
  16975. //
  16976. // Iridescence
  16977. //
  16978. // XYZ to linear-sRGB color space
  16979. const XYZ_TO_REC709 = /*@__PURE__*/ mat3(
  16980. 3.2404542, -0.969266, 0.0556434,
  16981. -1.5371385, 1.8760108, -0.2040259,
  16982. -0.4985314, 0.0415560, 1.0572252
  16983. );
  16984. // Assume air interface for top
  16985. // Note: We don't handle the case fresnel0 == 1
  16986. const Fresnel0ToIor = ( fresnel0 ) => {
  16987. const sqrtF0 = fresnel0.sqrt();
  16988. return vec3( 1.0 ).add( sqrtF0 ).div( vec3( 1.0 ).sub( sqrtF0 ) );
  16989. };
  16990. // ior is a value between 1.0 and 3.0. 1.0 is air interface
  16991. const IorToFresnel0 = ( transmittedIor, incidentIor ) => {
  16992. return transmittedIor.sub( incidentIor ).div( transmittedIor.add( incidentIor ) ).pow2();
  16993. };
  16994. // Fresnel equations for dielectric/dielectric interfaces.
  16995. // Ref: https://belcour.github.io/blog/research/2017/05/01/brdf-thin-film.html
  16996. // Evaluation XYZ sensitivity curves in Fourier space
  16997. const evalSensitivity = ( OPD, shift ) => {
  16998. const phase = OPD.mul( 2.0 * Math.PI * 1.0e-9 );
  16999. const val = vec3( 5.4856e-13, 4.4201e-13, 5.2481e-13 );
  17000. const pos = vec3( 1.6810e+06, 1.7953e+06, 2.2084e+06 );
  17001. const VAR = vec3( 4.3278e+09, 9.3046e+09, 6.6121e+09 );
  17002. 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() );
  17003. 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() );
  17004. xyz = vec3( xyz.x.add( x ), xyz.y, xyz.z ).div( 1.0685e-7 );
  17005. const rgb = XYZ_TO_REC709.mul( xyz );
  17006. return rgb;
  17007. };
  17008. const evalIridescence = /*@__PURE__*/ Fn( ( { outsideIOR, eta2, cosTheta1, thinFilmThickness, baseF0 } ) => {
  17009. // Force iridescenceIOR -> outsideIOR when thinFilmThickness -> 0.0
  17010. const iridescenceIOR = mix( outsideIOR, eta2, smoothstep( 0.0, 0.03, thinFilmThickness ) );
  17011. // Evaluate the cosTheta on the base layer (Snell law)
  17012. const sinTheta2Sq = outsideIOR.div( iridescenceIOR ).pow2().mul( cosTheta1.pow2().oneMinus() );
  17013. // Handle TIR:
  17014. const cosTheta2Sq = sinTheta2Sq.oneMinus();
  17015. If( cosTheta2Sq.lessThan( 0 ), () => {
  17016. return vec3( 1.0 );
  17017. } );
  17018. const cosTheta2 = cosTheta2Sq.sqrt();
  17019. // First interface
  17020. const R0 = IorToFresnel0( iridescenceIOR, outsideIOR );
  17021. const R12 = F_Schlick( { f0: R0, f90: 1.0, dotVH: cosTheta1 } );
  17022. //const R21 = R12;
  17023. const T121 = R12.oneMinus();
  17024. const phi12 = iridescenceIOR.lessThan( outsideIOR ).select( Math.PI, 0.0 );
  17025. const phi21 = float( Math.PI ).sub( phi12 );
  17026. // Second interface
  17027. const baseIOR = Fresnel0ToIor( baseF0.clamp( 0.0, 0.9999 ) ); // guard against 1.0
  17028. const R1 = IorToFresnel0( baseIOR, iridescenceIOR.toVec3() );
  17029. const R23 = F_Schlick( { f0: R1, f90: 1.0, dotVH: cosTheta2 } );
  17030. const phi23 = vec3(
  17031. baseIOR.x.lessThan( iridescenceIOR ).select( Math.PI, 0.0 ),
  17032. baseIOR.y.lessThan( iridescenceIOR ).select( Math.PI, 0.0 ),
  17033. baseIOR.z.lessThan( iridescenceIOR ).select( Math.PI, 0.0 )
  17034. );
  17035. // Phase shift
  17036. const OPD = iridescenceIOR.mul( thinFilmThickness, cosTheta2, 2.0 );
  17037. const phi = vec3( phi21 ).add( phi23 );
  17038. // Compound terms
  17039. const R123 = R12.mul( R23 ).clamp( 1e-5, 0.9999 );
  17040. const r123 = R123.sqrt();
  17041. const Rs = T121.pow2().mul( R23 ).div( vec3( 1.0 ).sub( R123 ) );
  17042. // Reflectance term for m = 0 (DC term amplitude)
  17043. const C0 = R12.add( Rs );
  17044. const I = C0.toVar();
  17045. // Reflectance term for m > 0 (pairs of diracs)
  17046. const Cm = Rs.sub( T121 ).toVar();
  17047. Loop( { start: 1, end: 2, condition: '<=', name: 'm' }, ( { m } ) => {
  17048. Cm.mulAssign( r123 );
  17049. const Sm = evalSensitivity( float( m ).mul( OPD ), float( m ).mul( phi ) ).mul( 2.0 );
  17050. I.addAssign( Cm.mul( Sm ) );
  17051. } );
  17052. // Since out of gamut colors might be produced, negative color values are clamped to 0.
  17053. return I.max( vec3( 0.0 ) );
  17054. } ).setLayout( {
  17055. name: 'evalIridescence',
  17056. type: 'vec3',
  17057. inputs: [
  17058. { name: 'outsideIOR', type: 'float' },
  17059. { name: 'eta2', type: 'float' },
  17060. { name: 'cosTheta1', type: 'float' },
  17061. { name: 'thinFilmThickness', type: 'float' },
  17062. { name: 'baseF0', type: 'vec3' }
  17063. ]
  17064. } );
  17065. //
  17066. // Sheen
  17067. //
  17068. // This is a curve-fit approximation to the "Charlie sheen" BRDF integrated over the hemisphere from
  17069. // Estevez and Kulla 2017, "Production Friendly Microfacet Sheen BRDF".
  17070. const IBLSheenBRDF = /*@__PURE__*/ Fn( ( { normal, viewDir, roughness } ) => {
  17071. const dotNV = normal.dot( viewDir ).saturate();
  17072. const r2 = roughness.mul( roughness );
  17073. const rInv = roughness.add( 0.1 ).reciprocal();
  17074. const a = float( -1.9362 ).add( roughness.mul( 1.0678 ) ).add( r2.mul( 0.4573 ) ).sub( rInv.mul( 0.8469 ) );
  17075. const b = float( -0.6014 ).add( roughness.mul( 0.5538 ) ).sub( r2.mul( 0.4670 ) ).sub( rInv.mul( 0.1255 ) );
  17076. const DG = a.mul( dotNV ).add( b ).exp();
  17077. return DG.saturate();
  17078. } );
  17079. const clearcoatF0 = vec3( 0.04 );
  17080. const clearcoatF90 = float( 1 );
  17081. /**
  17082. * Represents the lighting model for a PBR material.
  17083. *
  17084. * @augments LightingModel
  17085. */
  17086. class PhysicalLightingModel extends LightingModel {
  17087. /**
  17088. * Constructs a new physical lighting model.
  17089. *
  17090. * @param {boolean} [clearcoat=false] - Whether clearcoat is supported or not.
  17091. * @param {boolean} [sheen=false] - Whether sheen is supported or not.
  17092. * @param {boolean} [iridescence=false] - Whether iridescence is supported or not.
  17093. * @param {boolean} [anisotropy=false] - Whether anisotropy is supported or not.
  17094. * @param {boolean} [transmission=false] - Whether transmission is supported or not.
  17095. * @param {boolean} [dispersion=false] - Whether dispersion is supported or not.
  17096. */
  17097. constructor( clearcoat = false, sheen = false, iridescence = false, anisotropy = false, transmission = false, dispersion = false ) {
  17098. super();
  17099. /**
  17100. * Whether clearcoat is supported or not.
  17101. *
  17102. * @type {boolean}
  17103. * @default false
  17104. */
  17105. this.clearcoat = clearcoat;
  17106. /**
  17107. * Whether sheen is supported or not.
  17108. *
  17109. * @type {boolean}
  17110. * @default false
  17111. */
  17112. this.sheen = sheen;
  17113. /**
  17114. * Whether iridescence is supported or not.
  17115. *
  17116. * @type {boolean}
  17117. * @default false
  17118. */
  17119. this.iridescence = iridescence;
  17120. /**
  17121. * Whether anisotropy is supported or not.
  17122. *
  17123. * @type {boolean}
  17124. * @default false
  17125. */
  17126. this.anisotropy = anisotropy;
  17127. /**
  17128. * Whether transmission is supported or not.
  17129. *
  17130. * @type {boolean}
  17131. * @default false
  17132. */
  17133. this.transmission = transmission;
  17134. /**
  17135. * Whether dispersion is supported or not.
  17136. *
  17137. * @type {boolean}
  17138. * @default false
  17139. */
  17140. this.dispersion = dispersion;
  17141. /**
  17142. * The clear coat radiance.
  17143. *
  17144. * @type {?Node}
  17145. * @default null
  17146. */
  17147. this.clearcoatRadiance = null;
  17148. /**
  17149. * The clear coat specular direct.
  17150. *
  17151. * @type {?Node}
  17152. * @default null
  17153. */
  17154. this.clearcoatSpecularDirect = null;
  17155. /**
  17156. * The clear coat specular indirect.
  17157. *
  17158. * @type {?Node}
  17159. * @default null
  17160. */
  17161. this.clearcoatSpecularIndirect = null;
  17162. /**
  17163. * The sheen specular direct.
  17164. *
  17165. * @type {?Node}
  17166. * @default null
  17167. */
  17168. this.sheenSpecularDirect = null;
  17169. /**
  17170. * The sheen specular indirect.
  17171. *
  17172. * @type {?Node}
  17173. * @default null
  17174. */
  17175. this.sheenSpecularIndirect = null;
  17176. /**
  17177. * The iridescence Fresnel.
  17178. *
  17179. * @type {?Node}
  17180. * @default null
  17181. */
  17182. this.iridescenceFresnel = null;
  17183. /**
  17184. * The iridescence F0.
  17185. *
  17186. * @type {?Node}
  17187. * @default null
  17188. */
  17189. this.iridescenceF0 = null;
  17190. /**
  17191. * The iridescence F0 dielectric.
  17192. *
  17193. * @type {?Node}
  17194. * @default null
  17195. */
  17196. this.iridescenceF0Dielectric = null;
  17197. /**
  17198. * The iridescence F0 metallic.
  17199. *
  17200. * @type {?Node}
  17201. * @default null
  17202. */
  17203. this.iridescenceF0Metallic = null;
  17204. }
  17205. /**
  17206. * Depending on what features are requested, the method prepares certain node variables
  17207. * which are later used for lighting computations.
  17208. *
  17209. * @param {NodeBuilder} builder - The current node builder.
  17210. */
  17211. start( builder ) {
  17212. if ( this.clearcoat === true ) {
  17213. this.clearcoatRadiance = vec3().toVar( 'clearcoatRadiance' );
  17214. this.clearcoatSpecularDirect = vec3().toVar( 'clearcoatSpecularDirect' );
  17215. this.clearcoatSpecularIndirect = vec3().toVar( 'clearcoatSpecularIndirect' );
  17216. }
  17217. if ( this.sheen === true ) {
  17218. this.sheenSpecularDirect = vec3().toVar( 'sheenSpecularDirect' );
  17219. this.sheenSpecularIndirect = vec3().toVar( 'sheenSpecularIndirect' );
  17220. }
  17221. if ( this.iridescence === true ) {
  17222. const dotNVi = normalView.dot( positionViewDirection ).clamp();
  17223. const iridescenceFresnelDielectric = evalIridescence( {
  17224. outsideIOR: float( 1.0 ),
  17225. eta2: iridescenceIOR,
  17226. cosTheta1: dotNVi,
  17227. thinFilmThickness: iridescenceThickness,
  17228. baseF0: specularColor
  17229. } );
  17230. const iridescenceFresnelMetallic = evalIridescence( {
  17231. outsideIOR: float( 1.0 ),
  17232. eta2: iridescenceIOR,
  17233. cosTheta1: dotNVi,
  17234. thinFilmThickness: iridescenceThickness,
  17235. baseF0: diffuseColor.rgb
  17236. } );
  17237. this.iridescenceFresnel = mix( iridescenceFresnelDielectric, iridescenceFresnelMetallic, metalness );
  17238. this.iridescenceF0Dielectric = Schlick_to_F0( { f: iridescenceFresnelDielectric, f90: 1.0, dotVH: dotNVi } );
  17239. this.iridescenceF0Metallic = Schlick_to_F0( { f: iridescenceFresnelMetallic, f90: 1.0, dotVH: dotNVi } );
  17240. this.iridescenceF0 = mix( this.iridescenceF0Dielectric, this.iridescenceF0Metallic, metalness );
  17241. }
  17242. if ( this.transmission === true ) {
  17243. const position = positionWorld;
  17244. const v = cameraPosition.sub( positionWorld ).normalize(); // TODO: Create Node for this, same issue in MaterialX
  17245. const n = normalWorld;
  17246. const context = builder.context;
  17247. context.backdrop = getIBLVolumeRefraction(
  17248. n,
  17249. v,
  17250. roughness,
  17251. diffuseContribution,
  17252. specularColorBlended,
  17253. specularF90, // specularF90
  17254. position, // positionWorld
  17255. modelWorldMatrix, // modelMatrix
  17256. cameraViewMatrix, // viewMatrix
  17257. cameraProjectionMatrix, // projMatrix
  17258. ior,
  17259. thickness,
  17260. attenuationColor,
  17261. attenuationDistance,
  17262. this.dispersion ? dispersion : null
  17263. );
  17264. context.backdropAlpha = transmission;
  17265. diffuseColor.a.mulAssign( mix( 1, context.backdrop.a, transmission ) );
  17266. }
  17267. super.start( builder );
  17268. }
  17269. // Fdez-Agüera's "Multiple-Scattering Microfacet Model for Real-Time Image Based Lighting"
  17270. // Approximates multi-scattering in order to preserve energy.
  17271. // http://www.jcgt.org/published/0008/01/03/
  17272. computeMultiscattering( singleScatter, multiScatter, specularF90, f0, iridescenceF0 = null ) {
  17273. const dotNV = normalView.dot( positionViewDirection ).clamp(); // @ TODO: Move to core dotNV
  17274. const fab = DFGLUT( { roughness, dotNV } );
  17275. const Fr = iridescenceF0 ? iridescence.mix( f0, iridescenceF0 ) : f0;
  17276. const FssEss = Fr.mul( fab.x ).add( specularF90.mul( fab.y ) );
  17277. const Ess = fab.x.add( fab.y );
  17278. const Ems = Ess.oneMinus();
  17279. const Favg = Fr.add( Fr.oneMinus().mul( 0.047619 ) ); // 1/21
  17280. const Fms = FssEss.mul( Favg ).div( Ems.mul( Favg ).oneMinus() );
  17281. singleScatter.addAssign( FssEss );
  17282. multiScatter.addAssign( Fms.mul( Ems ) );
  17283. }
  17284. /**
  17285. * Implements the direct light.
  17286. *
  17287. * @param {Object} lightData - The light data.
  17288. * @param {NodeBuilder} builder - The current node builder.
  17289. */
  17290. direct( { lightDirection, lightColor, reflectedLight }, /* builder */ ) {
  17291. const dotNL = normalView.dot( lightDirection ).clamp();
  17292. const irradiance = dotNL.mul( lightColor ).toVar();
  17293. if ( this.sheen === true ) {
  17294. this.sheenSpecularDirect.addAssign( irradiance.mul( BRDF_Sheen( { lightDirection } ) ) );
  17295. const sheenAlbedoV = IBLSheenBRDF( { normal: normalView, viewDir: positionViewDirection, roughness: sheenRoughness } );
  17296. const sheenAlbedoL = IBLSheenBRDF( { normal: normalView, viewDir: lightDirection, roughness: sheenRoughness } );
  17297. const sheenEnergyComp = sheen.r.max( sheen.g ).max( sheen.b ).mul( sheenAlbedoV.max( sheenAlbedoL ) ).oneMinus();
  17298. irradiance.mulAssign( sheenEnergyComp );
  17299. }
  17300. if ( this.clearcoat === true ) {
  17301. const dotNLcc = clearcoatNormalView.dot( lightDirection ).clamp();
  17302. const ccIrradiance = dotNLcc.mul( lightColor );
  17303. this.clearcoatSpecularDirect.addAssign( ccIrradiance.mul( BRDF_GGX( { lightDirection, f0: clearcoatF0, f90: clearcoatF90, roughness: clearcoatRoughness, normalView: clearcoatNormalView } ) ) );
  17304. }
  17305. reflectedLight.directDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor: diffuseContribution } ) ) );
  17306. 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 } ) ) );
  17307. }
  17308. /**
  17309. * This method is intended for implementing the direct light term for
  17310. * rect area light nodes.
  17311. *
  17312. * @param {Object} input - The input data.
  17313. * @param {NodeBuilder} builder - The current node builder.
  17314. */
  17315. directRectArea( { lightColor, lightPosition, halfWidth, halfHeight, reflectedLight, ltc_1, ltc_2 }, /* builder */ ) {
  17316. const p0 = lightPosition.add( halfWidth ).sub( halfHeight ); // counterclockwise; light shines in local neg z direction
  17317. const p1 = lightPosition.sub( halfWidth ).sub( halfHeight );
  17318. const p2 = lightPosition.sub( halfWidth ).add( halfHeight );
  17319. const p3 = lightPosition.add( halfWidth ).add( halfHeight );
  17320. const N = normalView;
  17321. const V = positionViewDirection;
  17322. const P = positionView.toVar();
  17323. const uv = LTC_Uv( { N, V, roughness } );
  17324. const t1 = ltc_1.sample( uv ).toVar();
  17325. const t2 = ltc_2.sample( uv ).toVar();
  17326. const mInv = mat3(
  17327. vec3( t1.x, 0, t1.y ),
  17328. vec3( 0, 1, 0 ),
  17329. vec3( t1.z, 0, t1.w )
  17330. ).toVar();
  17331. // LTC Fresnel Approximation by Stephen Hill
  17332. // http://blog.selfshadow.com/publications/s2016-advances/s2016_ltc_fresnel.pdf
  17333. const fresnel = specularColorBlended.mul( t2.x ).add( specularColorBlended.oneMinus().mul( t2.y ) ).toVar();
  17334. reflectedLight.directSpecular.addAssign( lightColor.mul( fresnel ).mul( LTC_Evaluate( { N, V, P, mInv, p0, p1, p2, p3 } ) ) );
  17335. 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 } ) ) );
  17336. }
  17337. /**
  17338. * Implements the indirect lighting.
  17339. *
  17340. * @param {NodeBuilder} builder - The current node builder.
  17341. */
  17342. indirect( builder ) {
  17343. this.indirectDiffuse( builder );
  17344. this.indirectSpecular( builder );
  17345. this.ambientOcclusion( builder );
  17346. }
  17347. /**
  17348. * Implements the indirect diffuse term.
  17349. *
  17350. * @param {NodeBuilder} builder - The current node builder.
  17351. */
  17352. indirectDiffuse( builder ) {
  17353. const { irradiance, reflectedLight } = builder.context;
  17354. const diffuse = irradiance.mul( BRDF_Lambert( { diffuseColor: diffuseContribution } ) ).toVar();
  17355. if ( this.sheen === true ) {
  17356. const sheenAlbedo = IBLSheenBRDF( { normal: normalView, viewDir: positionViewDirection, roughness: sheenRoughness } );
  17357. const sheenEnergyComp = sheen.r.max( sheen.g ).max( sheen.b ).mul( sheenAlbedo ).oneMinus();
  17358. diffuse.mulAssign( sheenEnergyComp );
  17359. }
  17360. reflectedLight.indirectDiffuse.addAssign( diffuse );
  17361. }
  17362. /**
  17363. * Implements the indirect specular term.
  17364. *
  17365. * @param {NodeBuilder} builder - The current node builder.
  17366. */
  17367. indirectSpecular( builder ) {
  17368. const { radiance, iblIrradiance, reflectedLight } = builder.context;
  17369. if ( this.sheen === true ) {
  17370. this.sheenSpecularIndirect.addAssign( iblIrradiance.mul(
  17371. sheen,
  17372. IBLSheenBRDF( {
  17373. normal: normalView,
  17374. viewDir: positionViewDirection,
  17375. roughness: sheenRoughness
  17376. } )
  17377. ) );
  17378. }
  17379. if ( this.clearcoat === true ) {
  17380. const dotNVcc = clearcoatNormalView.dot( positionViewDirection ).clamp();
  17381. const clearcoatEnv = EnvironmentBRDF( {
  17382. dotNV: dotNVcc,
  17383. specularColor: clearcoatF0,
  17384. specularF90: clearcoatF90,
  17385. roughness: clearcoatRoughness
  17386. } );
  17387. this.clearcoatSpecularIndirect.addAssign( this.clearcoatRadiance.mul( clearcoatEnv ) );
  17388. }
  17389. // Both indirect specular and indirect diffuse light accumulate here
  17390. // Compute multiscattering separately for dielectric and metallic, then mix
  17391. const singleScatteringDielectric = vec3().toVar( 'singleScatteringDielectric' );
  17392. const multiScatteringDielectric = vec3().toVar( 'multiScatteringDielectric' );
  17393. const singleScatteringMetallic = vec3().toVar( 'singleScatteringMetallic' );
  17394. const multiScatteringMetallic = vec3().toVar( 'multiScatteringMetallic' );
  17395. this.computeMultiscattering( singleScatteringDielectric, multiScatteringDielectric, specularF90, specularColor, this.iridescenceF0Dielectric );
  17396. this.computeMultiscattering( singleScatteringMetallic, multiScatteringMetallic, specularF90, diffuseColor.rgb, this.iridescenceF0Metallic );
  17397. // Mix based on metalness
  17398. const singleScattering = mix( singleScatteringDielectric, singleScatteringMetallic, metalness );
  17399. const multiScattering = mix( multiScatteringDielectric, multiScatteringMetallic, metalness );
  17400. // Diffuse energy conservation uses dielectric path
  17401. const totalScatteringDielectric = singleScatteringDielectric.add( multiScatteringDielectric );
  17402. const diffuse = diffuseContribution.mul( totalScatteringDielectric.oneMinus() );
  17403. const cosineWeightedIrradiance = iblIrradiance.mul( 1 / Math.PI );
  17404. const indirectSpecular = radiance.mul( singleScattering ).add( multiScattering.mul( cosineWeightedIrradiance ) ).toVar();
  17405. const indirectDiffuse = diffuse.mul( cosineWeightedIrradiance ).toVar();
  17406. if ( this.sheen === true ) {
  17407. const sheenAlbedo = IBLSheenBRDF( { normal: normalView, viewDir: positionViewDirection, roughness: sheenRoughness } );
  17408. const sheenEnergyComp = sheen.r.max( sheen.g ).max( sheen.b ).mul( sheenAlbedo ).oneMinus();
  17409. indirectSpecular.mulAssign( sheenEnergyComp );
  17410. indirectDiffuse.mulAssign( sheenEnergyComp );
  17411. }
  17412. reflectedLight.indirectSpecular.addAssign( indirectSpecular );
  17413. reflectedLight.indirectDiffuse.addAssign( indirectDiffuse );
  17414. }
  17415. /**
  17416. * Implements the ambient occlusion term.
  17417. *
  17418. * @param {NodeBuilder} builder - The current node builder.
  17419. */
  17420. ambientOcclusion( builder ) {
  17421. const { ambientOcclusion, reflectedLight } = builder.context;
  17422. const dotNV = normalView.dot( positionViewDirection ).clamp(); // @ TODO: Move to core dotNV
  17423. const aoNV = dotNV.add( ambientOcclusion );
  17424. const aoExp = roughness.mul( -16 ).oneMinus().negate().exp2();
  17425. const aoNode = ambientOcclusion.sub( aoNV.pow( aoExp ).oneMinus() ).clamp();
  17426. if ( this.clearcoat === true ) {
  17427. this.clearcoatSpecularIndirect.mulAssign( ambientOcclusion );
  17428. }
  17429. if ( this.sheen === true ) {
  17430. this.sheenSpecularIndirect.mulAssign( ambientOcclusion );
  17431. }
  17432. reflectedLight.indirectDiffuse.mulAssign( ambientOcclusion );
  17433. reflectedLight.indirectSpecular.mulAssign( aoNode );
  17434. }
  17435. /**
  17436. * Used for final lighting accumulations depending on the requested features.
  17437. *
  17438. * @param {NodeBuilder} builder - The current node builder.
  17439. */
  17440. finish( { context } ) {
  17441. const { outgoingLight } = context;
  17442. if ( this.clearcoat === true ) {
  17443. const dotNVcc = clearcoatNormalView.dot( positionViewDirection ).clamp();
  17444. const Fcc = F_Schlick( {
  17445. dotVH: dotNVcc,
  17446. f0: clearcoatF0,
  17447. f90: clearcoatF90
  17448. } );
  17449. const clearcoatLight = outgoingLight.mul( clearcoat.mul( Fcc ).oneMinus() ).add( this.clearcoatSpecularDirect.add( this.clearcoatSpecularIndirect ).mul( clearcoat ) );
  17450. outgoingLight.assign( clearcoatLight );
  17451. }
  17452. if ( this.sheen === true ) {
  17453. const sheenLight = outgoingLight.add( this.sheenSpecularDirect, this.sheenSpecularIndirect.mul( 1.0 / Math.PI ) );
  17454. outgoingLight.assign( sheenLight );
  17455. }
  17456. }
  17457. }
  17458. // These defines must match with PMREMGenerator
  17459. const cubeUV_r0 = /*@__PURE__*/ float( 1.0 );
  17460. const cubeUV_m0 = /*@__PURE__*/ float( -2 );
  17461. const cubeUV_r1 = /*@__PURE__*/ float( 0.8 );
  17462. const cubeUV_m1 = /*@__PURE__*/ float( -1 );
  17463. const cubeUV_r4 = /*@__PURE__*/ float( 0.4 );
  17464. const cubeUV_m4 = /*@__PURE__*/ float( 2.0 );
  17465. const cubeUV_r5 = /*@__PURE__*/ float( 0.305 );
  17466. const cubeUV_m5 = /*@__PURE__*/ float( 3.0 );
  17467. const cubeUV_r6 = /*@__PURE__*/ float( 0.21 );
  17468. const cubeUV_m6 = /*@__PURE__*/ float( 4.0 );
  17469. const cubeUV_minMipLevel = /*@__PURE__*/ float( 4.0 );
  17470. const cubeUV_minTileSize = /*@__PURE__*/ float( 16.0 );
  17471. // These shader functions convert between the UV coordinates of a single face of
  17472. // a cubemap, the 0-5 integer index of a cube face, and the direction vector for
  17473. // sampling a textureCube (not generally normalized ).
  17474. const getFace = /*@__PURE__*/ Fn( ( [ direction ] ) => {
  17475. const absDirection = vec3( abs( direction ) ).toVar();
  17476. const face = float( -1 ).toVar();
  17477. If( absDirection.x.greaterThan( absDirection.z ), () => {
  17478. If( absDirection.x.greaterThan( absDirection.y ), () => {
  17479. face.assign( select( direction.x.greaterThan( 0.0 ), 0.0, 3.0 ) );
  17480. } ).Else( () => {
  17481. face.assign( select( direction.y.greaterThan( 0.0 ), 1.0, 4.0 ) );
  17482. } );
  17483. } ).Else( () => {
  17484. If( absDirection.z.greaterThan( absDirection.y ), () => {
  17485. face.assign( select( direction.z.greaterThan( 0.0 ), 2.0, 5.0 ) );
  17486. } ).Else( () => {
  17487. face.assign( select( direction.y.greaterThan( 0.0 ), 1.0, 4.0 ) );
  17488. } );
  17489. } );
  17490. return face;
  17491. } ).setLayout( {
  17492. name: 'getFace',
  17493. type: 'float',
  17494. inputs: [
  17495. { name: 'direction', type: 'vec3' }
  17496. ]
  17497. } );
  17498. // RH coordinate system; PMREM face-indexing convention
  17499. const getUV = /*@__PURE__*/ Fn( ( [ direction, face ] ) => {
  17500. const uv = vec2().toVar();
  17501. If( face.equal( 0.0 ), () => {
  17502. uv.assign( vec2( direction.z, direction.y ).div( abs( direction.x ) ) ); // pos x
  17503. } ).ElseIf( face.equal( 1.0 ), () => {
  17504. uv.assign( vec2( direction.x.negate(), direction.z.negate() ).div( abs( direction.y ) ) ); // pos y
  17505. } ).ElseIf( face.equal( 2.0 ), () => {
  17506. uv.assign( vec2( direction.x.negate(), direction.y ).div( abs( direction.z ) ) ); // pos z
  17507. } ).ElseIf( face.equal( 3.0 ), () => {
  17508. uv.assign( vec2( direction.z.negate(), direction.y ).div( abs( direction.x ) ) ); // neg x
  17509. } ).ElseIf( face.equal( 4.0 ), () => {
  17510. uv.assign( vec2( direction.x.negate(), direction.z ).div( abs( direction.y ) ) ); // neg y
  17511. } ).Else( () => {
  17512. uv.assign( vec2( direction.x, direction.y ).div( abs( direction.z ) ) ); // neg z
  17513. } );
  17514. return mul( 0.5, uv.add( 1.0 ) );
  17515. } ).setLayout( {
  17516. name: 'getUV',
  17517. type: 'vec2',
  17518. inputs: [
  17519. { name: 'direction', type: 'vec3' },
  17520. { name: 'face', type: 'float' }
  17521. ]
  17522. } );
  17523. const roughnessToMip = /*@__PURE__*/ Fn( ( [ roughness ] ) => {
  17524. const mip = float( 0.0 ).toVar();
  17525. If( roughness.greaterThanEqual( cubeUV_r1 ), () => {
  17526. mip.assign( cubeUV_r0.sub( roughness ).mul( cubeUV_m1.sub( cubeUV_m0 ) ).div( cubeUV_r0.sub( cubeUV_r1 ) ).add( cubeUV_m0 ) );
  17527. } ).ElseIf( roughness.greaterThanEqual( cubeUV_r4 ), () => {
  17528. mip.assign( cubeUV_r1.sub( roughness ).mul( cubeUV_m4.sub( cubeUV_m1 ) ).div( cubeUV_r1.sub( cubeUV_r4 ) ).add( cubeUV_m1 ) );
  17529. } ).ElseIf( roughness.greaterThanEqual( cubeUV_r5 ), () => {
  17530. mip.assign( cubeUV_r4.sub( roughness ).mul( cubeUV_m5.sub( cubeUV_m4 ) ).div( cubeUV_r4.sub( cubeUV_r5 ) ).add( cubeUV_m4 ) );
  17531. } ).ElseIf( roughness.greaterThanEqual( cubeUV_r6 ), () => {
  17532. mip.assign( cubeUV_r5.sub( roughness ).mul( cubeUV_m6.sub( cubeUV_m5 ) ).div( cubeUV_r5.sub( cubeUV_r6 ) ).add( cubeUV_m5 ) );
  17533. } ).Else( () => {
  17534. mip.assign( float( -2 ).mul( log2( mul( 1.16, roughness ) ) ) ); // 1.16 = 1.79^0.25
  17535. } );
  17536. return mip;
  17537. } ).setLayout( {
  17538. name: 'roughnessToMip',
  17539. type: 'float',
  17540. inputs: [
  17541. { name: 'roughness', type: 'float' }
  17542. ]
  17543. } );
  17544. // RH coordinate system; PMREM face-indexing convention
  17545. const getDirection = /*@__PURE__*/ Fn( ( [ uv_immutable, face ] ) => {
  17546. const uv = uv_immutable.toVar();
  17547. uv.assign( mul( 2.0, uv ).sub( 1.0 ) );
  17548. const direction = vec3( uv, 1.0 ).toVar();
  17549. If( face.equal( 0.0 ), () => {
  17550. direction.assign( direction.zyx ); // ( 1, v, u ) pos x
  17551. } ).ElseIf( face.equal( 1.0 ), () => {
  17552. direction.assign( direction.xzy );
  17553. direction.xz.mulAssign( -1 ); // ( -u, 1, -v ) pos y
  17554. } ).ElseIf( face.equal( 2.0 ), () => {
  17555. direction.x.mulAssign( -1 ); // ( -u, v, 1 ) pos z
  17556. } ).ElseIf( face.equal( 3.0 ), () => {
  17557. direction.assign( direction.zyx );
  17558. direction.xz.mulAssign( -1 ); // ( -1, v, -u ) neg x
  17559. } ).ElseIf( face.equal( 4.0 ), () => {
  17560. direction.assign( direction.xzy );
  17561. direction.xy.mulAssign( -1 ); // ( -u, -1, v ) neg y
  17562. } ).ElseIf( face.equal( 5.0 ), () => {
  17563. direction.z.mulAssign( -1 ); // ( u, v, -1 ) neg zS
  17564. } );
  17565. return direction;
  17566. } ).setLayout( {
  17567. name: 'getDirection',
  17568. type: 'vec3',
  17569. inputs: [
  17570. { name: 'uv', type: 'vec2' },
  17571. { name: 'face', type: 'float' }
  17572. ]
  17573. } );
  17574. //
  17575. const textureCubeUV = /*@__PURE__*/ Fn( ( [ envMap, sampleDir_immutable, roughness_immutable, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP ] ) => {
  17576. const roughness = float( roughness_immutable );
  17577. const sampleDir = vec3( sampleDir_immutable );
  17578. const mip = clamp( roughnessToMip( roughness ), cubeUV_m0, CUBEUV_MAX_MIP );
  17579. const mipF = fract( mip );
  17580. const mipInt = floor( mip );
  17581. const color0 = vec3( bilinearCubeUV( envMap, sampleDir, mipInt, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP ) ).toVar();
  17582. If( mipF.notEqual( 0.0 ), () => {
  17583. const color1 = vec3( bilinearCubeUV( envMap, sampleDir, mipInt.add( 1.0 ), CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP ) ).toVar();
  17584. color0.assign( mix( color0, color1, mipF ) );
  17585. } );
  17586. return color0;
  17587. } );
  17588. const bilinearCubeUV = /*@__PURE__*/ Fn( ( [ envMap, direction_immutable, mipInt_immutable, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP ] ) => {
  17589. const mipInt = float( mipInt_immutable ).toVar();
  17590. const direction = vec3( direction_immutable );
  17591. const face = float( getFace( direction ) ).toVar();
  17592. const filterInt = float( max$1( cubeUV_minMipLevel.sub( mipInt ), 0.0 ) ).toVar();
  17593. mipInt.assign( max$1( mipInt, cubeUV_minMipLevel ) );
  17594. const faceSize = float( exp2( mipInt ) ).toVar();
  17595. const uv = vec2( getUV( direction, face ).mul( faceSize.sub( 2.0 ) ).add( 1.0 ) ).toVar();
  17596. If( face.greaterThan( 2.0 ), () => {
  17597. uv.y.addAssign( faceSize );
  17598. face.subAssign( 3.0 );
  17599. } );
  17600. uv.x.addAssign( face.mul( faceSize ) );
  17601. uv.x.addAssign( filterInt.mul( mul( 3.0, cubeUV_minTileSize ) ) );
  17602. uv.y.addAssign( mul( 4.0, exp2( CUBEUV_MAX_MIP ).sub( faceSize ) ) );
  17603. uv.x.mulAssign( CUBEUV_TEXEL_WIDTH );
  17604. uv.y.mulAssign( CUBEUV_TEXEL_HEIGHT );
  17605. return envMap.sample( uv ).grad( vec2(), vec2() ); // disable anisotropic filtering
  17606. } );
  17607. const getSample = /*@__PURE__*/ Fn( ( { envMap, mipInt, outputDirection, theta, axis, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP } ) => {
  17608. const cosTheta = cos( theta );
  17609. // Rodrigues' axis-angle rotation
  17610. const sampleDirection = outputDirection.mul( cosTheta )
  17611. .add( axis.cross( outputDirection ).mul( sin( theta ) ) )
  17612. .add( axis.mul( axis.dot( outputDirection ).mul( cosTheta.oneMinus() ) ) );
  17613. return bilinearCubeUV( envMap, sampleDirection, mipInt, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP );
  17614. } );
  17615. const blur = /*@__PURE__*/ Fn( ( { n, latitudinal, poleAxis, outputDirection, weights, samples, dTheta, mipInt, envMap, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP } ) => {
  17616. const axis = vec3( select( latitudinal, poleAxis, cross( poleAxis, outputDirection ) ) ).toVar();
  17617. If( axis.equal( vec3( 0.0 ) ), () => {
  17618. axis.assign( vec3( outputDirection.z, 0.0, outputDirection.x.negate() ) );
  17619. } );
  17620. axis.assign( normalize( axis ) );
  17621. const gl_FragColor = vec3().toVar();
  17622. gl_FragColor.addAssign( weights.element( 0 ).mul( getSample( { theta: 0.0, axis, outputDirection, mipInt, envMap, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP } ) ) );
  17623. Loop( { start: int( 1 ), end: n }, ( { i } ) => {
  17624. If( i.greaterThanEqual( samples ), () => {
  17625. Break();
  17626. } );
  17627. const theta = float( dTheta.mul( float( i ) ) ).toVar();
  17628. 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 } ) ) );
  17629. gl_FragColor.addAssign( weights.element( i ).mul( getSample( { theta, axis, outputDirection, mipInt, envMap, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP } ) ) );
  17630. } );
  17631. return vec4( gl_FragColor, 1 );
  17632. } );
  17633. // GGX VNDF importance sampling functions
  17634. // Van der Corput radical inverse for generating quasi-random sequences
  17635. const radicalInverse_VdC = /*@__PURE__*/ Fn( ( [ bits_immutable ] ) => {
  17636. const bits = uint( bits_immutable ).toVar();
  17637. bits.assign( bits.shiftLeft( uint( 16 ) ).bitOr( bits.shiftRight( uint( 16 ) ) ) );
  17638. bits.assign( bits.bitAnd( uint( 0x55555555 ) ).shiftLeft( uint( 1 ) ).bitOr( bits.bitAnd( uint( 0xAAAAAAAA ) ).shiftRight( uint( 1 ) ) ) );
  17639. bits.assign( bits.bitAnd( uint( 0x33333333 ) ).shiftLeft( uint( 2 ) ).bitOr( bits.bitAnd( uint( 0xCCCCCCCC ) ).shiftRight( uint( 2 ) ) ) );
  17640. bits.assign( bits.bitAnd( uint( 0x0F0F0F0F ) ).shiftLeft( uint( 4 ) ).bitOr( bits.bitAnd( uint( 0xF0F0F0F0 ) ).shiftRight( uint( 4 ) ) ) );
  17641. bits.assign( bits.bitAnd( uint( 0x00FF00FF ) ).shiftLeft( uint( 8 ) ).bitOr( bits.bitAnd( uint( 0xFF00FF00 ) ).shiftRight( uint( 8 ) ) ) );
  17642. return float( bits ).mul( 2.3283064365386963e-10 ); // / 0x100000000
  17643. } );
  17644. // Hammersley sequence for quasi-Monte Carlo sampling
  17645. const hammersley = /*@__PURE__*/ Fn( ( [ i, N ] ) => {
  17646. return vec2( float( i ).div( float( N ) ), radicalInverse_VdC( i ) );
  17647. } );
  17648. // GGX VNDF importance sampling (Eric Heitz 2018)
  17649. // "Sampling the GGX Distribution of Visible Normals"
  17650. // https://jcgt.org/published/0007/04/01/
  17651. const importanceSampleGGX_VNDF = /*@__PURE__*/ Fn( ( [ Xi, V_immutable, roughness_immutable ] ) => {
  17652. const V = vec3( V_immutable ).toVar();
  17653. const roughness = float( roughness_immutable );
  17654. const alpha = roughness.mul( roughness ).toVar();
  17655. // Section 3.2: Transform view direction to hemisphere configuration
  17656. const Vh = normalize( vec3( alpha.mul( V.x ), alpha.mul( V.y ), V.z ) ).toVar();
  17657. // Section 4.1: Orthonormal basis
  17658. const lensq = Vh.x.mul( Vh.x ).add( Vh.y.mul( Vh.y ) );
  17659. 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();
  17660. const T2 = cross( Vh, T1 ).toVar();
  17661. // Section 4.2: Parameterization of projected area
  17662. const r = sqrt( Xi.x );
  17663. const phi = mul( 2.0, 3.14159265359 ).mul( Xi.y );
  17664. const t1 = r.mul( cos( phi ) ).toVar();
  17665. const t2 = r.mul( sin( phi ) ).toVar();
  17666. const s = mul( 0.5, Vh.z.add( 1.0 ) );
  17667. t2.assign( s.oneMinus().mul( sqrt( t1.mul( t1 ).oneMinus() ) ).add( s.mul( t2 ) ) );
  17668. // Section 4.3: Reprojection onto hemisphere
  17669. 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() ) ) ) );
  17670. // Section 3.4: Transform back to ellipsoid configuration
  17671. return normalize( vec3( alpha.mul( Nh.x ), alpha.mul( Nh.y ), max$1( 0.0, Nh.z ) ) );
  17672. } );
  17673. // GGX convolution using VNDF importance sampling
  17674. const ggxConvolution = /*@__PURE__*/ Fn( ( { roughness, mipInt, envMap, N_immutable, GGX_SAMPLES, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP } ) => {
  17675. const N = vec3( N_immutable ).toVar();
  17676. const prefilteredColor = vec3( 0.0 ).toVar();
  17677. const totalWeight = float( 0.0 ).toVar();
  17678. // For very low roughness, just sample the environment directly
  17679. If( roughness.lessThan( 0.001 ), () => {
  17680. prefilteredColor.assign( bilinearCubeUV( envMap, N, mipInt, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP ) );
  17681. } ).Else( () => {
  17682. // Tangent space basis for VNDF sampling
  17683. const up = select( abs( N.z ).lessThan( 0.999 ), vec3( 0.0, 0.0, 1.0 ), vec3( 1.0, 0.0, 0.0 ) );
  17684. const tangent = normalize( cross( up, N ) ).toVar();
  17685. const bitangent = cross( N, tangent ).toVar();
  17686. Loop( { start: uint( 0 ), end: GGX_SAMPLES }, ( { i } ) => {
  17687. const Xi = hammersley( i, GGX_SAMPLES );
  17688. // For PMREM, V = N, so in tangent space V is always (0, 0, 1)
  17689. const H_tangent = importanceSampleGGX_VNDF( Xi, vec3( 0.0, 0.0, 1.0 ), roughness );
  17690. // Transform H back to world space
  17691. const H = normalize( tangent.mul( H_tangent.x ).add( bitangent.mul( H_tangent.y ) ).add( N.mul( H_tangent.z ) ) );
  17692. const L = normalize( H.mul( dot( N, H ).mul( 2.0 ) ).sub( N ) );
  17693. const NdotL = max$1( dot( N, L ), 0.0 );
  17694. If( NdotL.greaterThan( 0.0 ), () => {
  17695. // Sample environment at fixed mip level
  17696. // VNDF importance sampling handles the distribution filtering
  17697. const sampleColor = bilinearCubeUV( envMap, L, mipInt, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP );
  17698. // Weight by NdotL for the split-sum approximation
  17699. // VNDF PDF naturally accounts for the visible microfacet distribution
  17700. prefilteredColor.addAssign( sampleColor.mul( NdotL ) );
  17701. totalWeight.addAssign( NdotL );
  17702. } );
  17703. } );
  17704. If( totalWeight.greaterThan( 0.0 ), () => {
  17705. prefilteredColor.assign( prefilteredColor.div( totalWeight ) );
  17706. } );
  17707. } );
  17708. return vec4( prefilteredColor, 1.0 );
  17709. } );
  17710. const LOD_MIN = 4;
  17711. // The standard deviations (radians) associated with the extra mips.
  17712. // Used for scene blur in fromScene() method.
  17713. const EXTRA_LOD_SIGMA = [ 0.125, 0.215, 0.35, 0.446, 0.526, 0.582 ];
  17714. // The maximum length of the blur for loop. Smaller sigmas will use fewer
  17715. // samples and exit early, but not recompile the shader.
  17716. // Used for scene blur in fromScene() method.
  17717. const MAX_SAMPLES = 20;
  17718. // GGX VNDF importance sampling configuration
  17719. const GGX_SAMPLES = 512;
  17720. const _flatCamera = /*@__PURE__*/ new OrthographicCamera( -1, 1, 1, -1, 0, 1 );
  17721. const _cubeCamera = /*@__PURE__*/ new PerspectiveCamera( 90, 1 );
  17722. const _clearColor$2 = /*@__PURE__*/ new Color();
  17723. let _oldTarget = null;
  17724. let _oldActiveCubeFace = 0;
  17725. let _oldActiveMipmapLevel = 0;
  17726. const _origin = /*@__PURE__*/ new Vector3();
  17727. // maps blur materials to their uniforms dictionary
  17728. const _uniformsMap = new WeakMap();
  17729. // WebGPU Face indices
  17730. const _faceLib = [
  17731. 3, 1, 5,
  17732. 0, 4, 2
  17733. ];
  17734. const _direction = /*@__PURE__*/ getDirection( uv$1(), attribute( 'faceIndex' ) ).normalize();
  17735. const _outputDirection = /*@__PURE__*/ vec3( _direction.x, _direction.y, _direction.z );
  17736. /**
  17737. * This class generates a Prefiltered, Mipmapped Radiance Environment Map
  17738. * (PMREM) from a cubeMap environment texture. This allows different levels of
  17739. * blur to be quickly accessed based on material roughness. It is packed into a
  17740. * special CubeUV format that allows us to perform custom interpolation so that
  17741. * we can support nonlinear formats such as RGBE. Unlike a traditional mipmap
  17742. * chain, it only goes down to the LOD_MIN level (above), and then creates extra
  17743. * even more filtered 'mips' at the same LOD_MIN resolution, associated with
  17744. * higher roughness levels. In this way we maintain resolution to smoothly
  17745. * interpolate diffuse lighting while limiting sampling computation.
  17746. *
  17747. * The prefiltering uses GGX VNDF (Visible Normal Distribution Function)
  17748. * importance sampling based on "Sampling the GGX Distribution of Visible Normals"
  17749. * (Heitz, 2018) to generate environment maps that accurately match the GGX BRDF
  17750. * used in material rendering for physically-based image-based lighting.
  17751. */
  17752. class PMREMGenerator {
  17753. /**
  17754. * Constructs a new PMREM generator.
  17755. *
  17756. * @param {Renderer} renderer - The renderer.
  17757. */
  17758. constructor( renderer ) {
  17759. this._renderer = renderer;
  17760. this._pingPongRenderTarget = null;
  17761. this._lodMax = 0;
  17762. this._cubeSize = 0;
  17763. this._sizeLods = [];
  17764. this._sigmas = [];
  17765. this._lodMeshes = [];
  17766. this._blurMaterial = null;
  17767. this._ggxMaterial = null;
  17768. this._cubemapMaterial = null;
  17769. this._equirectMaterial = null;
  17770. this._backgroundBox = null;
  17771. }
  17772. get _hasInitialized() {
  17773. return this._renderer.hasInitialized();
  17774. }
  17775. /**
  17776. * Generates a PMREM from a supplied Scene, which can be faster than using an
  17777. * image if networking bandwidth is low. Optional sigma specifies a blur radius
  17778. * in radians to be applied to the scene before PMREM generation. Optional near
  17779. * and far planes ensure the scene is rendered in its entirety.
  17780. *
  17781. * @param {Scene} scene - The scene to be captured.
  17782. * @param {number} [sigma=0] - The blur radius in radians.
  17783. * @param {number} [near=0.1] - The near plane distance.
  17784. * @param {number} [far=100] - The far plane distance.
  17785. * @param {Object} [options={}] - The configuration options.
  17786. * @param {number} [options.size=256] - The texture size of the PMREM.
  17787. * @param {Vector3} [options.renderTarget=origin] - The position of the internal cube camera that renders the scene.
  17788. * @param {?RenderTarget} [options.renderTarget=null] - The render target to use.
  17789. * @return {RenderTarget} The resulting PMREM.
  17790. * @see {@link PMREMGenerator#fromScene}
  17791. */
  17792. fromScene( scene, sigma = 0, near = 0.1, far = 100, options = {} ) {
  17793. const {
  17794. size = 256,
  17795. position = _origin,
  17796. renderTarget = null,
  17797. } = options;
  17798. this._setSize( size );
  17799. if ( this._hasInitialized === false ) {
  17800. warn( 'PMREMGenerator: ".fromScene()" called before the backend is initialized. Try using "await renderer.init()" instead.' );
  17801. const cubeUVRenderTarget = renderTarget || this._allocateTarget();
  17802. options.renderTarget = cubeUVRenderTarget;
  17803. this.fromSceneAsync( scene, sigma, near, far, options );
  17804. return cubeUVRenderTarget;
  17805. }
  17806. _oldTarget = this._renderer.getRenderTarget();
  17807. _oldActiveCubeFace = this._renderer.getActiveCubeFace();
  17808. _oldActiveMipmapLevel = this._renderer.getActiveMipmapLevel();
  17809. const cubeUVRenderTarget = renderTarget || this._allocateTarget();
  17810. cubeUVRenderTarget.depthBuffer = true;
  17811. this._init( cubeUVRenderTarget );
  17812. this._sceneToCubeUV( scene, near, far, cubeUVRenderTarget, position );
  17813. if ( sigma > 0 ) {
  17814. this._blur( cubeUVRenderTarget, 0, 0, sigma );
  17815. }
  17816. this._applyPMREM( cubeUVRenderTarget );
  17817. this._cleanup( cubeUVRenderTarget );
  17818. return cubeUVRenderTarget;
  17819. }
  17820. /**
  17821. * Generates a PMREM from a supplied Scene, which can be faster than using an
  17822. * image if networking bandwidth is low. Optional sigma specifies a blur radius
  17823. * in radians to be applied to the scene before PMREM generation. Optional near
  17824. * and far planes ensure the scene is rendered in its entirety (the cubeCamera
  17825. * is placed at the origin).
  17826. *
  17827. * @deprecated
  17828. * @param {Scene} scene - The scene to be captured.
  17829. * @param {number} [sigma=0] - The blur radius in radians.
  17830. * @param {number} [near=0.1] - The near plane distance.
  17831. * @param {number} [far=100] - The far plane distance.
  17832. * @param {Object} [options={}] - The configuration options.
  17833. * @param {number} [options.size=256] - The texture size of the PMREM.
  17834. * @param {Vector3} [options.position=origin] - The position of the internal cube camera that renders the scene.
  17835. * @param {?RenderTarget} [options.renderTarget=null] - The render target to use.
  17836. * @return {Promise<RenderTarget>} A Promise that resolve with the PMREM when the generation has been finished.
  17837. * @see {@link PMREMGenerator#fromScene}
  17838. */
  17839. async fromSceneAsync( scene, sigma = 0, near = 0.1, far = 100, options = {} ) {
  17840. warnOnce( 'PMREMGenerator: ".fromSceneAsync()" is deprecated. Use "await renderer.init()" instead.' ); // @deprecated r181
  17841. await this._renderer.init();
  17842. return this.fromScene( scene, sigma, near, far, options );
  17843. }
  17844. /**
  17845. * Generates a PMREM from an equirectangular texture, which can be either LDR
  17846. * or HDR. The ideal input image size is 1k (1024 x 512),
  17847. * as this matches best with the 256 x 256 cubemap output.
  17848. *
  17849. * @param {Texture} equirectangular - The equirectangular texture to be converted.
  17850. * @param {?RenderTarget} [renderTarget=null] - The render target to use.
  17851. * @return {RenderTarget} The resulting PMREM.
  17852. * @see {@link PMREMGenerator#fromEquirectangularAsync}
  17853. */
  17854. fromEquirectangular( equirectangular, renderTarget = null ) {
  17855. if ( this._hasInitialized === false ) {
  17856. warn( 'PMREMGenerator: .fromEquirectangular() called before the backend is initialized. Try using "await renderer.init()" instead.' );
  17857. this._setSizeFromTexture( equirectangular );
  17858. const cubeUVRenderTarget = renderTarget || this._allocateTarget();
  17859. this.fromEquirectangularAsync( equirectangular, cubeUVRenderTarget );
  17860. return cubeUVRenderTarget;
  17861. }
  17862. return this._fromTexture( equirectangular, renderTarget );
  17863. }
  17864. /**
  17865. * Generates a PMREM from an equirectangular texture, which can be either LDR
  17866. * or HDR. The ideal input image size is 1k (1024 x 512),
  17867. * as this matches best with the 256 x 256 cubemap output.
  17868. *
  17869. * @deprecated
  17870. * @param {Texture} equirectangular - The equirectangular texture to be converted.
  17871. * @param {?RenderTarget} [renderTarget=null] - The render target to use.
  17872. * @return {Promise<RenderTarget>} The resulting PMREM.
  17873. * @see {@link PMREMGenerator#fromEquirectangular}
  17874. */
  17875. async fromEquirectangularAsync( equirectangular, renderTarget = null ) {
  17876. warnOnce( 'PMREMGenerator: ".fromEquirectangularAsync()" is deprecated. Use "await renderer.init()" instead.' ); // @deprecated r181
  17877. await this._renderer.init();
  17878. return this._fromTexture( equirectangular, renderTarget );
  17879. }
  17880. /**
  17881. * Generates a PMREM from an cubemap texture, which can be either LDR
  17882. * or HDR. The ideal input cube size is 256 x 256,
  17883. * as this matches best with the 256 x 256 cubemap output.
  17884. *
  17885. * @param {Texture} cubemap - The cubemap texture to be converted.
  17886. * @param {?RenderTarget} [renderTarget=null] - The render target to use.
  17887. * @return {RenderTarget} The resulting PMREM.
  17888. * @see {@link PMREMGenerator#fromCubemapAsync}
  17889. */
  17890. fromCubemap( cubemap, renderTarget = null ) {
  17891. if ( this._hasInitialized === false ) {
  17892. warn( 'PMREMGenerator: .fromCubemap() called before the backend is initialized. Try using .fromCubemapAsync() instead.' );
  17893. this._setSizeFromTexture( cubemap );
  17894. const cubeUVRenderTarget = renderTarget || this._allocateTarget();
  17895. this.fromCubemapAsync( cubemap, renderTarget );
  17896. return cubeUVRenderTarget;
  17897. }
  17898. return this._fromTexture( cubemap, renderTarget );
  17899. }
  17900. /**
  17901. * Generates a PMREM from an cubemap texture, which can be either LDR
  17902. * or HDR. The ideal input cube size is 256 x 256,
  17903. * with the 256 x 256 cubemap output.
  17904. *
  17905. * @deprecated
  17906. * @param {Texture} cubemap - The cubemap texture to be converted.
  17907. * @param {?RenderTarget} [renderTarget=null] - The render target to use.
  17908. * @return {Promise<RenderTarget>} The resulting PMREM.
  17909. * @see {@link PMREMGenerator#fromCubemap}
  17910. */
  17911. async fromCubemapAsync( cubemap, renderTarget = null ) {
  17912. warnOnce( 'PMREMGenerator: ".fromCubemapAsync()" is deprecated. Use "await renderer.init()" instead.' ); // @deprecated r181
  17913. await this._renderer.init();
  17914. return this._fromTexture( cubemap, renderTarget );
  17915. }
  17916. /**
  17917. * Pre-compiles the cubemap shader. You can get faster start-up by invoking this method during
  17918. * your texture's network fetch for increased concurrency.
  17919. *
  17920. * @returns {Promise}
  17921. */
  17922. async compileCubemapShader() {
  17923. if ( this._cubemapMaterial === null ) {
  17924. this._cubemapMaterial = _getCubemapMaterial();
  17925. await this._compileMaterial( this._cubemapMaterial );
  17926. }
  17927. }
  17928. /**
  17929. * Pre-compiles the equirectangular shader. You can get faster start-up by invoking this method during
  17930. * your texture's network fetch for increased concurrency.
  17931. *
  17932. * @returns {Promise}
  17933. */
  17934. async compileEquirectangularShader() {
  17935. if ( this._equirectMaterial === null ) {
  17936. this._equirectMaterial = _getEquirectMaterial();
  17937. await this._compileMaterial( this._equirectMaterial );
  17938. }
  17939. }
  17940. /**
  17941. * Disposes of the PMREMGenerator's internal memory. Note that PMREMGenerator is a static class,
  17942. * so you should not need more than one PMREMGenerator object. If you do, calling dispose() on
  17943. * one of them will cause any others to also become unusable.
  17944. */
  17945. dispose() {
  17946. this._dispose();
  17947. if ( this._cubemapMaterial !== null ) this._cubemapMaterial.dispose();
  17948. if ( this._equirectMaterial !== null ) this._equirectMaterial.dispose();
  17949. if ( this._backgroundBox !== null ) {
  17950. this._backgroundBox.geometry.dispose();
  17951. this._backgroundBox.material.dispose();
  17952. }
  17953. }
  17954. // private interface
  17955. _setSizeFromTexture( texture ) {
  17956. if ( texture.mapping === CubeReflectionMapping || texture.mapping === CubeRefractionMapping ) {
  17957. this._setSize( texture.image.length === 0 ? 16 : ( texture.image[ 0 ].width || texture.image[ 0 ].image.width ) );
  17958. } else { // Equirectangular
  17959. this._setSize( texture.image.width / 4 );
  17960. }
  17961. }
  17962. _setSize( cubeSize ) {
  17963. this._lodMax = Math.floor( Math.log2( cubeSize ) );
  17964. this._cubeSize = Math.pow( 2, this._lodMax );
  17965. }
  17966. _dispose() {
  17967. if ( this._blurMaterial !== null ) this._blurMaterial.dispose();
  17968. if ( this._ggxMaterial !== null ) this._ggxMaterial.dispose();
  17969. if ( this._pingPongRenderTarget !== null ) this._pingPongRenderTarget.dispose();
  17970. for ( let i = 0; i < this._lodMeshes.length; i ++ ) {
  17971. this._lodMeshes[ i ].geometry.dispose();
  17972. }
  17973. }
  17974. _cleanup( outputTarget ) {
  17975. this._renderer.setRenderTarget( _oldTarget, _oldActiveCubeFace, _oldActiveMipmapLevel );
  17976. outputTarget.scissorTest = false;
  17977. _setViewport( outputTarget, 0, 0, outputTarget.width, outputTarget.height );
  17978. }
  17979. _fromTexture( texture, renderTarget ) {
  17980. this._setSizeFromTexture( texture );
  17981. _oldTarget = this._renderer.getRenderTarget();
  17982. _oldActiveCubeFace = this._renderer.getActiveCubeFace();
  17983. _oldActiveMipmapLevel = this._renderer.getActiveMipmapLevel();
  17984. const cubeUVRenderTarget = renderTarget || this._allocateTarget();
  17985. this._init( cubeUVRenderTarget );
  17986. this._textureToCubeUV( texture, cubeUVRenderTarget );
  17987. this._applyPMREM( cubeUVRenderTarget );
  17988. this._cleanup( cubeUVRenderTarget );
  17989. return cubeUVRenderTarget;
  17990. }
  17991. _allocateTarget() {
  17992. const width = 3 * Math.max( this._cubeSize, 16 * 7 );
  17993. const height = 4 * this._cubeSize;
  17994. const cubeUVRenderTarget = _createRenderTarget( width, height );
  17995. return cubeUVRenderTarget;
  17996. }
  17997. _init( renderTarget ) {
  17998. if ( this._pingPongRenderTarget === null || this._pingPongRenderTarget.width !== renderTarget.width || this._pingPongRenderTarget.height !== renderTarget.height ) {
  17999. if ( this._pingPongRenderTarget !== null ) {
  18000. this._dispose();
  18001. }
  18002. this._pingPongRenderTarget = _createRenderTarget( renderTarget.width, renderTarget.height );
  18003. const { _lodMax } = this;
  18004. ( { lodMeshes: this._lodMeshes, sizeLods: this._sizeLods, sigmas: this._sigmas } = _createPlanes( _lodMax ) );
  18005. this._blurMaterial = _getBlurShader( _lodMax, renderTarget.width, renderTarget.height );
  18006. this._ggxMaterial = _getGGXShader( _lodMax, renderTarget.width, renderTarget.height );
  18007. }
  18008. }
  18009. async _compileMaterial( material ) {
  18010. const mesh = new Mesh( new BufferGeometry(), material );
  18011. await this._renderer.compile( mesh, _flatCamera );
  18012. }
  18013. _sceneToCubeUV( scene, near, far, cubeUVRenderTarget, position ) {
  18014. const cubeCamera = _cubeCamera;
  18015. cubeCamera.near = near;
  18016. cubeCamera.far = far;
  18017. // px, py, pz, nx, ny, nz
  18018. const upSign = [ 1, 1, 1, 1, -1, 1 ];
  18019. const forwardSign = [ 1, -1, 1, -1, 1, -1 ];
  18020. const renderer = this._renderer;
  18021. const originalAutoClear = renderer.autoClear;
  18022. renderer.getClearColor( _clearColor$2 );
  18023. renderer.autoClear = false;
  18024. if ( this._backgroundBox === null ) {
  18025. this._backgroundBox = new Mesh(
  18026. new BoxGeometry(),
  18027. new MeshBasicMaterial( {
  18028. name: 'PMREM.Background',
  18029. side: BackSide,
  18030. depthWrite: false,
  18031. depthTest: false,
  18032. } )
  18033. );
  18034. }
  18035. const backgroundBox = this._backgroundBox;
  18036. const backgroundMaterial = backgroundBox.material;
  18037. let useSolidColor = false;
  18038. const background = scene.background;
  18039. if ( background ) {
  18040. if ( background.isColor ) {
  18041. backgroundMaterial.color.copy( background );
  18042. scene.background = null;
  18043. useSolidColor = true;
  18044. }
  18045. } else {
  18046. backgroundMaterial.color.copy( _clearColor$2 );
  18047. useSolidColor = true;
  18048. }
  18049. renderer.setRenderTarget( cubeUVRenderTarget );
  18050. renderer.clear();
  18051. if ( useSolidColor ) {
  18052. renderer.render( backgroundBox, cubeCamera );
  18053. }
  18054. for ( let i = 0; i < 6; i ++ ) {
  18055. const col = i % 3;
  18056. if ( col === 0 ) {
  18057. cubeCamera.up.set( 0, upSign[ i ], 0 );
  18058. cubeCamera.position.set( position.x, position.y, position.z );
  18059. cubeCamera.lookAt( position.x + forwardSign[ i ], position.y, position.z );
  18060. } else if ( col === 1 ) {
  18061. cubeCamera.up.set( 0, 0, upSign[ i ] );
  18062. cubeCamera.position.set( position.x, position.y, position.z );
  18063. cubeCamera.lookAt( position.x, position.y + forwardSign[ i ], position.z );
  18064. } else {
  18065. cubeCamera.up.set( 0, upSign[ i ], 0 );
  18066. cubeCamera.position.set( position.x, position.y, position.z );
  18067. cubeCamera.lookAt( position.x, position.y, position.z + forwardSign[ i ] );
  18068. }
  18069. const size = this._cubeSize;
  18070. _setViewport( cubeUVRenderTarget, col * size, i > 2 ? size : 0, size, size );
  18071. renderer.render( scene, cubeCamera );
  18072. }
  18073. renderer.autoClear = originalAutoClear;
  18074. scene.background = background;
  18075. }
  18076. _textureToCubeUV( texture, cubeUVRenderTarget ) {
  18077. const renderer = this._renderer;
  18078. const isCubeTexture = ( texture.mapping === CubeReflectionMapping || texture.mapping === CubeRefractionMapping );
  18079. if ( isCubeTexture ) {
  18080. if ( this._cubemapMaterial === null ) {
  18081. this._cubemapMaterial = _getCubemapMaterial( texture );
  18082. }
  18083. } else {
  18084. if ( this._equirectMaterial === null ) {
  18085. this._equirectMaterial = _getEquirectMaterial( texture );
  18086. }
  18087. }
  18088. const material = isCubeTexture ? this._cubemapMaterial : this._equirectMaterial;
  18089. material.fragmentNode.value = texture;
  18090. const mesh = this._lodMeshes[ 0 ];
  18091. mesh.material = material;
  18092. const size = this._cubeSize;
  18093. _setViewport( cubeUVRenderTarget, 0, 0, 3 * size, 2 * size );
  18094. renderer.setRenderTarget( cubeUVRenderTarget );
  18095. renderer.render( mesh, _flatCamera );
  18096. }
  18097. _applyPMREM( cubeUVRenderTarget ) {
  18098. const renderer = this._renderer;
  18099. const autoClear = renderer.autoClear;
  18100. renderer.autoClear = false;
  18101. const n = this._lodMeshes.length;
  18102. // Use GGX VNDF importance sampling
  18103. for ( let i = 1; i < n; i ++ ) {
  18104. this._applyGGXFilter( cubeUVRenderTarget, i - 1, i );
  18105. }
  18106. renderer.autoClear = autoClear;
  18107. }
  18108. /**
  18109. * Applies GGX VNDF importance sampling filter to generate a prefiltered environment map.
  18110. * Uses Monte Carlo integration with VNDF importance sampling to accurately represent the
  18111. * GGX BRDF for physically-based rendering. Reads from the previous LOD level and
  18112. * applies incremental roughness filtering to avoid over-blurring.
  18113. *
  18114. * @private
  18115. * @param {RenderTarget} cubeUVRenderTarget
  18116. * @param {number} lodIn - Source LOD level to read from
  18117. * @param {number} lodOut - Target LOD level to write to
  18118. */
  18119. _applyGGXFilter( cubeUVRenderTarget, lodIn, lodOut ) {
  18120. const renderer = this._renderer;
  18121. const pingPongRenderTarget = this._pingPongRenderTarget;
  18122. const ggxMaterial = this._ggxMaterial;
  18123. const ggxMesh = this._lodMeshes[ lodOut ];
  18124. ggxMesh.material = ggxMaterial;
  18125. const ggxUniforms = _uniformsMap.get( ggxMaterial );
  18126. // Calculate incremental roughness between LOD levels
  18127. const targetRoughness = lodOut / ( this._lodMeshes.length - 1 );
  18128. const sourceRoughness = lodIn / ( this._lodMeshes.length - 1 );
  18129. const incrementalRoughness = Math.sqrt( targetRoughness * targetRoughness - sourceRoughness * sourceRoughness );
  18130. // Apply blur strength mapping for better quality across the roughness range
  18131. const blurStrength = 0.0 + targetRoughness * 1.25;
  18132. const adjustedRoughness = incrementalRoughness * blurStrength;
  18133. // Calculate viewport position based on output LOD level
  18134. const { _lodMax } = this;
  18135. const outputSize = this._sizeLods[ lodOut ];
  18136. const x = 3 * outputSize * ( lodOut > _lodMax - LOD_MIN ? lodOut - _lodMax + LOD_MIN : 0 );
  18137. const y = 4 * ( this._cubeSize - outputSize );
  18138. // Read from previous LOD with incremental roughness
  18139. cubeUVRenderTarget.texture.frame = ( cubeUVRenderTarget.texture.frame || 0 ) + 1;
  18140. ggxUniforms.envMap.value = cubeUVRenderTarget.texture;
  18141. ggxUniforms.roughness.value = adjustedRoughness;
  18142. ggxUniforms.mipInt.value = _lodMax - lodIn; // Sample from input LOD
  18143. _setViewport( pingPongRenderTarget, x, y, 3 * outputSize, 2 * outputSize );
  18144. renderer.setRenderTarget( pingPongRenderTarget );
  18145. renderer.render( ggxMesh, _flatCamera );
  18146. // Copy from pingPong back to cubeUV (simple direct copy)
  18147. pingPongRenderTarget.texture.frame = ( pingPongRenderTarget.texture.frame || 0 ) + 1;
  18148. ggxUniforms.envMap.value = pingPongRenderTarget.texture;
  18149. ggxUniforms.roughness.value = 0.0; // Direct copy
  18150. ggxUniforms.mipInt.value = _lodMax - lodOut; // Read from the level we just wrote
  18151. _setViewport( cubeUVRenderTarget, x, y, 3 * outputSize, 2 * outputSize );
  18152. renderer.setRenderTarget( cubeUVRenderTarget );
  18153. renderer.render( ggxMesh, _flatCamera );
  18154. }
  18155. /**
  18156. * This is a two-pass Gaussian blur for a cubemap. Normally this is done
  18157. * vertically and horizontally, but this breaks down on a cube. Here we apply
  18158. * the blur latitudinally (around the poles), and then longitudinally (towards
  18159. * the poles) to approximate the orthogonally-separable blur. It is least
  18160. * accurate at the poles, but still does a decent job.
  18161. *
  18162. * Used for initial scene blur in fromScene() method when sigma > 0.
  18163. *
  18164. * @private
  18165. * @param {RenderTarget} cubeUVRenderTarget - The cubemap render target.
  18166. * @param {number} lodIn - The input level-of-detail.
  18167. * @param {number} lodOut - The output level-of-detail.
  18168. * @param {number} sigma - The blur radius in radians.
  18169. * @param {Vector3} [poleAxis] - The pole axis.
  18170. */
  18171. _blur( cubeUVRenderTarget, lodIn, lodOut, sigma, poleAxis ) {
  18172. const pingPongRenderTarget = this._pingPongRenderTarget;
  18173. this._halfBlur(
  18174. cubeUVRenderTarget,
  18175. pingPongRenderTarget,
  18176. lodIn,
  18177. lodOut,
  18178. sigma,
  18179. 'latitudinal',
  18180. poleAxis );
  18181. this._halfBlur(
  18182. pingPongRenderTarget,
  18183. cubeUVRenderTarget,
  18184. lodOut,
  18185. lodOut,
  18186. sigma,
  18187. 'longitudinal',
  18188. poleAxis );
  18189. }
  18190. _halfBlur( targetIn, targetOut, lodIn, lodOut, sigmaRadians, direction, poleAxis ) {
  18191. const renderer = this._renderer;
  18192. const blurMaterial = this._blurMaterial;
  18193. if ( direction !== 'latitudinal' && direction !== 'longitudinal' ) {
  18194. error( 'blur direction must be either latitudinal or longitudinal!' );
  18195. }
  18196. // Number of standard deviations at which to cut off the discrete approximation.
  18197. const STANDARD_DEVIATIONS = 3;
  18198. const blurMesh = this._lodMeshes[ lodOut ];
  18199. blurMesh.material = blurMaterial;
  18200. const blurUniforms = _uniformsMap.get( blurMaterial );
  18201. const pixels = this._sizeLods[ lodIn ] - 1;
  18202. const radiansPerPixel = isFinite( sigmaRadians ) ? Math.PI / ( 2 * pixels ) : 2 * Math.PI / ( 2 * MAX_SAMPLES - 1 );
  18203. const sigmaPixels = sigmaRadians / radiansPerPixel;
  18204. const samples = isFinite( sigmaRadians ) ? 1 + Math.floor( STANDARD_DEVIATIONS * sigmaPixels ) : MAX_SAMPLES;
  18205. if ( samples > MAX_SAMPLES ) {
  18206. warn( `sigmaRadians, ${
  18207. sigmaRadians}, is too large and will clip, as it requested ${
  18208. samples} samples when the maximum is set to ${MAX_SAMPLES}` );
  18209. }
  18210. const weights = [];
  18211. let sum = 0;
  18212. for ( let i = 0; i < MAX_SAMPLES; ++ i ) {
  18213. const x = i / sigmaPixels;
  18214. const weight = Math.exp( - x * x / 2 );
  18215. weights.push( weight );
  18216. if ( i === 0 ) {
  18217. sum += weight;
  18218. } else if ( i < samples ) {
  18219. sum += 2 * weight;
  18220. }
  18221. }
  18222. for ( let i = 0; i < weights.length; i ++ ) {
  18223. weights[ i ] = weights[ i ] / sum;
  18224. }
  18225. targetIn.texture.frame = ( targetIn.texture.frame || 0 ) + 1;
  18226. blurUniforms.envMap.value = targetIn.texture;
  18227. blurUniforms.samples.value = samples;
  18228. blurUniforms.weights.array = weights;
  18229. blurUniforms.latitudinal.value = direction === 'latitudinal' ? 1 : 0;
  18230. if ( poleAxis ) {
  18231. blurUniforms.poleAxis.value = poleAxis;
  18232. }
  18233. const { _lodMax } = this;
  18234. blurUniforms.dTheta.value = radiansPerPixel;
  18235. blurUniforms.mipInt.value = _lodMax - lodIn;
  18236. const outputSize = this._sizeLods[ lodOut ];
  18237. const x = 3 * outputSize * ( lodOut > _lodMax - LOD_MIN ? lodOut - _lodMax + LOD_MIN : 0 );
  18238. const y = 4 * ( this._cubeSize - outputSize );
  18239. _setViewport( targetOut, x, y, 3 * outputSize, 2 * outputSize );
  18240. renderer.setRenderTarget( targetOut );
  18241. renderer.render( blurMesh, _flatCamera );
  18242. }
  18243. }
  18244. function _createPlanes( lodMax ) {
  18245. const sizeLods = [];
  18246. const sigmas = [];
  18247. const lodMeshes = [];
  18248. let lod = lodMax;
  18249. const totalLods = lodMax - LOD_MIN + 1 + EXTRA_LOD_SIGMA.length;
  18250. for ( let i = 0; i < totalLods; i ++ ) {
  18251. const sizeLod = Math.pow( 2, lod );
  18252. sizeLods.push( sizeLod );
  18253. let sigma = 1.0 / sizeLod;
  18254. if ( i > lodMax - LOD_MIN ) {
  18255. sigma = EXTRA_LOD_SIGMA[ i - lodMax + LOD_MIN - 1 ];
  18256. } else if ( i === 0 ) {
  18257. sigma = 0;
  18258. }
  18259. sigmas.push( sigma );
  18260. const texelSize = 1.0 / ( sizeLod - 2 );
  18261. const min = - texelSize;
  18262. const max = 1 + texelSize;
  18263. const uv1 = [ min, min, max, min, max, max, min, min, max, max, min, max ];
  18264. const cubeFaces = 6;
  18265. const vertices = 6;
  18266. const positionSize = 3;
  18267. const uvSize = 2;
  18268. const faceIndexSize = 1;
  18269. const position = new Float32Array( positionSize * vertices * cubeFaces );
  18270. const uv = new Float32Array( uvSize * vertices * cubeFaces );
  18271. const faceIndex = new Float32Array( faceIndexSize * vertices * cubeFaces );
  18272. for ( let face = 0; face < cubeFaces; face ++ ) {
  18273. const x = ( face % 3 ) * 2 / 3 - 1;
  18274. const y = face > 2 ? 0 : -1;
  18275. const coordinates = [
  18276. x, y, 0,
  18277. x + 2 / 3, y, 0,
  18278. x + 2 / 3, y + 1, 0,
  18279. x, y, 0,
  18280. x + 2 / 3, y + 1, 0,
  18281. x, y + 1, 0
  18282. ];
  18283. const faceIdx = _faceLib[ face ];
  18284. position.set( coordinates, positionSize * vertices * faceIdx );
  18285. uv.set( uv1, uvSize * vertices * faceIdx );
  18286. const fill = [ faceIdx, faceIdx, faceIdx, faceIdx, faceIdx, faceIdx ];
  18287. faceIndex.set( fill, faceIndexSize * vertices * faceIdx );
  18288. }
  18289. const planes = new BufferGeometry();
  18290. planes.setAttribute( 'position', new BufferAttribute( position, positionSize ) );
  18291. planes.setAttribute( 'uv', new BufferAttribute( uv, uvSize ) );
  18292. planes.setAttribute( 'faceIndex', new BufferAttribute( faceIndex, faceIndexSize ) );
  18293. lodMeshes.push( new Mesh( planes, null ) );
  18294. if ( lod > LOD_MIN ) {
  18295. lod --;
  18296. }
  18297. }
  18298. return { lodMeshes, sizeLods, sigmas };
  18299. }
  18300. function _createRenderTarget( width, height ) {
  18301. const params = {
  18302. magFilter: LinearFilter,
  18303. minFilter: LinearFilter,
  18304. generateMipmaps: false,
  18305. type: HalfFloatType,
  18306. format: RGBAFormat,
  18307. colorSpace: LinearSRGBColorSpace,
  18308. //depthBuffer: false
  18309. };
  18310. const cubeUVRenderTarget = new RenderTarget( width, height, params );
  18311. cubeUVRenderTarget.texture.mapping = CubeUVReflectionMapping;
  18312. cubeUVRenderTarget.texture.name = 'PMREM.cubeUv';
  18313. cubeUVRenderTarget.texture.isPMREMTexture = true;
  18314. cubeUVRenderTarget.scissorTest = true;
  18315. return cubeUVRenderTarget;
  18316. }
  18317. function _setViewport( target, x, y, width, height ) {
  18318. target.viewport.set( x, y, width, height );
  18319. target.scissor.set( x, y, width, height );
  18320. }
  18321. function _getMaterial( type ) {
  18322. const material = new NodeMaterial();
  18323. material.depthTest = false;
  18324. material.depthWrite = false;
  18325. material.blending = NoBlending;
  18326. material.name = `PMREM_${ type }`;
  18327. return material;
  18328. }
  18329. function _getBlurShader( lodMax, width, height ) {
  18330. const weights = uniformArray( new Array( MAX_SAMPLES ).fill( 0 ) );
  18331. const poleAxis = uniform( new Vector3( 0, 1, 0 ) );
  18332. const dTheta = uniform( 0 );
  18333. const n = float( MAX_SAMPLES );
  18334. const latitudinal = uniform( 0 ); // false, bool
  18335. const samples = uniform( 1 ); // int
  18336. const envMap = texture();
  18337. const mipInt = uniform( 0 ); // int
  18338. const CUBEUV_TEXEL_WIDTH = float( 1 / width );
  18339. const CUBEUV_TEXEL_HEIGHT = float( 1 / height );
  18340. const CUBEUV_MAX_MIP = float( lodMax );
  18341. const materialUniforms = {
  18342. n,
  18343. latitudinal,
  18344. weights,
  18345. poleAxis,
  18346. outputDirection: _outputDirection,
  18347. dTheta,
  18348. samples,
  18349. envMap,
  18350. mipInt,
  18351. CUBEUV_TEXEL_WIDTH,
  18352. CUBEUV_TEXEL_HEIGHT,
  18353. CUBEUV_MAX_MIP
  18354. };
  18355. const material = _getMaterial( 'blur' );
  18356. material.fragmentNode = blur( { ...materialUniforms, latitudinal: latitudinal.equal( 1 ) } );
  18357. _uniformsMap.set( material, materialUniforms );
  18358. return material;
  18359. }
  18360. function _getGGXShader( lodMax, width, height ) {
  18361. const envMap = texture();
  18362. const roughness = uniform( 0 );
  18363. const mipInt = uniform( 0 );
  18364. const CUBEUV_TEXEL_WIDTH = float( 1 / width );
  18365. const CUBEUV_TEXEL_HEIGHT = float( 1 / height );
  18366. const CUBEUV_MAX_MIP = float( lodMax );
  18367. const materialUniforms = {
  18368. envMap,
  18369. roughness,
  18370. mipInt,
  18371. CUBEUV_TEXEL_WIDTH,
  18372. CUBEUV_TEXEL_HEIGHT,
  18373. CUBEUV_MAX_MIP
  18374. };
  18375. const material = _getMaterial( 'ggx' );
  18376. material.fragmentNode = ggxConvolution( {
  18377. ...materialUniforms,
  18378. N_immutable: _outputDirection,
  18379. GGX_SAMPLES: uint( GGX_SAMPLES )
  18380. } );
  18381. _uniformsMap.set( material, materialUniforms );
  18382. return material;
  18383. }
  18384. function _getCubemapMaterial( envTexture ) {
  18385. const material = _getMaterial( 'cubemap' );
  18386. material.fragmentNode = cubeTexture( envTexture, _outputDirection );
  18387. return material;
  18388. }
  18389. function _getEquirectMaterial( envTexture ) {
  18390. const material = _getMaterial( 'equirect' );
  18391. material.fragmentNode = texture( envTexture, equirectUV( _outputDirection ), 0 );
  18392. return material;
  18393. }
  18394. const _cache = new WeakMap();
  18395. /**
  18396. * Generates the cubeUV size based on the given image height.
  18397. *
  18398. * @private
  18399. * @param {number} imageHeight - The image height.
  18400. * @return {{texelWidth: number,texelHeight: number, maxMip: number}} The result object.
  18401. */
  18402. function _generateCubeUVSize( imageHeight ) {
  18403. const maxMip = Math.log2( imageHeight ) - 2;
  18404. const texelHeight = 1.0 / imageHeight;
  18405. const texelWidth = 1.0 / ( 3 * Math.max( Math.pow( 2, maxMip ), 7 * 16 ) );
  18406. return { texelWidth, texelHeight, maxMip };
  18407. }
  18408. /**
  18409. * Generates a PMREM from the given texture.
  18410. *
  18411. * @private
  18412. * @param {Texture} texture - The texture to create the PMREM for.
  18413. * @param {Renderer} renderer - The renderer.
  18414. * @param {PMREMGenerator} generator - The PMREM generator.
  18415. * @return {?Texture} The PMREM.
  18416. */
  18417. function _getPMREMFromTexture( texture, renderer, generator ) {
  18418. const cache = _getCache( renderer );
  18419. let cacheTexture = cache.get( texture );
  18420. const pmremVersion = cacheTexture !== undefined ? cacheTexture.pmremVersion : -1;
  18421. if ( pmremVersion !== texture.pmremVersion ) {
  18422. const image = texture.image;
  18423. if ( texture.isCubeTexture ) {
  18424. if ( isCubeMapReady( image ) ) {
  18425. cacheTexture = generator.fromCubemap( texture, cacheTexture );
  18426. } else {
  18427. return null;
  18428. }
  18429. } else {
  18430. if ( isEquirectangularMapReady( image ) ) {
  18431. cacheTexture = generator.fromEquirectangular( texture, cacheTexture );
  18432. } else {
  18433. return null;
  18434. }
  18435. }
  18436. cacheTexture.pmremVersion = texture.pmremVersion;
  18437. cache.set( texture, cacheTexture );
  18438. }
  18439. return cacheTexture.texture;
  18440. }
  18441. /**
  18442. * Returns a cache that stores generated PMREMs for the respective textures.
  18443. * A cache must be maintained per renderer since PMREMs are render target textures
  18444. * which can't be shared across render contexts.
  18445. *
  18446. * @private
  18447. * @param {Renderer} renderer - The renderer.
  18448. * @return {WeakMap<Texture, Texture>} The PMREM cache.
  18449. */
  18450. function _getCache( renderer ) {
  18451. let rendererCache = _cache.get( renderer );
  18452. if ( rendererCache === undefined ) {
  18453. rendererCache = new WeakMap();
  18454. _cache.set( renderer, rendererCache );
  18455. }
  18456. return rendererCache;
  18457. }
  18458. /**
  18459. * This node represents a PMREM which is a special type of preprocessed
  18460. * environment map intended for PBR materials.
  18461. *
  18462. * ```js
  18463. * const material = new MeshStandardNodeMaterial();
  18464. * material.envNode = pmremTexture( envMap );
  18465. * ```
  18466. *
  18467. * @augments TempNode
  18468. */
  18469. class PMREMNode extends TempNode {
  18470. static get type() {
  18471. return 'PMREMNode';
  18472. }
  18473. /**
  18474. * Constructs a new function overloading node.
  18475. *
  18476. * @param {Texture} value - The input texture.
  18477. * @param {Node<vec2>} [uvNode=null] - The uv node.
  18478. * @param {Node<float>} [levelNode=null] - The level node.
  18479. */
  18480. constructor( value, uvNode = null, levelNode = null ) {
  18481. super( 'vec3' );
  18482. /**
  18483. * Reference to the input texture.
  18484. *
  18485. * @private
  18486. * @type {Texture}
  18487. */
  18488. this._value = value;
  18489. /**
  18490. * Reference to the generated PMREM.
  18491. *
  18492. * @private
  18493. * @type {Texture | null}
  18494. * @default null
  18495. */
  18496. this._pmrem = null;
  18497. /**
  18498. * The uv node.
  18499. *
  18500. * @type {Node<vec2>}
  18501. */
  18502. this.uvNode = uvNode;
  18503. /**
  18504. * The level node.
  18505. *
  18506. * @type {Node<float>}
  18507. */
  18508. this.levelNode = levelNode;
  18509. /**
  18510. * Reference to a PMREM generator.
  18511. *
  18512. * @private
  18513. * @type {?PMREMGenerator}
  18514. * @default null
  18515. */
  18516. this._generator = null;
  18517. const defaultTexture = new Texture();
  18518. defaultTexture.isRenderTargetTexture = true;
  18519. /**
  18520. * The texture node holding the generated PMREM.
  18521. *
  18522. * @private
  18523. * @type {TextureNode}
  18524. */
  18525. this._texture = texture( defaultTexture );
  18526. /**
  18527. * A uniform representing the PMREM's width.
  18528. *
  18529. * @private
  18530. * @type {UniformNode<float>}
  18531. */
  18532. this._width = uniform( 0 );
  18533. /**
  18534. * A uniform representing the PMREM's height.
  18535. *
  18536. * @private
  18537. * @type {UniformNode<float>}
  18538. */
  18539. this._height = uniform( 0 );
  18540. /**
  18541. * A uniform representing the PMREM's max Mip.
  18542. *
  18543. * @private
  18544. * @type {UniformNode<float>}
  18545. */
  18546. this._maxMip = uniform( 0 );
  18547. /**
  18548. * The `updateBeforeType` is set to `NodeUpdateType.RENDER`.
  18549. *
  18550. * @type {string}
  18551. * @default 'render'
  18552. */
  18553. this.updateBeforeType = NodeUpdateType.RENDER;
  18554. }
  18555. set value( value ) {
  18556. this._value = value;
  18557. this._pmrem = null;
  18558. }
  18559. /**
  18560. * The node's texture value.
  18561. *
  18562. * @type {Texture}
  18563. */
  18564. get value() {
  18565. return this._value;
  18566. }
  18567. /**
  18568. * Uses the given PMREM texture to update internal values.
  18569. *
  18570. * @param {Texture} texture - The PMREM texture.
  18571. */
  18572. updateFromTexture( texture ) {
  18573. const cubeUVSize = _generateCubeUVSize( texture.image.height );
  18574. this._texture.value = texture;
  18575. this._width.value = cubeUVSize.texelWidth;
  18576. this._height.value = cubeUVSize.texelHeight;
  18577. this._maxMip.value = cubeUVSize.maxMip;
  18578. }
  18579. updateBefore( frame ) {
  18580. let pmrem = this._pmrem;
  18581. const pmremVersion = pmrem ? pmrem.pmremVersion : -1;
  18582. const texture = this._value;
  18583. if ( pmremVersion !== texture.pmremVersion ) {
  18584. if ( texture.isPMREMTexture === true ) {
  18585. pmrem = texture;
  18586. } else {
  18587. pmrem = _getPMREMFromTexture( texture, frame.renderer, this._generator );
  18588. }
  18589. if ( pmrem !== null ) {
  18590. this._pmrem = pmrem;
  18591. this.updateFromTexture( pmrem );
  18592. }
  18593. }
  18594. }
  18595. setup( builder ) {
  18596. if ( this._generator === null ) {
  18597. this._generator = new PMREMGenerator( builder.renderer );
  18598. }
  18599. this.updateBefore( builder );
  18600. //
  18601. let uvNode = this.uvNode;
  18602. if ( uvNode === null && builder.context.getUV ) {
  18603. uvNode = builder.context.getUV( this, builder );
  18604. }
  18605. //
  18606. uvNode = materialEnvRotation.mul( vec3( uvNode.x, uvNode.y.negate(), uvNode.z ) );
  18607. //
  18608. let levelNode = this.levelNode;
  18609. if ( levelNode === null && builder.context.getTextureLevel ) {
  18610. levelNode = builder.context.getTextureLevel( this );
  18611. }
  18612. //
  18613. return textureCubeUV( this._texture, uvNode, levelNode, this._width, this._height, this._maxMip );
  18614. }
  18615. dispose() {
  18616. super.dispose();
  18617. if ( this._generator !== null ) this._generator.dispose();
  18618. }
  18619. }
  18620. /**
  18621. * Returns `true` if the given cube map image has been fully loaded.
  18622. *
  18623. * @private
  18624. * @param {?Array<(Image|Object)>} [image] - The cube map image.
  18625. * @return {boolean} Whether the given cube map is ready or not.
  18626. */
  18627. function isCubeMapReady( image ) {
  18628. if ( image === null || image === undefined ) return false;
  18629. let count = 0;
  18630. const length = 6;
  18631. for ( let i = 0; i < length; i ++ ) {
  18632. if ( image[ i ] !== undefined ) count ++;
  18633. }
  18634. return count === length;
  18635. }
  18636. /**
  18637. * Returns `true` if the given equirectangular image has been fully loaded.
  18638. *
  18639. * @private
  18640. * @param {(Image|Object)} image - The equirectangular image.
  18641. * @return {boolean} Whether the given cube map is ready or not.
  18642. */
  18643. function isEquirectangularMapReady( image ) {
  18644. if ( image === null || image === undefined ) return false;
  18645. return image.height > 0;
  18646. }
  18647. /**
  18648. * TSL function for creating a PMREM node.
  18649. *
  18650. * @tsl
  18651. * @function
  18652. * @param {Texture} value - The input texture.
  18653. * @param {?Node<vec2>} [uvNode=null] - The uv node.
  18654. * @param {?Node<float>} [levelNode=null] - The level node.
  18655. * @returns {PMREMNode}
  18656. */
  18657. const pmremTexture = /*@__PURE__*/ nodeProxy( PMREMNode ).setParameterLength( 1, 3 );
  18658. const _envNodeCache = new WeakMap();
  18659. /**
  18660. * Represents a physical model for Image-based lighting (IBL). The environment
  18661. * is defined via environment maps in the equirectangular, cube map or cubeUV (PMREM) format.
  18662. * `EnvironmentNode` is intended for PBR materials like {@link MeshStandardNodeMaterial}.
  18663. *
  18664. * @augments LightingNode
  18665. */
  18666. class EnvironmentNode extends LightingNode {
  18667. static get type() {
  18668. return 'EnvironmentNode';
  18669. }
  18670. /**
  18671. * Constructs a new environment node.
  18672. *
  18673. * @param {Node} [envNode=null] - A node representing the environment.
  18674. */
  18675. constructor( envNode = null ) {
  18676. super();
  18677. /**
  18678. * A node representing the environment.
  18679. *
  18680. * @type {?Node}
  18681. * @default null
  18682. */
  18683. this.envNode = envNode;
  18684. }
  18685. setup( builder ) {
  18686. const { material } = builder;
  18687. let envNode = this.envNode;
  18688. if ( envNode.isTextureNode || envNode.isMaterialReferenceNode ) {
  18689. const value = ( envNode.isTextureNode ) ? envNode.value : material[ envNode.property ];
  18690. let cacheEnvNode = _envNodeCache.get( value );
  18691. if ( cacheEnvNode === undefined ) {
  18692. cacheEnvNode = pmremTexture( value );
  18693. _envNodeCache.set( value, cacheEnvNode );
  18694. }
  18695. envNode = cacheEnvNode;
  18696. }
  18697. //
  18698. const useAnisotropy = material.useAnisotropy === true || material.anisotropy > 0;
  18699. const radianceNormalView = useAnisotropy ? bentNormalView : normalView;
  18700. const radiance = envNode.context( createRadianceContext( roughness, radianceNormalView ) ).mul( materialEnvIntensity );
  18701. const irradiance = envNode.context( createIrradianceContext( normalWorld ) ).mul( Math.PI ).mul( materialEnvIntensity );
  18702. const isolateRadiance = isolate( radiance );
  18703. const isolateIrradiance = isolate( irradiance );
  18704. //
  18705. builder.context.radiance.addAssign( isolateRadiance );
  18706. builder.context.iblIrradiance.addAssign( isolateIrradiance );
  18707. //
  18708. const clearcoatRadiance = builder.context.lightingModel.clearcoatRadiance;
  18709. if ( clearcoatRadiance ) {
  18710. const clearcoatRadianceContext = envNode.context( createRadianceContext( clearcoatRoughness, clearcoatNormalView ) ).mul( materialEnvIntensity );
  18711. const isolateClearcoatRadiance = isolate( clearcoatRadianceContext );
  18712. clearcoatRadiance.addAssign( isolateClearcoatRadiance );
  18713. }
  18714. }
  18715. }
  18716. const createRadianceContext = ( roughnessNode, normalViewNode ) => {
  18717. let reflectVec = null;
  18718. return {
  18719. getUV: () => {
  18720. if ( reflectVec === null ) {
  18721. reflectVec = positionViewDirection.negate().reflect( normalViewNode );
  18722. // Mixing the reflection with the normal is more accurate and keeps rough objects from gathering light from behind their tangent plane.
  18723. reflectVec = pow4( roughnessNode ).mix( reflectVec, normalViewNode ).normalize();
  18724. reflectVec = reflectVec.transformDirection( cameraViewMatrix );
  18725. }
  18726. return reflectVec;
  18727. },
  18728. getTextureLevel: () => {
  18729. return roughnessNode;
  18730. }
  18731. };
  18732. };
  18733. const createIrradianceContext = ( normalWorldNode ) => {
  18734. return {
  18735. getUV: () => {
  18736. return normalWorldNode;
  18737. },
  18738. getTextureLevel: () => {
  18739. return float( 1.0 );
  18740. }
  18741. };
  18742. };
  18743. const _defaultValues$6 = /*@__PURE__*/ new MeshStandardMaterial();
  18744. /**
  18745. * Node material version of {@link MeshStandardMaterial}.
  18746. *
  18747. * @augments NodeMaterial
  18748. */
  18749. class MeshStandardNodeMaterial extends NodeMaterial {
  18750. static get type() {
  18751. return 'MeshStandardNodeMaterial';
  18752. }
  18753. /**
  18754. * Constructs a new mesh standard node material.
  18755. *
  18756. * @param {Object} [parameters] - The configuration parameter.
  18757. */
  18758. constructor( parameters ) {
  18759. super();
  18760. /**
  18761. * This flag can be used for type testing.
  18762. *
  18763. * @type {boolean}
  18764. * @readonly
  18765. * @default true
  18766. */
  18767. this.isMeshStandardNodeMaterial = true;
  18768. /**
  18769. * Set to `true` because standard materials react on lights.
  18770. *
  18771. * @type {boolean}
  18772. * @default true
  18773. */
  18774. this.lights = true;
  18775. /**
  18776. * The emissive color of standard materials is by default inferred from the `emissive`,
  18777. * `emissiveIntensity` and `emissiveMap` properties. This node property allows to
  18778. * overwrite the default and define the emissive color with a node instead.
  18779. *
  18780. * If you don't want to overwrite the emissive color but modify the existing
  18781. * value instead, use {@link materialEmissive}.
  18782. *
  18783. * @type {?Node<vec3>}
  18784. * @default null
  18785. */
  18786. this.emissiveNode = null;
  18787. /**
  18788. * The metalness of standard materials is by default inferred from the `metalness`,
  18789. * and `metalnessMap` properties. This node property allows to
  18790. * overwrite the default and define the metalness with a node instead.
  18791. *
  18792. * If you don't want to overwrite the metalness but modify the existing
  18793. * value instead, use {@link materialMetalness}.
  18794. *
  18795. * @type {?Node<float>}
  18796. * @default null
  18797. */
  18798. this.metalnessNode = null;
  18799. /**
  18800. * The roughness of standard materials is by default inferred from the `roughness`,
  18801. * and `roughnessMap` properties. This node property allows to
  18802. * overwrite the default and define the roughness with a node instead.
  18803. *
  18804. * If you don't want to overwrite the roughness but modify the existing
  18805. * value instead, use {@link materialRoughness}.
  18806. *
  18807. * @type {?Node<float>}
  18808. * @default null
  18809. */
  18810. this.roughnessNode = null;
  18811. this.setDefaultValues( _defaultValues$6 );
  18812. this.setValues( parameters );
  18813. }
  18814. /**
  18815. * Overwritten since this type of material uses {@link EnvironmentNode}
  18816. * to implement the PBR (PMREM based) environment mapping. Besides, the
  18817. * method honors `Scene.environment`.
  18818. *
  18819. * @param {NodeBuilder} builder - The current node builder.
  18820. * @return {?EnvironmentNode<vec3>} The environment node.
  18821. */
  18822. setupEnvironment( builder ) {
  18823. let envNode = super.setupEnvironment( builder );
  18824. if ( envNode === null && builder.environmentNode ) {
  18825. envNode = builder.environmentNode;
  18826. }
  18827. return envNode ? new EnvironmentNode( envNode ) : null;
  18828. }
  18829. /**
  18830. * Setups the lighting model.
  18831. *
  18832. * @return {PhysicalLightingModel} The lighting model.
  18833. */
  18834. setupLightingModel( /*builder*/ ) {
  18835. return new PhysicalLightingModel();
  18836. }
  18837. /**
  18838. * Setups the specular related node variables.
  18839. */
  18840. setupSpecular() {
  18841. const specularColorNode = mix( vec3( 0.04 ), diffuseColor.rgb, metalness );
  18842. specularColor.assign( vec3( 0.04 ) );
  18843. specularColorBlended.assign( specularColorNode );
  18844. specularF90.assign( 1.0 );
  18845. }
  18846. /**
  18847. * Setups the standard specific node variables.
  18848. *
  18849. * @param {NodeBuilder} builder - The current node builder.
  18850. */
  18851. setupVariants() {
  18852. // METALNESS
  18853. const metalnessNode = this.metalnessNode ? float( this.metalnessNode ) : materialMetalness;
  18854. metalness.assign( metalnessNode );
  18855. // ROUGHNESS
  18856. let roughnessNode = this.roughnessNode ? float( this.roughnessNode ) : materialRoughness;
  18857. roughnessNode = getRoughness( { roughness: roughnessNode } );
  18858. roughness.assign( roughnessNode );
  18859. // SPECULAR COLOR
  18860. this.setupSpecular();
  18861. // DIFFUSE COLOR
  18862. diffuseContribution.assign( diffuseColor.rgb.mul( metalnessNode.oneMinus() ) );
  18863. }
  18864. copy( source ) {
  18865. this.emissiveNode = source.emissiveNode;
  18866. this.metalnessNode = source.metalnessNode;
  18867. this.roughnessNode = source.roughnessNode;
  18868. return super.copy( source );
  18869. }
  18870. }
  18871. const _defaultValues$5 = /*@__PURE__*/ new MeshPhysicalMaterial();
  18872. /**
  18873. * Node material version of {@link MeshPhysicalMaterial}.
  18874. *
  18875. * @augments MeshStandardNodeMaterial
  18876. */
  18877. class MeshPhysicalNodeMaterial extends MeshStandardNodeMaterial {
  18878. static get type() {
  18879. return 'MeshPhysicalNodeMaterial';
  18880. }
  18881. /**
  18882. * Constructs a new mesh physical node material.
  18883. *
  18884. * @param {Object} [parameters] - The configuration parameter.
  18885. */
  18886. constructor( parameters ) {
  18887. super();
  18888. /**
  18889. * This flag can be used for type testing.
  18890. *
  18891. * @type {boolean}
  18892. * @readonly
  18893. * @default true
  18894. */
  18895. this.isMeshPhysicalNodeMaterial = true;
  18896. /**
  18897. * The clearcoat of physical materials is by default inferred from the `clearcoat`
  18898. * and `clearcoatMap` properties. This node property allows to overwrite the default
  18899. * and define the clearcoat with a node instead.
  18900. *
  18901. * If you don't want to overwrite the clearcoat but modify the existing
  18902. * value instead, use {@link materialClearcoat}.
  18903. *
  18904. * @type {?Node<float>}
  18905. * @default null
  18906. */
  18907. this.clearcoatNode = null;
  18908. /**
  18909. * The clearcoat roughness of physical materials is by default inferred from the `clearcoatRoughness`
  18910. * and `clearcoatRoughnessMap` properties. This node property allows to overwrite the default
  18911. * and define the clearcoat roughness with a node instead.
  18912. *
  18913. * If you don't want to overwrite the clearcoat roughness but modify the existing
  18914. * value instead, use {@link materialClearcoatRoughness}.
  18915. *
  18916. * @type {?Node<float>}
  18917. * @default null
  18918. */
  18919. this.clearcoatRoughnessNode = null;
  18920. /**
  18921. * The clearcoat normal of physical materials is by default inferred from the `clearcoatNormalMap`
  18922. * property. This node property allows to overwrite the default
  18923. * and define the clearcoat normal with a node instead.
  18924. *
  18925. * If you don't want to overwrite the clearcoat normal but modify the existing
  18926. * value instead, use {@link materialClearcoatNormal}.
  18927. *
  18928. * @type {?Node<vec3>}
  18929. * @default null
  18930. */
  18931. this.clearcoatNormalNode = null;
  18932. /**
  18933. * The sheen of physical materials is by default inferred from the `sheen`, `sheenColor`
  18934. * and `sheenColorMap` properties. This node property allows to overwrite the default
  18935. * and define the sheen with a node instead.
  18936. *
  18937. * If you don't want to overwrite the sheen but modify the existing
  18938. * value instead, use {@link materialSheen}.
  18939. *
  18940. * @type {?Node<vec3>}
  18941. * @default null
  18942. */
  18943. this.sheenNode = null;
  18944. /**
  18945. * The sheen roughness of physical materials is by default inferred from the `sheenRoughness` and
  18946. * `sheenRoughnessMap` properties. This node property allows to overwrite the default
  18947. * and define the sheen roughness with a node instead.
  18948. *
  18949. * If you don't want to overwrite the sheen roughness but modify the existing
  18950. * value instead, use {@link materialSheenRoughness}.
  18951. *
  18952. * @type {?Node<float>}
  18953. * @default null
  18954. */
  18955. this.sheenRoughnessNode = null;
  18956. /**
  18957. * The iridescence of physical materials is by default inferred from the `iridescence`
  18958. * property. This node property allows to overwrite the default
  18959. * and define the iridescence with a node instead.
  18960. *
  18961. * If you don't want to overwrite the iridescence but modify the existing
  18962. * value instead, use {@link materialIridescence}.
  18963. *
  18964. * @type {?Node<float>}
  18965. * @default null
  18966. */
  18967. this.iridescenceNode = null;
  18968. /**
  18969. * The iridescence IOR of physical materials is by default inferred from the `iridescenceIOR`
  18970. * property. This node property allows to overwrite the default
  18971. * and define the iridescence IOR with a node instead.
  18972. *
  18973. * If you don't want to overwrite the iridescence IOR but modify the existing
  18974. * value instead, use {@link materialIridescenceIOR}.
  18975. *
  18976. * @type {?Node<float>}
  18977. * @default null
  18978. */
  18979. this.iridescenceIORNode = null;
  18980. /**
  18981. * The iridescence thickness of physical materials is by default inferred from the `iridescenceThicknessRange`
  18982. * and `iridescenceThicknessMap` properties. This node property allows to overwrite the default
  18983. * and define the iridescence thickness with a node instead.
  18984. *
  18985. * If you don't want to overwrite the iridescence thickness but modify the existing
  18986. * value instead, use {@link materialIridescenceThickness}.
  18987. *
  18988. * @type {?Node<float>}
  18989. * @default null
  18990. */
  18991. this.iridescenceThicknessNode = null;
  18992. /**
  18993. * The specular intensity of physical materials is by default inferred from the `specularIntensity`
  18994. * and `specularIntensityMap` properties. This node property allows to overwrite the default
  18995. * and define the specular intensity with a node instead.
  18996. *
  18997. * If you don't want to overwrite the specular intensity but modify the existing
  18998. * value instead, use {@link materialSpecularIntensity}.
  18999. *
  19000. * @type {?Node<float>}
  19001. * @default null
  19002. */
  19003. this.specularIntensityNode = null;
  19004. /**
  19005. * The specular color of physical materials is by default inferred from the `specularColor`
  19006. * and `specularColorMap` properties. This node property allows to overwrite the default
  19007. * and define the specular color with a node instead.
  19008. *
  19009. * If you don't want to overwrite the specular color but modify the existing
  19010. * value instead, use {@link materialSpecularColor}.
  19011. *
  19012. * @type {?Node<vec3>}
  19013. * @default null
  19014. */
  19015. this.specularColorNode = null;
  19016. /**
  19017. * The ior of physical materials is by default inferred from the `ior`
  19018. * property. This node property allows to overwrite the default
  19019. * and define the ior with a node instead.
  19020. *
  19021. * If you don't want to overwrite the ior but modify the existing
  19022. * value instead, use {@link materialIOR}.
  19023. *
  19024. * @type {?Node<float>}
  19025. * @default null
  19026. */
  19027. this.iorNode = null;
  19028. /**
  19029. * The transmission of physical materials is by default inferred from the `transmission` and
  19030. * `transmissionMap` properties. This node property allows to overwrite the default
  19031. * and define the transmission with a node instead.
  19032. *
  19033. * If you don't want to overwrite the transmission but modify the existing
  19034. * value instead, use {@link materialTransmission}.
  19035. *
  19036. * @type {?Node<float>}
  19037. * @default null
  19038. */
  19039. this.transmissionNode = null;
  19040. /**
  19041. * The thickness of physical materials is by default inferred from the `thickness` and
  19042. * `thicknessMap` properties. This node property allows to overwrite the default
  19043. * and define the thickness with a node instead.
  19044. *
  19045. * If you don't want to overwrite the thickness but modify the existing
  19046. * value instead, use {@link materialThickness}.
  19047. *
  19048. * @type {?Node<float>}
  19049. * @default null
  19050. */
  19051. this.thicknessNode = null;
  19052. /**
  19053. * The attenuation distance of physical materials is by default inferred from the
  19054. * `attenuationDistance` property. This node property allows to overwrite the default
  19055. * and define the attenuation distance with a node instead.
  19056. *
  19057. * If you don't want to overwrite the attenuation distance but modify the existing
  19058. * value instead, use {@link materialAttenuationDistance}.
  19059. *
  19060. * @type {?Node<float>}
  19061. * @default null
  19062. */
  19063. this.attenuationDistanceNode = null;
  19064. /**
  19065. * The attenuation color of physical materials is by default inferred from the
  19066. * `attenuationColor` property. This node property allows to overwrite the default
  19067. * and define the attenuation color with a node instead.
  19068. *
  19069. * If you don't want to overwrite the attenuation color but modify the existing
  19070. * value instead, use {@link materialAttenuationColor}.
  19071. *
  19072. * @type {?Node<vec3>}
  19073. * @default null
  19074. */
  19075. this.attenuationColorNode = null;
  19076. /**
  19077. * The dispersion of physical materials is by default inferred from the
  19078. * `dispersion` property. This node property allows to overwrite the default
  19079. * and define the dispersion with a node instead.
  19080. *
  19081. * If you don't want to overwrite the dispersion but modify the existing
  19082. * value instead, use {@link materialDispersion}.
  19083. *
  19084. * @type {?Node<float>}
  19085. * @default null
  19086. */
  19087. this.dispersionNode = null;
  19088. /**
  19089. * The anisotropy of physical materials is by default inferred from the
  19090. * `anisotropy` property. This node property allows to overwrite the default
  19091. * and define the anisotropy with a node instead.
  19092. *
  19093. * If you don't want to overwrite the anisotropy but modify the existing
  19094. * value instead, use {@link materialAnisotropy}.
  19095. *
  19096. * @type {?Node<float>}
  19097. * @default null
  19098. */
  19099. this.anisotropyNode = null;
  19100. this.setDefaultValues( _defaultValues$5 );
  19101. this.setValues( parameters );
  19102. }
  19103. /**
  19104. * Whether the lighting model should use clearcoat or not.
  19105. *
  19106. * @type {boolean}
  19107. * @default true
  19108. */
  19109. get useClearcoat() {
  19110. return this.clearcoat > 0 || this.clearcoatNode !== null;
  19111. }
  19112. /**
  19113. * Whether the lighting model should use iridescence or not.
  19114. *
  19115. * @type {boolean}
  19116. * @default true
  19117. */
  19118. get useIridescence() {
  19119. return this.iridescence > 0 || this.iridescenceNode !== null;
  19120. }
  19121. /**
  19122. * Whether the lighting model should use sheen or not.
  19123. *
  19124. * @type {boolean}
  19125. * @default true
  19126. */
  19127. get useSheen() {
  19128. return this.sheen > 0 || this.sheenNode !== null;
  19129. }
  19130. /**
  19131. * Whether the lighting model should use anisotropy or not.
  19132. *
  19133. * @type {boolean}
  19134. * @default true
  19135. */
  19136. get useAnisotropy() {
  19137. return this.anisotropy > 0 || this.anisotropyNode !== null;
  19138. }
  19139. /**
  19140. * Whether the lighting model should use transmission or not.
  19141. *
  19142. * @type {boolean}
  19143. * @default true
  19144. */
  19145. get useTransmission() {
  19146. return this.transmission > 0 || this.transmissionNode !== null;
  19147. }
  19148. /**
  19149. * Whether the lighting model should use dispersion or not.
  19150. *
  19151. * @type {boolean}
  19152. * @default true
  19153. */
  19154. get useDispersion() {
  19155. return this.dispersion > 0 || this.dispersionNode !== null;
  19156. }
  19157. /**
  19158. * Setups the specular related node variables.
  19159. */
  19160. setupSpecular() {
  19161. const iorNode = this.iorNode ? float( this.iorNode ) : materialIOR;
  19162. ior.assign( iorNode );
  19163. specularColor.assign( min$1( pow2( ior.sub( 1.0 ).div( ior.add( 1.0 ) ) ).mul( materialSpecularColor ), vec3( 1.0 ) ).mul( materialSpecularIntensity ) );
  19164. specularColorBlended.assign( mix( specularColor, diffuseColor.rgb, metalness ) );
  19165. specularF90.assign( mix( materialSpecularIntensity, 1.0, metalness ) );
  19166. }
  19167. /**
  19168. * Setups the lighting model.
  19169. *
  19170. * @return {PhysicalLightingModel} The lighting model.
  19171. */
  19172. setupLightingModel( /*builder*/ ) {
  19173. return new PhysicalLightingModel( this.useClearcoat, this.useSheen, this.useIridescence, this.useAnisotropy, this.useTransmission, this.useDispersion );
  19174. }
  19175. /**
  19176. * Setups the physical specific node variables.
  19177. *
  19178. * @param {NodeBuilder} builder - The current node builder.
  19179. */
  19180. setupVariants( builder ) {
  19181. super.setupVariants( builder );
  19182. // CLEARCOAT
  19183. if ( this.useClearcoat ) {
  19184. const clearcoatNode = this.clearcoatNode ? float( this.clearcoatNode ) : materialClearcoat;
  19185. const clearcoatRoughnessNode = this.clearcoatRoughnessNode ? float( this.clearcoatRoughnessNode ) : materialClearcoatRoughness;
  19186. clearcoat.assign( clearcoatNode );
  19187. clearcoatRoughness.assign( getRoughness( { roughness: clearcoatRoughnessNode } ) );
  19188. }
  19189. // SHEEN
  19190. if ( this.useSheen ) {
  19191. const sheenNode = this.sheenNode ? vec3( this.sheenNode ) : materialSheen;
  19192. const sheenRoughnessNode = this.sheenRoughnessNode ? float( this.sheenRoughnessNode ) : materialSheenRoughness;
  19193. sheen.assign( sheenNode );
  19194. sheenRoughness.assign( sheenRoughnessNode );
  19195. }
  19196. // IRIDESCENCE
  19197. if ( this.useIridescence ) {
  19198. const iridescenceNode = this.iridescenceNode ? float( this.iridescenceNode ) : materialIridescence;
  19199. const iridescenceIORNode = this.iridescenceIORNode ? float( this.iridescenceIORNode ) : materialIridescenceIOR;
  19200. const iridescenceThicknessNode = this.iridescenceThicknessNode ? float( this.iridescenceThicknessNode ) : materialIridescenceThickness;
  19201. iridescence.assign( iridescenceNode );
  19202. iridescenceIOR.assign( iridescenceIORNode );
  19203. iridescenceThickness.assign( iridescenceThicknessNode );
  19204. }
  19205. // ANISOTROPY
  19206. if ( this.useAnisotropy ) {
  19207. const anisotropyV = ( this.anisotropyNode ? vec2( this.anisotropyNode ) : materialAnisotropy ).toVar();
  19208. anisotropy.assign( anisotropyV.length() );
  19209. If( anisotropy.equal( 0.0 ), () => {
  19210. anisotropyV.assign( vec2( 1.0, 0.0 ) );
  19211. } ).Else( () => {
  19212. anisotropyV.divAssign( vec2( anisotropy ) );
  19213. anisotropy.assign( anisotropy.saturate() );
  19214. } );
  19215. // Roughness along the anisotropy bitangent is the material roughness, while the tangent roughness increases with anisotropy.
  19216. alphaT.assign( anisotropy.pow2().mix( roughness.pow2(), 1.0 ) );
  19217. anisotropyT.assign( TBNViewMatrix[ 0 ].mul( anisotropyV.x ).add( TBNViewMatrix[ 1 ].mul( anisotropyV.y ) ) );
  19218. anisotropyB.assign( TBNViewMatrix[ 1 ].mul( anisotropyV.x ).sub( TBNViewMatrix[ 0 ].mul( anisotropyV.y ) ) );
  19219. }
  19220. // TRANSMISSION
  19221. if ( this.useTransmission ) {
  19222. const transmissionNode = this.transmissionNode ? float( this.transmissionNode ) : materialTransmission;
  19223. const thicknessNode = this.thicknessNode ? float( this.thicknessNode ) : materialThickness;
  19224. const attenuationDistanceNode = this.attenuationDistanceNode ? float( this.attenuationDistanceNode ) : materialAttenuationDistance;
  19225. const attenuationColorNode = this.attenuationColorNode ? vec3( this.attenuationColorNode ) : materialAttenuationColor;
  19226. transmission.assign( transmissionNode );
  19227. thickness.assign( thicknessNode );
  19228. attenuationDistance.assign( attenuationDistanceNode );
  19229. attenuationColor.assign( attenuationColorNode );
  19230. if ( this.useDispersion ) {
  19231. const dispersionNode = this.dispersionNode ? float( this.dispersionNode ) : materialDispersion;
  19232. dispersion.assign( dispersionNode );
  19233. }
  19234. }
  19235. }
  19236. /**
  19237. * Setups the clearcoat normal node.
  19238. *
  19239. * @return {Node<vec3>} The clearcoat normal.
  19240. */
  19241. setupClearcoatNormal() {
  19242. return this.clearcoatNormalNode ? vec3( this.clearcoatNormalNode ) : materialClearcoatNormal;
  19243. }
  19244. setup( builder ) {
  19245. builder.context.setupClearcoatNormal = () => subBuild( this.setupClearcoatNormal( builder ), 'NORMAL', 'vec3' );
  19246. super.setup( builder );
  19247. }
  19248. copy( source ) {
  19249. this.clearcoatNode = source.clearcoatNode;
  19250. this.clearcoatRoughnessNode = source.clearcoatRoughnessNode;
  19251. this.clearcoatNormalNode = source.clearcoatNormalNode;
  19252. this.sheenNode = source.sheenNode;
  19253. this.sheenRoughnessNode = source.sheenRoughnessNode;
  19254. this.iridescenceNode = source.iridescenceNode;
  19255. this.iridescenceIORNode = source.iridescenceIORNode;
  19256. this.iridescenceThicknessNode = source.iridescenceThicknessNode;
  19257. this.specularIntensityNode = source.specularIntensityNode;
  19258. this.specularColorNode = source.specularColorNode;
  19259. this.transmissionNode = source.transmissionNode;
  19260. this.thicknessNode = source.thicknessNode;
  19261. this.attenuationDistanceNode = source.attenuationDistanceNode;
  19262. this.attenuationColorNode = source.attenuationColorNode;
  19263. this.dispersionNode = source.dispersionNode;
  19264. this.anisotropyNode = source.anisotropyNode;
  19265. return super.copy( source );
  19266. }
  19267. }
  19268. /**
  19269. * Represents the lighting model for {@link MeshSSSNodeMaterial}.
  19270. *
  19271. * @augments PhysicalLightingModel
  19272. */
  19273. class SSSLightingModel extends PhysicalLightingModel {
  19274. /**
  19275. * Constructs a new physical lighting model.
  19276. *
  19277. * @param {boolean} [clearcoat=false] - Whether clearcoat is supported or not.
  19278. * @param {boolean} [sheen=false] - Whether sheen is supported or not.
  19279. * @param {boolean} [iridescence=false] - Whether iridescence is supported or not.
  19280. * @param {boolean} [anisotropy=false] - Whether anisotropy is supported or not.
  19281. * @param {boolean} [transmission=false] - Whether transmission is supported or not.
  19282. * @param {boolean} [dispersion=false] - Whether dispersion is supported or not.
  19283. * @param {boolean} [sss=false] - Whether SSS is supported or not.
  19284. */
  19285. constructor( clearcoat = false, sheen = false, iridescence = false, anisotropy = false, transmission = false, dispersion = false, sss = false ) {
  19286. super( clearcoat, sheen, iridescence, anisotropy, transmission, dispersion );
  19287. /**
  19288. * Whether the lighting model should use SSS or not.
  19289. *
  19290. * @type {boolean}
  19291. * @default false
  19292. */
  19293. this.useSSS = sss;
  19294. }
  19295. /**
  19296. * Extends the default implementation with a SSS term.
  19297. *
  19298. * 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/)
  19299. *
  19300. * @param {Object} input - The input data.
  19301. * @param {NodeBuilder} builder - The current node builder.
  19302. */
  19303. direct( { lightDirection, lightColor, reflectedLight }, builder ) {
  19304. if ( this.useSSS === true ) {
  19305. const material = builder.material;
  19306. const { thicknessColorNode, thicknessDistortionNode, thicknessAmbientNode, thicknessAttenuationNode, thicknessPowerNode, thicknessScaleNode } = material;
  19307. const scatteringHalf = lightDirection.add( normalView.mul( thicknessDistortionNode ) ).normalize();
  19308. const scatteringDot = float( positionViewDirection.dot( scatteringHalf.negate() ).saturate().pow( thicknessPowerNode ).mul( thicknessScaleNode ) );
  19309. const scatteringIllu = vec3( scatteringDot.add( thicknessAmbientNode ).mul( thicknessColorNode ) );
  19310. reflectedLight.directDiffuse.addAssign( scatteringIllu.mul( thicknessAttenuationNode.mul( lightColor ) ) );
  19311. }
  19312. super.direct( { lightDirection, lightColor, reflectedLight }, builder );
  19313. }
  19314. }
  19315. /**
  19316. * This node material is an experimental extension of {@link MeshPhysicalNodeMaterial}
  19317. * that implements a Subsurface scattering (SSS) term.
  19318. *
  19319. * @augments MeshPhysicalNodeMaterial
  19320. */
  19321. class MeshSSSNodeMaterial extends MeshPhysicalNodeMaterial {
  19322. static get type() {
  19323. return 'MeshSSSNodeMaterial';
  19324. }
  19325. /**
  19326. * Constructs a new mesh SSS node material.
  19327. *
  19328. * @param {Object} [parameters] - The configuration parameter.
  19329. */
  19330. constructor( parameters ) {
  19331. super( parameters );
  19332. /**
  19333. * Represents the thickness color.
  19334. *
  19335. * @type {?Node<vec3>}
  19336. * @default null
  19337. */
  19338. this.thicknessColorNode = null;
  19339. /**
  19340. * Represents the distortion factor.
  19341. *
  19342. * @type {?Node<float>}
  19343. */
  19344. this.thicknessDistortionNode = float( 0.1 );
  19345. /**
  19346. * Represents the thickness ambient factor.
  19347. *
  19348. * @type {?Node<float>}
  19349. */
  19350. this.thicknessAmbientNode = float( 0.0 );
  19351. /**
  19352. * Represents the thickness attenuation.
  19353. *
  19354. * @type {?Node<float>}
  19355. */
  19356. this.thicknessAttenuationNode = float( .1 );
  19357. /**
  19358. * Represents the thickness power.
  19359. *
  19360. * @type {?Node<float>}
  19361. */
  19362. this.thicknessPowerNode = float( 2.0 );
  19363. /**
  19364. * Represents the thickness scale.
  19365. *
  19366. * @type {?Node<float>}
  19367. */
  19368. this.thicknessScaleNode = float( 10.0 );
  19369. }
  19370. /**
  19371. * Whether the lighting model should use SSS or not.
  19372. *
  19373. * @type {boolean}
  19374. * @default true
  19375. */
  19376. get useSSS() {
  19377. return this.thicknessColorNode !== null;
  19378. }
  19379. /**
  19380. * Setups the lighting model.
  19381. *
  19382. * @return {SSSLightingModel} The lighting model.
  19383. */
  19384. setupLightingModel( /*builder*/ ) {
  19385. return new SSSLightingModel( this.useClearcoat, this.useSheen, this.useIridescence, this.useAnisotropy, this.useTransmission, this.useDispersion, this.useSSS );
  19386. }
  19387. copy( source ) {
  19388. this.thicknessColorNode = source.thicknessColorNode;
  19389. this.thicknessDistortionNode = source.thicknessDistortionNode;
  19390. this.thicknessAmbientNode = source.thicknessAmbientNode;
  19391. this.thicknessAttenuationNode = source.thicknessAttenuationNode;
  19392. this.thicknessPowerNode = source.thicknessPowerNode;
  19393. this.thicknessScaleNode = source.thicknessScaleNode;
  19394. return super.copy( source );
  19395. }
  19396. }
  19397. const getGradientIrradiance = /*@__PURE__*/ Fn( ( { normal, lightDirection, builder } ) => {
  19398. // dotNL will be from -1.0 to 1.0
  19399. const dotNL = normal.dot( lightDirection );
  19400. const coord = vec2( dotNL.mul( 0.5 ).add( 0.5 ), 0.0 );
  19401. if ( builder.material.gradientMap ) {
  19402. const gradientMap = materialReference( 'gradientMap', 'texture' ).context( { getUV: () => coord } );
  19403. return vec3( gradientMap.r );
  19404. } else {
  19405. const fw = coord.fwidth().mul( 0.5 );
  19406. return mix( vec3( 0.7 ), vec3( 1.0 ), smoothstep( float( 0.7 ).sub( fw.x ), float( 0.7 ).add( fw.x ), coord.x ) );
  19407. }
  19408. } );
  19409. /**
  19410. * Represents the lighting model for a toon material. Used in {@link MeshToonNodeMaterial}.
  19411. *
  19412. * @augments LightingModel
  19413. */
  19414. class ToonLightingModel extends LightingModel {
  19415. /**
  19416. * Implements the direct lighting. Instead of using a conventional smooth irradiance, the irradiance is
  19417. * reduced to a small number of discrete shades to create a comic-like, flat look.
  19418. *
  19419. * @param {Object} lightData - The light data.
  19420. * @param {NodeBuilder} builder - The current node builder.
  19421. */
  19422. direct( { lightDirection, lightColor, reflectedLight }, builder ) {
  19423. const irradiance = getGradientIrradiance( { normal: normalGeometry, lightDirection, builder } ).mul( lightColor );
  19424. reflectedLight.directDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor: diffuseColor.rgb } ) ) );
  19425. }
  19426. /**
  19427. * Implements the indirect lighting.
  19428. *
  19429. * @param {NodeBuilder} builder - The current node builder.
  19430. */
  19431. indirect( builder ) {
  19432. const { ambientOcclusion, irradiance, reflectedLight } = builder.context;
  19433. reflectedLight.indirectDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor } ) ) );
  19434. reflectedLight.indirectDiffuse.mulAssign( ambientOcclusion );
  19435. }
  19436. }
  19437. const _defaultValues$4 = /*@__PURE__*/ new MeshToonMaterial();
  19438. /**
  19439. * Node material version of {@link MeshToonMaterial}.
  19440. *
  19441. * @augments NodeMaterial
  19442. */
  19443. class MeshToonNodeMaterial extends NodeMaterial {
  19444. static get type() {
  19445. return 'MeshToonNodeMaterial';
  19446. }
  19447. /**
  19448. * Constructs a new mesh toon node material.
  19449. *
  19450. * @param {Object} [parameters] - The configuration parameter.
  19451. */
  19452. constructor( parameters ) {
  19453. super();
  19454. /**
  19455. * This flag can be used for type testing.
  19456. *
  19457. * @type {boolean}
  19458. * @readonly
  19459. * @default true
  19460. */
  19461. this.isMeshToonNodeMaterial = true;
  19462. /**
  19463. * Set to `true` because toon materials react on lights.
  19464. *
  19465. * @type {boolean}
  19466. * @default true
  19467. */
  19468. this.lights = true;
  19469. this.setDefaultValues( _defaultValues$4 );
  19470. this.setValues( parameters );
  19471. }
  19472. /**
  19473. * Setups the lighting model.
  19474. *
  19475. * @return {ToonLightingModel} The lighting model.
  19476. */
  19477. setupLightingModel( /*builder*/ ) {
  19478. return new ToonLightingModel();
  19479. }
  19480. }
  19481. /**
  19482. * TSL function for creating a matcap uv node.
  19483. *
  19484. * Can be used to compute texture coordinates for projecting a
  19485. * matcap onto a mesh. Used by {@link MeshMatcapNodeMaterial}.
  19486. *
  19487. * @tsl
  19488. * @function
  19489. * @returns {Node<vec2>} The matcap UV coordinates.
  19490. */
  19491. const matcapUV = /*@__PURE__*/ Fn( () => {
  19492. const x = vec3( positionViewDirection.z, 0, positionViewDirection.x.negate() ).normalize();
  19493. const y = positionViewDirection.cross( x );
  19494. return vec2( x.dot( normalView ), y.dot( normalView ) ).mul( 0.495 ).add( 0.5 ); // 0.495 to remove artifacts caused by undersized matcap disks
  19495. } ).once( [ 'NORMAL', 'VERTEX' ] )().toVar( 'matcapUV' );
  19496. const _defaultValues$3 = /*@__PURE__*/ new MeshMatcapMaterial();
  19497. /**
  19498. * Node material version of {@link MeshMatcapMaterial}.
  19499. *
  19500. * @augments NodeMaterial
  19501. */
  19502. class MeshMatcapNodeMaterial extends NodeMaterial {
  19503. static get type() {
  19504. return 'MeshMatcapNodeMaterial';
  19505. }
  19506. /**
  19507. * Constructs a new mesh normal node material.
  19508. *
  19509. * @param {Object} [parameters] - The configuration parameter.
  19510. */
  19511. constructor( parameters ) {
  19512. super();
  19513. /**
  19514. * This flag can be used for type testing.
  19515. *
  19516. * @type {boolean}
  19517. * @readonly
  19518. * @default true
  19519. */
  19520. this.isMeshMatcapNodeMaterial = true;
  19521. this.setDefaultValues( _defaultValues$3 );
  19522. this.setValues( parameters );
  19523. }
  19524. /**
  19525. * Setups the matcap specific node variables.
  19526. *
  19527. * @param {NodeBuilder} builder - The current node builder.
  19528. */
  19529. setupVariants( builder ) {
  19530. const uv = matcapUV;
  19531. let matcapColor;
  19532. if ( builder.material.matcap ) {
  19533. matcapColor = materialReference( 'matcap', 'texture' ).context( { getUV: () => uv } );
  19534. } else {
  19535. matcapColor = vec3( mix( 0.2, 0.8, uv.y ) ); // default if matcap is missing
  19536. }
  19537. diffuseColor.rgb.mulAssign( matcapColor.rgb );
  19538. }
  19539. }
  19540. /**
  19541. * Applies a rotation to the given position node.
  19542. *
  19543. * @augments TempNode
  19544. */
  19545. class RotateNode extends TempNode {
  19546. static get type() {
  19547. return 'RotateNode';
  19548. }
  19549. /**
  19550. * Constructs a new rotate node.
  19551. *
  19552. * @param {Node} positionNode - The position node.
  19553. * @param {Node} rotationNode - Represents the rotation that is applied to the position node. Depending
  19554. * on whether the position data are 2D or 3D, the rotation is expressed a single float value or an Euler value.
  19555. */
  19556. constructor( positionNode, rotationNode ) {
  19557. super();
  19558. /**
  19559. * The position node.
  19560. *
  19561. * @type {Node}
  19562. */
  19563. this.positionNode = positionNode;
  19564. /**
  19565. * Represents the rotation that is applied to the position node.
  19566. * Depending on whether the position data are 2D or 3D, the rotation is expressed a single float value or an Euler value.
  19567. *
  19568. * @type {Node}
  19569. */
  19570. this.rotationNode = rotationNode;
  19571. }
  19572. /**
  19573. * The type of the {@link RotateNode#positionNode} defines the node's type.
  19574. *
  19575. * @param {NodeBuilder} builder - The current node builder.
  19576. * @return {string} The node's type.
  19577. */
  19578. getNodeType( builder ) {
  19579. return this.positionNode.getNodeType( builder );
  19580. }
  19581. setup( builder ) {
  19582. const { rotationNode, positionNode } = this;
  19583. const nodeType = this.getNodeType( builder );
  19584. if ( nodeType === 'vec2' ) {
  19585. const cosAngle = rotationNode.cos();
  19586. const sinAngle = rotationNode.sin();
  19587. const rotationMatrix = mat2(
  19588. cosAngle, sinAngle,
  19589. sinAngle.negate(), cosAngle
  19590. );
  19591. return rotationMatrix.mul( positionNode );
  19592. } else {
  19593. const rotation = rotationNode;
  19594. 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 ) );
  19595. 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 ) );
  19596. 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 ) );
  19597. return rotationXMatrix.mul( rotationYMatrix ).mul( rotationZMatrix ).mul( vec4( positionNode, 1.0 ) ).xyz;
  19598. }
  19599. }
  19600. }
  19601. /**
  19602. * TSL function for creating a rotate node.
  19603. *
  19604. * @tsl
  19605. * @function
  19606. * @param {Node} positionNode - The position node.
  19607. * @param {Node} rotationNode - Represents the rotation that is applied to the position node. Depending
  19608. * on whether the position data are 2D or 3D, the rotation is expressed a single float value or an Euler value.
  19609. * @returns {RotateNode}
  19610. */
  19611. const rotate = /*@__PURE__*/ nodeProxy( RotateNode ).setParameterLength( 2 );
  19612. const _defaultValues$2 = /*@__PURE__*/ new SpriteMaterial();
  19613. /**
  19614. * Node material version of {@link SpriteMaterial}.
  19615. *
  19616. * @augments NodeMaterial
  19617. */
  19618. class SpriteNodeMaterial extends NodeMaterial {
  19619. static get type() {
  19620. return 'SpriteNodeMaterial';
  19621. }
  19622. /**
  19623. * Constructs a new sprite node material.
  19624. *
  19625. * @param {Object} [parameters] - The configuration parameter.
  19626. */
  19627. constructor( parameters ) {
  19628. super();
  19629. /**
  19630. * This flag can be used for type testing.
  19631. *
  19632. * @type {boolean}
  19633. * @readonly
  19634. * @default true
  19635. */
  19636. this.isSpriteNodeMaterial = true;
  19637. this._useSizeAttenuation = true;
  19638. /**
  19639. * This property makes it possible to define the position of the sprite with a
  19640. * node. That can be useful when the material is used with instanced rendering
  19641. * and node data are defined with an instanced attribute node:
  19642. * ```js
  19643. * const positionAttribute = new InstancedBufferAttribute( new Float32Array( positions ), 3 );
  19644. * material.positionNode = instancedBufferAttribute( positionAttribute );
  19645. * ```
  19646. * Another possibility is to compute the instanced data with a compute shader:
  19647. * ```js
  19648. * const positionBuffer = instancedArray( particleCount, 'vec3' );
  19649. * particleMaterial.positionNode = positionBuffer.toAttribute();
  19650. * ```
  19651. *
  19652. * @type {?Node<vec2>}
  19653. * @default null
  19654. */
  19655. this.positionNode = null;
  19656. /**
  19657. * The rotation of sprite materials is by default inferred from the `rotation`,
  19658. * property. This node property allows to overwrite the default and define
  19659. * the rotation with a node instead.
  19660. *
  19661. * If you don't want to overwrite the rotation but modify the existing
  19662. * value instead, use {@link materialRotation}.
  19663. *
  19664. * @type {?Node<float>}
  19665. * @default null
  19666. */
  19667. this.rotationNode = null;
  19668. /**
  19669. * This node property provides an additional way to scale sprites next to
  19670. * `Object3D.scale`. The scale transformation based in `Object3D.scale`
  19671. * is multiplied with the scale value of this node in the vertex shader.
  19672. *
  19673. * @type {?Node<vec2>}
  19674. * @default null
  19675. */
  19676. this.scaleNode = null;
  19677. /**
  19678. * In Sprites, the transparent property is enabled by default.
  19679. *
  19680. * @type {boolean}
  19681. * @default true
  19682. */
  19683. this.transparent = true;
  19684. this.setDefaultValues( _defaultValues$2 );
  19685. this.setValues( parameters );
  19686. }
  19687. /**
  19688. * Setups the position node in view space. This method implements
  19689. * the sprite specific vertex shader.
  19690. *
  19691. * @param {NodeBuilder} builder - The current node builder.
  19692. * @return {Node<vec3>} The position in view space.
  19693. */
  19694. setupPositionView( builder ) {
  19695. const { object, camera } = builder;
  19696. const { positionNode, rotationNode, scaleNode, sizeAttenuation } = this;
  19697. const mvPosition = modelViewMatrix.mul( vec3( positionNode || 0 ) );
  19698. let scale = vec2( modelWorldMatrix[ 0 ].xyz.length(), modelWorldMatrix[ 1 ].xyz.length() );
  19699. if ( scaleNode !== null ) {
  19700. scale = scale.mul( vec2( scaleNode ) );
  19701. }
  19702. if ( camera.isPerspectiveCamera && sizeAttenuation === false ) {
  19703. scale = scale.mul( mvPosition.z.negate() );
  19704. }
  19705. let alignedPosition = positionGeometry.xy;
  19706. if ( object.center && object.center.isVector2 === true ) {
  19707. const center = reference$1( 'center', 'vec2', object );
  19708. alignedPosition = alignedPosition.sub( center.sub( 0.5 ) );
  19709. }
  19710. alignedPosition = alignedPosition.mul( scale );
  19711. const rotation = float( rotationNode || materialRotation );
  19712. const rotatedPosition = rotate( alignedPosition, rotation );
  19713. return vec4( mvPosition.xy.add( rotatedPosition ), mvPosition.zw );
  19714. }
  19715. copy( source ) {
  19716. this.positionNode = source.positionNode;
  19717. this.rotationNode = source.rotationNode;
  19718. this.scaleNode = source.scaleNode;
  19719. return super.copy( source );
  19720. }
  19721. /**
  19722. * Whether to use size attenuation or not.
  19723. *
  19724. * @type {boolean}
  19725. * @default true
  19726. */
  19727. get sizeAttenuation() {
  19728. return this._useSizeAttenuation;
  19729. }
  19730. set sizeAttenuation( value ) {
  19731. if ( this._useSizeAttenuation !== value ) {
  19732. this._useSizeAttenuation = value;
  19733. this.needsUpdate = true;
  19734. }
  19735. }
  19736. }
  19737. const _defaultValues$1 = /*@__PURE__*/ new PointsMaterial();
  19738. const _size$4 = /*@__PURE__*/ new Vector2();
  19739. /**
  19740. * Node material version of {@link PointsMaterial}.
  19741. *
  19742. * This material can be used in two ways:
  19743. *
  19744. * - By rendering point primitives with {@link Points}. Since WebGPU only supports point primitives
  19745. * with a pixel size of `1`, it's not possible to define a size.
  19746. *
  19747. * ```js
  19748. * const pointCloud = new THREE.Points( geometry, new THREE.PointsNodeMaterial() );
  19749. * ```
  19750. *
  19751. * - By rendering point primitives with {@link Sprites}. In this case, size is honored,
  19752. * see {@link PointsNodeMaterial#sizeNode}.
  19753. *
  19754. * ```js
  19755. * const instancedPoints = new THREE.Sprite( new THREE.PointsNodeMaterial( { positionNode: instancedBufferAttribute( positionAttribute ) } ) );
  19756. * ```
  19757. *
  19758. * @augments SpriteNodeMaterial
  19759. */
  19760. class PointsNodeMaterial extends SpriteNodeMaterial {
  19761. static get type() {
  19762. return 'PointsNodeMaterial';
  19763. }
  19764. /**
  19765. * Constructs a new points node material.
  19766. *
  19767. * @param {Object} [parameters] - The configuration parameter.
  19768. */
  19769. constructor( parameters ) {
  19770. super();
  19771. /**
  19772. * This node property provides an additional way to set the point size.
  19773. *
  19774. * Note that WebGPU only supports point primitives with 1 pixel size. Consequently,
  19775. * this node has no effect when the material is used with {@link Points} and a WebGPU
  19776. * backend. If an application wants to render points with a size larger than 1 pixel,
  19777. * the material should be used with {@link Sprite} and instancing.
  19778. *
  19779. * @type {?Node<vec2>}
  19780. * @default null
  19781. */
  19782. this.sizeNode = null;
  19783. /**
  19784. * This flag can be used for type testing.
  19785. *
  19786. * @type {boolean}
  19787. * @readonly
  19788. * @default true
  19789. */
  19790. this.isPointsNodeMaterial = true;
  19791. this.setDefaultValues( _defaultValues$1 );
  19792. this.setValues( parameters );
  19793. }
  19794. setupPositionView() {
  19795. const { positionNode } = this;
  19796. return modelViewMatrix.mul( vec3( positionNode || positionLocal ) ).xyz;
  19797. }
  19798. setupVertexSprite( builder ) {
  19799. const { material, camera } = builder;
  19800. const { rotationNode, scaleNode, sizeNode, sizeAttenuation } = this;
  19801. let mvp = super.setupVertex( builder );
  19802. // skip further processing if the material is not a node material
  19803. if ( material.isNodeMaterial !== true ) {
  19804. return mvp;
  19805. }
  19806. // point size
  19807. let pointSize = sizeNode !== null ? vec2( sizeNode ) : materialPointSize;
  19808. pointSize = pointSize.mul( screenDPR );
  19809. // size attenuation
  19810. if ( camera.isPerspectiveCamera && sizeAttenuation === true ) {
  19811. // follow WebGLRenderer's implementation, and scale by half the canvas height in logical units
  19812. pointSize = pointSize.mul( scale.div( positionView.z.negate() ) );
  19813. }
  19814. // scale
  19815. if ( scaleNode && scaleNode.isNode ) {
  19816. pointSize = pointSize.mul( vec2( scaleNode ) );
  19817. }
  19818. // compute offset
  19819. let offset = positionGeometry.xy;
  19820. // apply rotation
  19821. if ( rotationNode && rotationNode.isNode ) {
  19822. const rotation = float( rotationNode );
  19823. offset = rotate( offset, rotation );
  19824. }
  19825. // account for point size
  19826. offset = offset.mul( pointSize );
  19827. // scale by viewport size
  19828. offset = offset.div( viewportSize.div( 2 ) );
  19829. // compensate for the perspective divide
  19830. offset = offset.mul( mvp.w );
  19831. // add offset
  19832. mvp = mvp.add( vec4( offset, 0, 0 ) );
  19833. return mvp;
  19834. }
  19835. setupVertex( builder ) {
  19836. if ( builder.object.isPoints ) {
  19837. return super.setupVertex( builder );
  19838. } else {
  19839. return this.setupVertexSprite( builder );
  19840. }
  19841. }
  19842. /**
  19843. * Whether alpha to coverage should be used or not.
  19844. *
  19845. * @type {boolean}
  19846. * @default true
  19847. */
  19848. get alphaToCoverage() {
  19849. return this._useAlphaToCoverage;
  19850. }
  19851. set alphaToCoverage( value ) {
  19852. if ( this._useAlphaToCoverage !== value ) {
  19853. this._useAlphaToCoverage = value;
  19854. this.needsUpdate = true;
  19855. }
  19856. }
  19857. }
  19858. const scale = /*@__PURE__*/ uniform( 1 ).onFrameUpdate( function ( { renderer } ) {
  19859. const size = renderer.getSize( _size$4 ); // logical units
  19860. this.value = 0.5 * size.y;
  19861. } );
  19862. /**
  19863. * Represents lighting model for a shadow material. Used in {@link ShadowNodeMaterial}.
  19864. *
  19865. * @augments LightingModel
  19866. */
  19867. class ShadowMaskModel extends LightingModel {
  19868. /**
  19869. * Constructs a new shadow mask model.
  19870. */
  19871. constructor() {
  19872. super();
  19873. /**
  19874. * The shadow mask node.
  19875. *
  19876. * @type {Node}
  19877. */
  19878. this.shadowNode = float( 1 ).toVar( 'shadowMask' );
  19879. }
  19880. /**
  19881. * Only used to save the shadow mask.
  19882. *
  19883. * @param {Object} input - The input data.
  19884. */
  19885. direct( { lightNode } ) {
  19886. if ( lightNode.shadowNode !== null ) {
  19887. this.shadowNode.mulAssign( lightNode.shadowNode );
  19888. }
  19889. }
  19890. /**
  19891. * Uses the shadow mask to produce the final color.
  19892. *
  19893. * @param {NodeBuilder} builder - The current node builder.
  19894. */
  19895. finish( { context } ) {
  19896. diffuseColor.a.mulAssign( this.shadowNode.oneMinus() );
  19897. context.outgoingLight.rgb.assign( diffuseColor.rgb ); // TODO: Optimize LightsNode to avoid this assignment
  19898. }
  19899. }
  19900. const _defaultValues = /*@__PURE__*/ new ShadowMaterial();
  19901. /**
  19902. * Node material version of {@link ShadowMaterial}.
  19903. *
  19904. * @augments NodeMaterial
  19905. */
  19906. class ShadowNodeMaterial extends NodeMaterial {
  19907. static get type() {
  19908. return 'ShadowNodeMaterial';
  19909. }
  19910. /**
  19911. * Constructs a new shadow node material.
  19912. *
  19913. * @param {Object} [parameters] - The configuration parameter.
  19914. */
  19915. constructor( parameters ) {
  19916. super();
  19917. /**
  19918. * This flag can be used for type testing.
  19919. *
  19920. * @type {boolean}
  19921. * @readonly
  19922. * @default true
  19923. */
  19924. this.isShadowNodeMaterial = true;
  19925. /**
  19926. * Set to `true` because so it's possible to implement
  19927. * the shadow mask effect.
  19928. *
  19929. * @type {boolean}
  19930. * @default true
  19931. */
  19932. this.lights = true;
  19933. /**
  19934. * Overwritten since shadow materials are transparent
  19935. * by default.
  19936. *
  19937. * @type {boolean}
  19938. * @default true
  19939. */
  19940. this.transparent = true;
  19941. this.setDefaultValues( _defaultValues );
  19942. this.setValues( parameters );
  19943. }
  19944. /**
  19945. * Setups the lighting model.
  19946. *
  19947. * @return {ShadowMaskModel} The lighting model.
  19948. */
  19949. setupLightingModel( /*builder*/ ) {
  19950. return new ShadowMaskModel();
  19951. }
  19952. }
  19953. const scatteringDensity = property( 'vec3' );
  19954. const linearDepthRay = property( 'vec3' );
  19955. const outgoingRayLight = property( 'vec3' );
  19956. /**
  19957. * VolumetricLightingModel class extends the LightingModel to implement volumetric lighting effects.
  19958. * This model calculates the scattering and transmittance of light through a volumetric medium.
  19959. * It dynamically adjusts the direction of the ray based on the camera and object positions.
  19960. * The model supports custom scattering and depth nodes to enhance the lighting effects.
  19961. *
  19962. * @augments LightingModel
  19963. */
  19964. class VolumetricLightingModel extends LightingModel {
  19965. constructor() {
  19966. super();
  19967. }
  19968. start( builder ) {
  19969. const { material } = builder;
  19970. const startPos = property( 'vec3' );
  19971. const endPos = property( 'vec3' );
  19972. // This approach dynamically changes the direction of the ray,
  19973. // 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.
  19974. If( cameraPosition.sub( positionWorld ).length().greaterThan( modelRadius.mul( 2 ) ), () => {
  19975. startPos.assign( cameraPosition );
  19976. endPos.assign( positionWorld );
  19977. } ).Else( () => {
  19978. startPos.assign( positionWorld );
  19979. endPos.assign( cameraPosition );
  19980. } );
  19981. //
  19982. const viewVector = endPos.sub( startPos );
  19983. const steps = uniform( 'int' ).onRenderUpdate( ( { material } ) => material.steps );
  19984. const stepSize = viewVector.length().div( steps ).toVar();
  19985. const rayDir = viewVector.normalize().toVar(); // TODO: toVar() should be automatic here ( in loop )
  19986. const distTravelled = float( 0.0 ).toVar();
  19987. const transmittance = vec3( 1 ).toVar();
  19988. if ( material.offsetNode ) {
  19989. // reduce banding
  19990. distTravelled.addAssign( material.offsetNode.mul( stepSize ) );
  19991. }
  19992. Loop( steps, () => {
  19993. const positionRay = startPos.add( rayDir.mul( distTravelled ) );
  19994. const positionViewRay = cameraViewMatrix.mul( vec4( positionRay, 1 ) ).xyz;
  19995. if ( material.depthNode !== null ) {
  19996. linearDepthRay.assign( linearDepth( viewZToPerspectiveDepth( positionViewRay.z, cameraNear, cameraFar ) ) );
  19997. builder.context.sceneDepthNode = linearDepth( material.depthNode ).toVar();
  19998. }
  19999. builder.context.positionWorld = positionRay;
  20000. builder.context.shadowPositionWorld = positionRay;
  20001. builder.context.positionView = positionViewRay;
  20002. scatteringDensity.assign( 0 );
  20003. let scatteringNode;
  20004. if ( material.scatteringNode ) {
  20005. scatteringNode = material.scatteringNode( {
  20006. positionRay
  20007. } );
  20008. }
  20009. super.start( builder );
  20010. if ( scatteringNode ) {
  20011. scatteringDensity.mulAssign( scatteringNode );
  20012. }
  20013. // beer's law
  20014. const falloff = scatteringDensity.mul( .01 ).negate().mul( stepSize ).exp();
  20015. transmittance.mulAssign( falloff );
  20016. // move along the ray
  20017. distTravelled.addAssign( stepSize );
  20018. } );
  20019. outgoingRayLight.addAssign( transmittance.saturate().oneMinus() );
  20020. }
  20021. scatteringLight( lightColor, builder ) {
  20022. const sceneDepthNode = builder.context.sceneDepthNode;
  20023. if ( sceneDepthNode ) {
  20024. If( sceneDepthNode.greaterThanEqual( linearDepthRay ), () => {
  20025. scatteringDensity.addAssign( lightColor );
  20026. } );
  20027. } else {
  20028. scatteringDensity.addAssign( lightColor );
  20029. }
  20030. }
  20031. direct( { lightNode, lightColor }, builder ) {
  20032. // Ignore lights with infinite distance
  20033. if ( lightNode.light.distance === undefined ) return;
  20034. // TODO: We need a viewportOpaque*() ( output, depth ) to fit with modern rendering approaches
  20035. const directLight = lightColor.xyz.toVar();
  20036. directLight.mulAssign( lightNode.shadowNode ); // it no should be necessary if used in the same render pass
  20037. this.scatteringLight( directLight, builder );
  20038. }
  20039. directRectArea( { lightColor, lightPosition, halfWidth, halfHeight }, builder ) {
  20040. const p0 = lightPosition.add( halfWidth ).sub( halfHeight ); // counterclockwise; light shines in local neg z direction
  20041. const p1 = lightPosition.sub( halfWidth ).sub( halfHeight );
  20042. const p2 = lightPosition.sub( halfWidth ).add( halfHeight );
  20043. const p3 = lightPosition.add( halfWidth ).add( halfHeight );
  20044. const P = builder.context.positionView;
  20045. const directLight = lightColor.xyz.mul( LTC_Evaluate_Volume( { P, p0, p1, p2, p3 } ) ).pow( 1.5 );
  20046. this.scatteringLight( directLight, builder );
  20047. }
  20048. finish( builder ) {
  20049. builder.context.outgoingLight.assign( outgoingRayLight );
  20050. }
  20051. }
  20052. /**
  20053. * Volume node material.
  20054. *
  20055. * @augments NodeMaterial
  20056. */
  20057. class VolumeNodeMaterial extends NodeMaterial {
  20058. static get type() {
  20059. return 'VolumeNodeMaterial';
  20060. }
  20061. /**
  20062. * Constructs a new volume node material.
  20063. *
  20064. * @param {Object} [parameters] - The configuration parameter.
  20065. */
  20066. constructor( parameters ) {
  20067. super();
  20068. /**
  20069. * This flag can be used for type testing.
  20070. *
  20071. * @type {boolean}
  20072. * @readonly
  20073. * @default true
  20074. */
  20075. this.isVolumeNodeMaterial = true;
  20076. /**
  20077. * Number of steps used for raymarching.
  20078. *
  20079. * @type {number}
  20080. * @default 25
  20081. */
  20082. this.steps = 25;
  20083. /**
  20084. * Offsets the distance a ray has been traveled through a volume.
  20085. * Can be used to implement dithering to reduce banding.
  20086. *
  20087. * @type {Node<float>}
  20088. * @default null
  20089. */
  20090. this.offsetNode = null;
  20091. /**
  20092. * Node used for scattering calculations.
  20093. *
  20094. * @type {Function|FunctionNode<vec4>}
  20095. * @default null
  20096. */
  20097. this.scatteringNode = null;
  20098. this.lights = true;
  20099. this.transparent = true;
  20100. this.side = BackSide;
  20101. this.depthTest = false;
  20102. this.depthWrite = false;
  20103. this.setValues( parameters );
  20104. }
  20105. setupLightingModel() {
  20106. return new VolumetricLightingModel();
  20107. }
  20108. }
  20109. /**
  20110. * This module manages the internal animation loop of the renderer.
  20111. *
  20112. * @private
  20113. */
  20114. class Animation {
  20115. /**
  20116. * Constructs a new animation loop management component.
  20117. *
  20118. * @param {Renderer} renderer - A reference to the main renderer.
  20119. * @param {Nodes} nodes - Renderer component for managing nodes related logic.
  20120. * @param {Info} info - Renderer component for managing metrics and monitoring data.
  20121. */
  20122. constructor( renderer, nodes, info ) {
  20123. /**
  20124. * A reference to the main renderer.
  20125. *
  20126. * @type {Renderer}
  20127. */
  20128. this.renderer = renderer;
  20129. /**
  20130. * Renderer component for managing nodes related logic.
  20131. *
  20132. * @type {Nodes}
  20133. */
  20134. this.nodes = nodes;
  20135. /**
  20136. * Renderer component for managing metrics and monitoring data.
  20137. *
  20138. * @type {Info}
  20139. */
  20140. this.info = info;
  20141. /**
  20142. * A reference to the context from `requestAnimationFrame()` can
  20143. * be called (usually `window`).
  20144. *
  20145. * @type {?(Window|XRSession)}
  20146. */
  20147. this._context = typeof self !== 'undefined' ? self : null;
  20148. /**
  20149. * The user-defined animation loop.
  20150. *
  20151. * @type {?Function}
  20152. * @default null
  20153. */
  20154. this._animationLoop = null;
  20155. /**
  20156. * The requestId which is returned from the `requestAnimationFrame()` call.
  20157. * Can be used to cancel the stop the animation loop.
  20158. *
  20159. * @type {?number}
  20160. * @default null
  20161. */
  20162. this._requestId = null;
  20163. }
  20164. /**
  20165. * Starts the internal animation loop.
  20166. */
  20167. start() {
  20168. const update = ( time, xrFrame ) => {
  20169. this._requestId = this._context.requestAnimationFrame( update );
  20170. if ( this.info.autoReset === true ) this.info.reset();
  20171. this.nodes.nodeFrame.update();
  20172. this.info.frame = this.nodes.nodeFrame.frameId;
  20173. this.renderer._inspector.begin();
  20174. if ( this._animationLoop !== null ) this._animationLoop( time, xrFrame );
  20175. this.renderer._inspector.finish();
  20176. };
  20177. update();
  20178. }
  20179. /**
  20180. * Stops the internal animation loop.
  20181. */
  20182. stop() {
  20183. this._context.cancelAnimationFrame( this._requestId );
  20184. this._requestId = null;
  20185. }
  20186. /**
  20187. * Returns the user-level animation loop.
  20188. *
  20189. * @return {?Function} The animation loop.
  20190. */
  20191. getAnimationLoop() {
  20192. return this._animationLoop;
  20193. }
  20194. /**
  20195. * Defines the user-level animation loop.
  20196. *
  20197. * @param {?Function} callback - The animation loop.
  20198. */
  20199. setAnimationLoop( callback ) {
  20200. this._animationLoop = callback;
  20201. }
  20202. /**
  20203. * Returns the animation context.
  20204. *
  20205. * @return {Window|XRSession} The animation context.
  20206. */
  20207. getContext() {
  20208. return this._context;
  20209. }
  20210. /**
  20211. * Defines the context in which `requestAnimationFrame()` is executed.
  20212. *
  20213. * @param {Window|XRSession} context - The context to set.
  20214. */
  20215. setContext( context ) {
  20216. this._context = context;
  20217. }
  20218. /**
  20219. * Frees all internal resources and stops the animation loop.
  20220. */
  20221. dispose() {
  20222. this.stop();
  20223. }
  20224. }
  20225. /**
  20226. * Data structure for the renderer. It allows defining values
  20227. * with chained, hierarchical keys. Keys are meant to be
  20228. * objects since the module internally works with Weak Maps
  20229. * for performance reasons.
  20230. *
  20231. * @private
  20232. */
  20233. class ChainMap {
  20234. /**
  20235. * Constructs a new Chain Map.
  20236. */
  20237. constructor() {
  20238. /**
  20239. * A map of Weak Maps by their key length.
  20240. *
  20241. * @type {Object<number, WeakMap>}
  20242. */
  20243. this.weakMaps = {};
  20244. }
  20245. /**
  20246. * Returns the Weak Map for the given keys.
  20247. *
  20248. * @param {Array<Object>} keys - List of keys.
  20249. * @return {WeakMap} The weak map.
  20250. */
  20251. _getWeakMap( keys ) {
  20252. const length = keys.length;
  20253. let weakMap = this.weakMaps[ length ];
  20254. if ( weakMap === undefined ) {
  20255. weakMap = new WeakMap();
  20256. this.weakMaps[ length ] = weakMap;
  20257. }
  20258. return weakMap;
  20259. }
  20260. /**
  20261. * Returns the value for the given array of keys.
  20262. *
  20263. * @param {Array<Object>} keys - List of keys.
  20264. * @return {any} The value. Returns `undefined` if no value was found.
  20265. */
  20266. get( keys ) {
  20267. let map = this._getWeakMap( keys );
  20268. for ( let i = 0; i < keys.length - 1; i ++ ) {
  20269. map = map.get( keys[ i ] );
  20270. if ( map === undefined ) return undefined;
  20271. }
  20272. return map.get( keys[ keys.length - 1 ] );
  20273. }
  20274. /**
  20275. * Sets the value for the given keys.
  20276. *
  20277. * @param {Array<Object>} keys - List of keys.
  20278. * @param {any} value - The value to set.
  20279. * @return {ChainMap} A reference to this Chain Map.
  20280. */
  20281. set( keys, value ) {
  20282. let map = this._getWeakMap( keys );
  20283. for ( let i = 0; i < keys.length - 1; i ++ ) {
  20284. const key = keys[ i ];
  20285. if ( map.has( key ) === false ) map.set( key, new WeakMap() );
  20286. map = map.get( key );
  20287. }
  20288. map.set( keys[ keys.length - 1 ], value );
  20289. return this;
  20290. }
  20291. /**
  20292. * Deletes a value for the given keys.
  20293. *
  20294. * @param {Array<Object>} keys - The keys.
  20295. * @return {boolean} Returns `true` if the value has been removed successfully and `false` if the value has not be found.
  20296. */
  20297. delete( keys ) {
  20298. let map = this._getWeakMap( keys );
  20299. for ( let i = 0; i < keys.length - 1; i ++ ) {
  20300. map = map.get( keys[ i ] );
  20301. if ( map === undefined ) return false;
  20302. }
  20303. return map.delete( keys[ keys.length - 1 ] );
  20304. }
  20305. }
  20306. let _id$a = 0;
  20307. function getKeys( obj ) {
  20308. const keys = Object.keys( obj );
  20309. let proto = Object.getPrototypeOf( obj );
  20310. while ( proto ) {
  20311. const descriptors = Object.getOwnPropertyDescriptors( proto );
  20312. for ( const key in descriptors ) {
  20313. if ( descriptors[ key ] !== undefined ) {
  20314. const descriptor = descriptors[ key ];
  20315. if ( descriptor && typeof descriptor.get === 'function' ) {
  20316. keys.push( key );
  20317. }
  20318. }
  20319. }
  20320. proto = Object.getPrototypeOf( proto );
  20321. }
  20322. return keys;
  20323. }
  20324. /**
  20325. * A render object is the renderer's representation of single entity that gets drawn
  20326. * with a draw command. There is no unique mapping of render objects to 3D objects in the
  20327. * scene since render objects also depend from the used material, the current render context
  20328. * and the current scene's lighting.
  20329. *
  20330. * In general, the basic process of the renderer is:
  20331. *
  20332. * - Analyze the 3D objects in the scene and generate render lists containing render items.
  20333. * - Process the render lists by calling one or more render commands for each render item.
  20334. * - For each render command, request a render object and perform the draw.
  20335. *
  20336. * The module provides an interface to get data required for the draw command like the actual
  20337. * draw parameters or vertex buffers. It also holds a series of caching related methods since
  20338. * creating render objects should only be done when necessary.
  20339. *
  20340. * @private
  20341. */
  20342. class RenderObject {
  20343. /**
  20344. * Constructs a new render object.
  20345. *
  20346. * @param {Nodes} nodes - Renderer component for managing nodes related logic.
  20347. * @param {Geometries} geometries - Renderer component for managing geometries.
  20348. * @param {Renderer} renderer - The renderer.
  20349. * @param {Object3D} object - The 3D object.
  20350. * @param {Material} material - The 3D object's material.
  20351. * @param {Scene} scene - The scene the 3D object belongs to.
  20352. * @param {Camera} camera - The camera the object should be rendered with.
  20353. * @param {LightsNode} lightsNode - The lights node.
  20354. * @param {RenderContext} renderContext - The render context.
  20355. * @param {ClippingContext} clippingContext - The clipping context.
  20356. */
  20357. constructor( nodes, geometries, renderer, object, material, scene, camera, lightsNode, renderContext, clippingContext ) {
  20358. this.id = _id$a ++;
  20359. /**
  20360. * Renderer component for managing nodes related logic.
  20361. *
  20362. * @type {Nodes}
  20363. * @private
  20364. */
  20365. this._nodes = nodes;
  20366. /**
  20367. * Renderer component for managing geometries.
  20368. *
  20369. * @type {Geometries}
  20370. * @private
  20371. */
  20372. this._geometries = geometries;
  20373. /**
  20374. * The renderer.
  20375. *
  20376. * @type {Renderer}
  20377. */
  20378. this.renderer = renderer;
  20379. /**
  20380. * The 3D object.
  20381. *
  20382. * @type {Object3D}
  20383. */
  20384. this.object = object;
  20385. /**
  20386. * The 3D object's material.
  20387. *
  20388. * @type {Material}
  20389. */
  20390. this.material = material;
  20391. /**
  20392. * The scene the 3D object belongs to.
  20393. *
  20394. * @type {Scene}
  20395. */
  20396. this.scene = scene;
  20397. /**
  20398. * The camera the 3D object should be rendered with.
  20399. *
  20400. * @type {Camera}
  20401. */
  20402. this.camera = camera;
  20403. /**
  20404. * The lights node.
  20405. *
  20406. * @type {LightsNode}
  20407. */
  20408. this.lightsNode = lightsNode;
  20409. /**
  20410. * The render context.
  20411. *
  20412. * @type {RenderContext}
  20413. */
  20414. this.context = renderContext;
  20415. /**
  20416. * The 3D object's geometry.
  20417. *
  20418. * @type {BufferGeometry}
  20419. */
  20420. this.geometry = object.geometry;
  20421. /**
  20422. * The render object's version.
  20423. *
  20424. * @type {number}
  20425. */
  20426. this.version = material.version;
  20427. /**
  20428. * The draw range of the geometry.
  20429. *
  20430. * @type {?Object}
  20431. * @default null
  20432. */
  20433. this.drawRange = null;
  20434. /**
  20435. * An array holding the buffer attributes
  20436. * of the render object. This entails attribute
  20437. * definitions on geometry and node level.
  20438. *
  20439. * @type {?Array<BufferAttribute>}
  20440. * @default null
  20441. */
  20442. this.attributes = null;
  20443. /**
  20444. * An object holding the version of the
  20445. * attributes. The keys are the attribute names
  20446. * and the values are the attribute versions.
  20447. *
  20448. * @type {?Object<string, number>}
  20449. * @default null
  20450. */
  20451. this.attributesId = null;
  20452. /**
  20453. * A reference to a render pipeline the render
  20454. * object is processed with.
  20455. *
  20456. * @type {RenderPipeline}
  20457. * @default null
  20458. */
  20459. this.pipeline = null;
  20460. /**
  20461. * Only relevant for objects using
  20462. * multiple materials. This represents a group entry
  20463. * from the respective `BufferGeometry`.
  20464. *
  20465. * @type {?{start: number, count: number}}
  20466. * @default null
  20467. */
  20468. this.group = null;
  20469. /**
  20470. * An array holding the vertex buffers which can
  20471. * be buffer attributes but also interleaved buffers.
  20472. *
  20473. * @type {?Array<BufferAttribute|InterleavedBuffer>}
  20474. * @default null
  20475. */
  20476. this.vertexBuffers = null;
  20477. /**
  20478. * The parameters for the draw command.
  20479. *
  20480. * @type {?Object}
  20481. * @default null
  20482. */
  20483. this.drawParams = null;
  20484. /**
  20485. * If this render object is used inside a render bundle,
  20486. * this property points to the respective bundle group.
  20487. *
  20488. * @type {?BundleGroup}
  20489. * @default null
  20490. */
  20491. this.bundle = null;
  20492. /**
  20493. * The clipping context.
  20494. *
  20495. * @type {ClippingContext}
  20496. */
  20497. this.clippingContext = clippingContext;
  20498. /**
  20499. * The clipping context's cache key.
  20500. *
  20501. * @type {string}
  20502. */
  20503. this.clippingContextCacheKey = clippingContext !== null ? clippingContext.cacheKey : '';
  20504. /**
  20505. * The initial node cache key.
  20506. *
  20507. * @type {number}
  20508. */
  20509. this.initialNodesCacheKey = this.getDynamicCacheKey();
  20510. /**
  20511. * The initial cache key.
  20512. *
  20513. * @type {number}
  20514. */
  20515. this.initialCacheKey = this.getCacheKey();
  20516. /**
  20517. * The node builder state.
  20518. *
  20519. * @type {?NodeBuilderState}
  20520. * @private
  20521. * @default null
  20522. */
  20523. this._nodeBuilderState = null;
  20524. /**
  20525. * An array of bindings.
  20526. *
  20527. * @type {?Array<BindGroup>}
  20528. * @private
  20529. * @default null
  20530. */
  20531. this._bindings = null;
  20532. /**
  20533. * Reference to the node material observer.
  20534. *
  20535. * @type {?NodeMaterialObserver}
  20536. * @private
  20537. * @default null
  20538. */
  20539. this._monitor = null;
  20540. /**
  20541. * An event listener which is defined by `RenderObjects`. It performs
  20542. * clean up tasks when `dispose()` on this render object.
  20543. *
  20544. * @method
  20545. */
  20546. this.onDispose = null;
  20547. /**
  20548. * This flag can be used for type testing.
  20549. *
  20550. * @type {boolean}
  20551. * @readonly
  20552. * @default true
  20553. */
  20554. this.isRenderObject = true;
  20555. /**
  20556. * An event listener which is executed when `dispose()` is called on
  20557. * the material of this render object.
  20558. *
  20559. * @method
  20560. */
  20561. this.onMaterialDispose = () => {
  20562. this.dispose();
  20563. };
  20564. /**
  20565. * An event listener which is executed when `dispose()` is called on
  20566. * the geometry of this render object.
  20567. *
  20568. * @method
  20569. */
  20570. this.onGeometryDispose = () => {
  20571. // clear geometry cache attributes
  20572. this.attributes = null;
  20573. this.attributesId = null;
  20574. };
  20575. this.material.addEventListener( 'dispose', this.onMaterialDispose );
  20576. this.geometry.addEventListener( 'dispose', this.onGeometryDispose );
  20577. }
  20578. /**
  20579. * Updates the clipping context.
  20580. *
  20581. * @param {ClippingContext} context - The clipping context to set.
  20582. */
  20583. updateClipping( context ) {
  20584. this.clippingContext = context;
  20585. }
  20586. /**
  20587. * Whether the clipping requires an update or not.
  20588. *
  20589. * @type {boolean}
  20590. * @readonly
  20591. */
  20592. get clippingNeedsUpdate() {
  20593. if ( this.clippingContext === null || this.clippingContext.cacheKey === this.clippingContextCacheKey ) return false;
  20594. this.clippingContextCacheKey = this.clippingContext.cacheKey;
  20595. return true;
  20596. }
  20597. /**
  20598. * The number of clipping planes defined in context of hardware clipping.
  20599. *
  20600. * @type {number}
  20601. * @readonly
  20602. */
  20603. get hardwareClippingPlanes() {
  20604. return this.material.hardwareClipping === true ? this.clippingContext.unionClippingCount : 0;
  20605. }
  20606. /**
  20607. * Returns the node builder state of this render object.
  20608. *
  20609. * @return {NodeBuilderState} The node builder state.
  20610. */
  20611. getNodeBuilderState() {
  20612. return this._nodeBuilderState || ( this._nodeBuilderState = this._nodes.getForRender( this ) );
  20613. }
  20614. /**
  20615. * Returns the node material observer of this render object.
  20616. *
  20617. * @return {NodeMaterialObserver} The node material observer.
  20618. */
  20619. getMonitor() {
  20620. return this._monitor || ( this._monitor = this.getNodeBuilderState().observer );
  20621. }
  20622. /**
  20623. * Returns an array of bind groups of this render object.
  20624. *
  20625. * @return {Array<BindGroup>} The bindings.
  20626. */
  20627. getBindings() {
  20628. return this._bindings || ( this._bindings = this.getNodeBuilderState().createBindings() );
  20629. }
  20630. /**
  20631. * Returns a binding group by group name of this render object.
  20632. *
  20633. * @param {string} name - The name of the binding group.
  20634. * @return {?BindGroup} The bindings.
  20635. */
  20636. getBindingGroup( name ) {
  20637. for ( const bindingGroup of this.getBindings() ) {
  20638. if ( bindingGroup.name === name ) {
  20639. return bindingGroup;
  20640. }
  20641. }
  20642. }
  20643. /**
  20644. * Returns the index of the render object's geometry.
  20645. *
  20646. * @return {?BufferAttribute} The index. Returns `null` for non-indexed geometries.
  20647. */
  20648. getIndex() {
  20649. return this._geometries.getIndex( this );
  20650. }
  20651. /**
  20652. * Returns the indirect buffer attribute.
  20653. *
  20654. * @return {?BufferAttribute} The indirect attribute. `null` if no indirect drawing is used.
  20655. */
  20656. getIndirect() {
  20657. return this._geometries.getIndirect( this );
  20658. }
  20659. /**
  20660. * Returns the byte offset into the indirect attribute buffer.
  20661. *
  20662. * @return {number|Array<number>} The byte offset into the indirect attribute buffer.
  20663. */
  20664. getIndirectOffset() {
  20665. return this._geometries.getIndirectOffset( this );
  20666. }
  20667. /**
  20668. * Returns an array that acts as a key for identifying the render object in a chain map.
  20669. *
  20670. * @return {Array<Object>} An array with object references.
  20671. */
  20672. getChainArray() {
  20673. return [ this.object, this.material, this.context, this.lightsNode ];
  20674. }
  20675. /**
  20676. * This method is used when the geometry of a 3D object has been exchanged and the
  20677. * respective render object now requires an update.
  20678. *
  20679. * @param {BufferGeometry} geometry - The geometry to set.
  20680. */
  20681. setGeometry( geometry ) {
  20682. this.geometry = geometry;
  20683. this.attributes = null;
  20684. this.attributesId = null;
  20685. }
  20686. /**
  20687. * Returns the buffer attributes of the render object. The returned array holds
  20688. * attribute definitions on geometry and node level.
  20689. *
  20690. * @return {Array<BufferAttribute>} An array with buffer attributes.
  20691. */
  20692. getAttributes() {
  20693. if ( this.attributes !== null ) return this.attributes;
  20694. const nodeAttributes = this.getNodeBuilderState().nodeAttributes;
  20695. const geometry = this.geometry;
  20696. const attributes = [];
  20697. const vertexBuffers = new Set();
  20698. const attributesId = {};
  20699. for ( const nodeAttribute of nodeAttributes ) {
  20700. let attribute;
  20701. if ( nodeAttribute.node && nodeAttribute.node.attribute ) {
  20702. // node attribute
  20703. attribute = nodeAttribute.node.attribute;
  20704. } else {
  20705. // geometry attribute
  20706. attribute = geometry.getAttribute( nodeAttribute.name );
  20707. attributesId[ nodeAttribute.name ] = attribute.version;
  20708. }
  20709. if ( attribute === undefined ) continue;
  20710. attributes.push( attribute );
  20711. const bufferAttribute = attribute.isInterleavedBufferAttribute ? attribute.data : attribute;
  20712. vertexBuffers.add( bufferAttribute );
  20713. }
  20714. this.attributes = attributes;
  20715. this.attributesId = attributesId;
  20716. this.vertexBuffers = Array.from( vertexBuffers.values() );
  20717. return attributes;
  20718. }
  20719. /**
  20720. * Returns the vertex buffers of the render object.
  20721. *
  20722. * @return {Array<BufferAttribute|InterleavedBuffer>} An array with buffer attribute or interleaved buffers.
  20723. */
  20724. getVertexBuffers() {
  20725. if ( this.vertexBuffers === null ) this.getAttributes();
  20726. return this.vertexBuffers;
  20727. }
  20728. /**
  20729. * Returns the draw parameters for the render object.
  20730. *
  20731. * @return {?{vertexCount: number, firstVertex: number, instanceCount: number, firstInstance: number}} The draw parameters.
  20732. */
  20733. getDrawParameters() {
  20734. const { object, material, geometry, group, drawRange } = this;
  20735. const drawParams = this.drawParams || ( this.drawParams = {
  20736. vertexCount: 0,
  20737. firstVertex: 0,
  20738. instanceCount: 0,
  20739. firstInstance: 0
  20740. } );
  20741. const index = this.getIndex();
  20742. const hasIndex = ( index !== null );
  20743. let instanceCount = 1;
  20744. if ( geometry.isInstancedBufferGeometry === true ) {
  20745. instanceCount = geometry.instanceCount;
  20746. } else if ( object.count !== undefined ) {
  20747. instanceCount = Math.max( 0, object.count );
  20748. }
  20749. if ( instanceCount === 0 ) return null;
  20750. drawParams.instanceCount = instanceCount;
  20751. if ( object.isBatchedMesh === true ) return drawParams;
  20752. let rangeFactor = 1;
  20753. if ( material.wireframe === true && ! object.isPoints && ! object.isLineSegments && ! object.isLine && ! object.isLineLoop ) {
  20754. rangeFactor = 2;
  20755. }
  20756. let firstVertex = drawRange.start * rangeFactor;
  20757. let lastVertex = ( drawRange.start + drawRange.count ) * rangeFactor;
  20758. if ( group !== null ) {
  20759. firstVertex = Math.max( firstVertex, group.start * rangeFactor );
  20760. lastVertex = Math.min( lastVertex, ( group.start + group.count ) * rangeFactor );
  20761. }
  20762. const position = geometry.attributes.position;
  20763. let itemCount = Infinity;
  20764. if ( hasIndex ) {
  20765. itemCount = index.count;
  20766. } else if ( position !== undefined && position !== null ) {
  20767. itemCount = position.count;
  20768. }
  20769. firstVertex = Math.max( firstVertex, 0 );
  20770. lastVertex = Math.min( lastVertex, itemCount );
  20771. const count = lastVertex - firstVertex;
  20772. if ( count < 0 || count === Infinity ) return null;
  20773. drawParams.vertexCount = count;
  20774. drawParams.firstVertex = firstVertex;
  20775. return drawParams;
  20776. }
  20777. /**
  20778. * Returns the render object's geometry cache key.
  20779. *
  20780. * The geometry cache key is part of the material cache key.
  20781. *
  20782. * @return {string} The geometry cache key.
  20783. */
  20784. getGeometryCacheKey() {
  20785. const { geometry } = this;
  20786. let cacheKey = '';
  20787. for ( const name of Object.keys( geometry.attributes ).sort() ) {
  20788. const attribute = geometry.attributes[ name ];
  20789. cacheKey += name + ',';
  20790. if ( attribute.data ) cacheKey += attribute.data.stride + ',';
  20791. if ( attribute.offset ) cacheKey += attribute.offset + ',';
  20792. if ( attribute.itemSize ) cacheKey += attribute.itemSize + ',';
  20793. if ( attribute.normalized ) cacheKey += 'n,';
  20794. }
  20795. // structural equality isn't sufficient for morph targets since the
  20796. // data are maintained in textures. only if the targets are all equal
  20797. // the texture and thus the instance of `MorphNode` can be shared.
  20798. for ( const name of Object.keys( geometry.morphAttributes ).sort() ) {
  20799. const targets = geometry.morphAttributes[ name ];
  20800. cacheKey += 'morph-' + name + ',';
  20801. for ( let i = 0, l = targets.length; i < l; i ++ ) {
  20802. const attribute = targets[ i ];
  20803. cacheKey += attribute.id + ',';
  20804. }
  20805. }
  20806. if ( geometry.index ) {
  20807. cacheKey += 'index,';
  20808. }
  20809. return cacheKey;
  20810. }
  20811. /**
  20812. * Returns the render object's material cache key.
  20813. *
  20814. * The material cache key is part of the render object cache key.
  20815. *
  20816. * @return {number} The material cache key.
  20817. */
  20818. getMaterialCacheKey() {
  20819. const { object, material, renderer } = this;
  20820. let cacheKey = material.customProgramCacheKey();
  20821. for ( const property of getKeys( material ) ) {
  20822. if ( /^(is[A-Z]|_)|^(visible|version|uuid|name|opacity|userData)$/.test( property ) ) continue;
  20823. const value = material[ property ];
  20824. let valueKey;
  20825. if ( value !== null ) {
  20826. // some material values require a formatting
  20827. const type = typeof value;
  20828. if ( type === 'number' ) {
  20829. valueKey = value !== 0 ? '1' : '0'; // Convert to on/off, important for clearcoat, transmission, etc
  20830. } else if ( type === 'object' ) {
  20831. valueKey = '{';
  20832. if ( value.isTexture ) {
  20833. valueKey += value.mapping;
  20834. // WebGPU must honor the sampler data because they are part of the bindings
  20835. if ( renderer.backend.isWebGPUBackend === true ) {
  20836. valueKey += value.magFilter;
  20837. valueKey += value.minFilter;
  20838. valueKey += value.wrapS;
  20839. valueKey += value.wrapT;
  20840. valueKey += value.wrapR;
  20841. }
  20842. }
  20843. valueKey += '}';
  20844. } else {
  20845. valueKey = String( value );
  20846. }
  20847. } else {
  20848. valueKey = String( value );
  20849. }
  20850. cacheKey += /*property + ':' +*/ valueKey + ',';
  20851. }
  20852. cacheKey += this.clippingContextCacheKey + ',';
  20853. if ( object.geometry ) {
  20854. cacheKey += this.getGeometryCacheKey();
  20855. }
  20856. if ( object.skeleton ) {
  20857. cacheKey += object.skeleton.bones.length + ',';
  20858. }
  20859. if ( object.isBatchedMesh ) {
  20860. cacheKey += object._matricesTexture.uuid + ',';
  20861. if ( object._colorsTexture !== null ) {
  20862. cacheKey += object._colorsTexture.uuid + ',';
  20863. }
  20864. }
  20865. if ( object.isInstancedMesh || object.count > 1 || Array.isArray( object.morphTargetInfluences ) ) {
  20866. // TODO: https://github.com/mrdoob/three.js/pull/29066#issuecomment-2269400850
  20867. cacheKey += object.uuid + ',';
  20868. }
  20869. cacheKey += this.context.id + ',';
  20870. cacheKey += object.receiveShadow + ',';
  20871. return hashString( cacheKey );
  20872. }
  20873. /**
  20874. * Whether the geometry requires an update or not.
  20875. *
  20876. * @type {boolean}
  20877. * @readonly
  20878. */
  20879. get needsGeometryUpdate() {
  20880. if ( this.geometry.id !== this.object.geometry.id ) return true;
  20881. if ( this.attributes !== null ) {
  20882. const attributesId = this.attributesId;
  20883. for ( const name in attributesId ) {
  20884. const attribute = this.geometry.getAttribute( name );
  20885. if ( attribute === undefined || attributesId[ name ] !== attribute.id ) {
  20886. return true;
  20887. }
  20888. }
  20889. }
  20890. return false;
  20891. }
  20892. /**
  20893. * Whether the render object requires an update or not.
  20894. *
  20895. * Note: There are two distinct places where render objects are checked for an update.
  20896. *
  20897. * 1. In `RenderObjects.get()` which is executed when the render object is request. This
  20898. * method checks the `needsUpdate` flag and recreates the render object if necessary.
  20899. * 2. In `Renderer._renderObjectDirect()` right after getting the render object via
  20900. * `RenderObjects.get()`. The render object's NodeMaterialObserver is then used to detect
  20901. * a need for a refresh due to material, geometry or object related value changes.
  20902. *
  20903. * TODO: Investigate if it's possible to merge both steps so there is only a single place
  20904. * that performs the 'needsUpdate' check.
  20905. *
  20906. * @type {boolean}
  20907. * @readonly
  20908. */
  20909. get needsUpdate() {
  20910. return /*this.object.static !== true &&*/ ( this.initialNodesCacheKey !== this.getDynamicCacheKey() || this.clippingNeedsUpdate );
  20911. }
  20912. /**
  20913. * Returns the dynamic cache key which represents a key that is computed per draw command.
  20914. *
  20915. * @return {number} The cache key.
  20916. */
  20917. getDynamicCacheKey() {
  20918. let cacheKey = 0;
  20919. // `Nodes.getCacheKey()` returns an environment cache key which is not relevant when
  20920. // the renderer is inside a shadow pass.
  20921. if ( this.material.isShadowPassMaterial !== true ) {
  20922. cacheKey = this._nodes.getCacheKey( this.scene, this.lightsNode );
  20923. }
  20924. if ( this.camera.isArrayCamera ) {
  20925. cacheKey = hash$1( cacheKey, this.camera.cameras.length );
  20926. }
  20927. if ( this.object.receiveShadow ) {
  20928. cacheKey = hash$1( cacheKey, 1 );
  20929. }
  20930. cacheKey = hash$1( cacheKey, this.camera.id, this.renderer.contextNode.id, this.renderer.contextNode.version );
  20931. return cacheKey;
  20932. }
  20933. /**
  20934. * Returns the render object's cache key.
  20935. *
  20936. * @return {number} The cache key.
  20937. */
  20938. getCacheKey() {
  20939. return this.getMaterialCacheKey() + this.getDynamicCacheKey();
  20940. }
  20941. /**
  20942. * Frees internal resources.
  20943. */
  20944. dispose() {
  20945. this.material.removeEventListener( 'dispose', this.onMaterialDispose );
  20946. this.geometry.removeEventListener( 'dispose', this.onGeometryDispose );
  20947. this.onDispose();
  20948. }
  20949. }
  20950. const _chainKeys$5 = [];
  20951. /**
  20952. * This module manages the render objects of the renderer.
  20953. *
  20954. * @private
  20955. */
  20956. class RenderObjects {
  20957. /**
  20958. * Constructs a new render object management component.
  20959. *
  20960. * @param {Renderer} renderer - The renderer.
  20961. * @param {Nodes} nodes - Renderer component for managing nodes related logic.
  20962. * @param {Geometries} geometries - Renderer component for managing geometries.
  20963. * @param {Pipelines} pipelines - Renderer component for managing pipelines.
  20964. * @param {Bindings} bindings - Renderer component for managing bindings.
  20965. * @param {Info} info - Renderer component for managing metrics and monitoring data.
  20966. */
  20967. constructor( renderer, nodes, geometries, pipelines, bindings, info ) {
  20968. /**
  20969. * The renderer.
  20970. *
  20971. * @type {Renderer}
  20972. */
  20973. this.renderer = renderer;
  20974. /**
  20975. * Renderer component for managing nodes related logic.
  20976. *
  20977. * @type {Nodes}
  20978. */
  20979. this.nodes = nodes;
  20980. /**
  20981. * Renderer component for managing geometries.
  20982. *
  20983. * @type {Geometries}
  20984. */
  20985. this.geometries = geometries;
  20986. /**
  20987. * Renderer component for managing pipelines.
  20988. *
  20989. * @type {Pipelines}
  20990. */
  20991. this.pipelines = pipelines;
  20992. /**
  20993. * Renderer component for managing bindings.
  20994. *
  20995. * @type {Bindings}
  20996. */
  20997. this.bindings = bindings;
  20998. /**
  20999. * Renderer component for managing metrics and monitoring data.
  21000. *
  21001. * @type {Info}
  21002. */
  21003. this.info = info;
  21004. /**
  21005. * A dictionary that manages render contexts in chain maps
  21006. * for each pass ID.
  21007. *
  21008. * @type {Object<string,ChainMap>}
  21009. */
  21010. this.chainMaps = {};
  21011. }
  21012. /**
  21013. * Returns a render object for the given object and state data.
  21014. *
  21015. * @param {Object3D} object - The 3D object.
  21016. * @param {Material} material - The 3D object's material.
  21017. * @param {Scene} scene - The scene the 3D object belongs to.
  21018. * @param {Camera} camera - The camera the 3D object should be rendered with.
  21019. * @param {LightsNode} lightsNode - The lights node.
  21020. * @param {RenderContext} renderContext - The render context.
  21021. * @param {ClippingContext} clippingContext - The clipping context.
  21022. * @param {string} [passId] - An optional ID for identifying the pass.
  21023. * @return {RenderObject} The render object.
  21024. */
  21025. get( object, material, scene, camera, lightsNode, renderContext, clippingContext, passId ) {
  21026. const chainMap = this.getChainMap( passId );
  21027. // reuse chainArray
  21028. _chainKeys$5[ 0 ] = object;
  21029. _chainKeys$5[ 1 ] = material;
  21030. _chainKeys$5[ 2 ] = renderContext;
  21031. _chainKeys$5[ 3 ] = lightsNode;
  21032. let renderObject = chainMap.get( _chainKeys$5 );
  21033. if ( renderObject === undefined ) {
  21034. renderObject = this.createRenderObject( this.nodes, this.geometries, this.renderer, object, material, scene, camera, lightsNode, renderContext, clippingContext, passId );
  21035. chainMap.set( _chainKeys$5, renderObject );
  21036. } else {
  21037. renderObject.updateClipping( clippingContext );
  21038. if ( renderObject.needsGeometryUpdate ) {
  21039. renderObject.setGeometry( object.geometry );
  21040. }
  21041. if ( renderObject.version !== material.version || renderObject.needsUpdate ) {
  21042. if ( renderObject.initialCacheKey !== renderObject.getCacheKey() ) {
  21043. renderObject.dispose();
  21044. renderObject = this.get( object, material, scene, camera, lightsNode, renderContext, clippingContext, passId );
  21045. } else {
  21046. renderObject.version = material.version;
  21047. }
  21048. }
  21049. }
  21050. _chainKeys$5.length = 0;
  21051. return renderObject;
  21052. }
  21053. /**
  21054. * Returns a chain map for the given pass ID.
  21055. *
  21056. * @param {string} [passId='default'] - The pass ID.
  21057. * @return {ChainMap} The chain map.
  21058. */
  21059. getChainMap( passId = 'default' ) {
  21060. return this.chainMaps[ passId ] || ( this.chainMaps[ passId ] = new ChainMap() );
  21061. }
  21062. /**
  21063. * Frees internal resources.
  21064. */
  21065. dispose() {
  21066. this.chainMaps = {};
  21067. }
  21068. /**
  21069. * Factory method for creating render objects with the given list of parameters.
  21070. *
  21071. * @param {Nodes} nodes - Renderer component for managing nodes related logic.
  21072. * @param {Geometries} geometries - Renderer component for managing geometries.
  21073. * @param {Renderer} renderer - The renderer.
  21074. * @param {Object3D} object - The 3D object.
  21075. * @param {Material} material - The object's material.
  21076. * @param {Scene} scene - The scene the 3D object belongs to.
  21077. * @param {Camera} camera - The camera the object should be rendered with.
  21078. * @param {LightsNode} lightsNode - The lights node.
  21079. * @param {RenderContext} renderContext - The render context.
  21080. * @param {ClippingContext} clippingContext - The clipping context.
  21081. * @param {string} [passId] - An optional ID for identifying the pass.
  21082. * @return {RenderObject} The render object.
  21083. */
  21084. createRenderObject( nodes, geometries, renderer, object, material, scene, camera, lightsNode, renderContext, clippingContext, passId ) {
  21085. const chainMap = this.getChainMap( passId );
  21086. const renderObject = new RenderObject( nodes, geometries, renderer, object, material, scene, camera, lightsNode, renderContext, clippingContext );
  21087. renderObject.onDispose = () => {
  21088. this.pipelines.delete( renderObject );
  21089. this.bindings.deleteForRender( renderObject );
  21090. this.nodes.delete( renderObject );
  21091. chainMap.delete( renderObject.getChainArray() );
  21092. };
  21093. return renderObject;
  21094. }
  21095. }
  21096. /**
  21097. * Data structure for the renderer. It is intended to manage
  21098. * data of objects in dictionaries.
  21099. *
  21100. * @private
  21101. */
  21102. class DataMap {
  21103. /**
  21104. * Constructs a new data map.
  21105. */
  21106. constructor() {
  21107. /**
  21108. * `DataMap` internally uses a weak map
  21109. * to manage its data.
  21110. *
  21111. * @type {WeakMap<Object, Object>}
  21112. */
  21113. this.data = new WeakMap();
  21114. }
  21115. /**
  21116. * Returns the dictionary for the given object.
  21117. *
  21118. * @param {Object} object - The object.
  21119. * @return {Object} The dictionary.
  21120. */
  21121. get( object ) {
  21122. let map = this.data.get( object );
  21123. if ( map === undefined ) {
  21124. map = {};
  21125. this.data.set( object, map );
  21126. }
  21127. return map;
  21128. }
  21129. /**
  21130. * Deletes the dictionary for the given object.
  21131. *
  21132. * @param {Object} object - The object.
  21133. * @return {?Object} The deleted dictionary.
  21134. */
  21135. delete( object ) {
  21136. let map = null;
  21137. if ( this.data.has( object ) ) {
  21138. map = this.data.get( object );
  21139. this.data.delete( object );
  21140. }
  21141. return map;
  21142. }
  21143. /**
  21144. * Returns `true` if the given object has a dictionary defined.
  21145. *
  21146. * @param {Object} object - The object to test.
  21147. * @return {boolean} Whether a dictionary is defined or not.
  21148. */
  21149. has( object ) {
  21150. return this.data.has( object );
  21151. }
  21152. /**
  21153. * Frees internal resources.
  21154. */
  21155. dispose() {
  21156. this.data = new WeakMap();
  21157. }
  21158. }
  21159. const AttributeType = {
  21160. VERTEX: 1,
  21161. INDEX: 2,
  21162. STORAGE: 3,
  21163. INDIRECT: 4
  21164. };
  21165. // size of a chunk in bytes (STD140 layout)
  21166. const GPU_CHUNK_BYTES = 16;
  21167. // @TODO: Move to src/constants.js
  21168. const BlendColorFactor = 211;
  21169. const OneMinusBlendColorFactor = 212;
  21170. /**
  21171. * This renderer module manages geometry attributes.
  21172. *
  21173. * @private
  21174. * @augments DataMap
  21175. */
  21176. class Attributes extends DataMap {
  21177. /**
  21178. * Constructs a new attribute management component.
  21179. *
  21180. * @param {Backend} backend - The renderer's backend.
  21181. */
  21182. constructor( backend ) {
  21183. super();
  21184. /**
  21185. * The renderer's backend.
  21186. *
  21187. * @type {Backend}
  21188. */
  21189. this.backend = backend;
  21190. }
  21191. /**
  21192. * Deletes the data for the given attribute.
  21193. *
  21194. * @param {BufferAttribute} attribute - The attribute.
  21195. * @return {?Object} The deleted attribute data.
  21196. */
  21197. delete( attribute ) {
  21198. const attributeData = super.delete( attribute );
  21199. if ( attributeData !== null ) {
  21200. this.backend.destroyAttribute( attribute );
  21201. }
  21202. return attributeData;
  21203. }
  21204. /**
  21205. * Updates the given attribute. This method creates attribute buffers
  21206. * for new attributes and updates data for existing ones.
  21207. *
  21208. * @param {BufferAttribute} attribute - The attribute to update.
  21209. * @param {number} type - The attribute type.
  21210. */
  21211. update( attribute, type ) {
  21212. const data = this.get( attribute );
  21213. if ( data.version === undefined ) {
  21214. if ( type === AttributeType.VERTEX ) {
  21215. this.backend.createAttribute( attribute );
  21216. } else if ( type === AttributeType.INDEX ) {
  21217. this.backend.createIndexAttribute( attribute );
  21218. } else if ( type === AttributeType.STORAGE ) {
  21219. this.backend.createStorageAttribute( attribute );
  21220. } else if ( type === AttributeType.INDIRECT ) {
  21221. this.backend.createIndirectStorageAttribute( attribute );
  21222. }
  21223. data.version = this._getBufferAttribute( attribute ).version;
  21224. } else {
  21225. const bufferAttribute = this._getBufferAttribute( attribute );
  21226. if ( data.version < bufferAttribute.version || bufferAttribute.usage === DynamicDrawUsage ) {
  21227. this.backend.updateAttribute( attribute );
  21228. data.version = bufferAttribute.version;
  21229. }
  21230. }
  21231. }
  21232. /**
  21233. * Utility method for handling interleaved buffer attributes correctly.
  21234. * To process them, their `InterleavedBuffer` is returned.
  21235. *
  21236. * @param {BufferAttribute} attribute - The attribute.
  21237. * @return {BufferAttribute|InterleavedBuffer}
  21238. */
  21239. _getBufferAttribute( attribute ) {
  21240. if ( attribute.isInterleavedBufferAttribute ) attribute = attribute.data;
  21241. return attribute;
  21242. }
  21243. }
  21244. /**
  21245. * Returns the wireframe version for the given geometry.
  21246. *
  21247. * @private
  21248. * @function
  21249. * @param {BufferGeometry} geometry - The geometry.
  21250. * @return {number} The version.
  21251. */
  21252. function getWireframeVersion( geometry ) {
  21253. return ( geometry.index !== null ) ? geometry.index.version : geometry.attributes.position.version;
  21254. }
  21255. /**
  21256. * Returns a wireframe index attribute for the given geometry.
  21257. *
  21258. * @private
  21259. * @function
  21260. * @param {BufferGeometry} geometry - The geometry.
  21261. * @return {BufferAttribute} The wireframe index attribute.
  21262. */
  21263. function getWireframeIndex( geometry ) {
  21264. const indices = [];
  21265. const geometryIndex = geometry.index;
  21266. const geometryPosition = geometry.attributes.position;
  21267. if ( geometryIndex !== null ) {
  21268. const array = geometryIndex.array;
  21269. for ( let i = 0, l = array.length; i < l; i += 3 ) {
  21270. const a = array[ i + 0 ];
  21271. const b = array[ i + 1 ];
  21272. const c = array[ i + 2 ];
  21273. indices.push( a, b, b, c, c, a );
  21274. }
  21275. } else {
  21276. const array = geometryPosition.array;
  21277. for ( let i = 0, l = ( array.length / 3 ) - 1; i < l; i += 3 ) {
  21278. const a = i + 0;
  21279. const b = i + 1;
  21280. const c = i + 2;
  21281. indices.push( a, b, b, c, c, a );
  21282. }
  21283. }
  21284. const attribute = new ( arrayNeedsUint32( indices ) ? Uint32BufferAttribute : Uint16BufferAttribute )( indices, 1 );
  21285. attribute.version = getWireframeVersion( geometry );
  21286. return attribute;
  21287. }
  21288. /**
  21289. * This renderer module manages geometries.
  21290. *
  21291. * @private
  21292. * @augments DataMap
  21293. */
  21294. class Geometries extends DataMap {
  21295. /**
  21296. * Constructs a new geometry management component.
  21297. *
  21298. * @param {Attributes} attributes - Renderer component for managing attributes.
  21299. * @param {Info} info - Renderer component for managing metrics and monitoring data.
  21300. */
  21301. constructor( attributes, info ) {
  21302. super();
  21303. /**
  21304. * Renderer component for managing attributes.
  21305. *
  21306. * @type {Attributes}
  21307. */
  21308. this.attributes = attributes;
  21309. /**
  21310. * Renderer component for managing metrics and monitoring data.
  21311. *
  21312. * @type {Info}
  21313. */
  21314. this.info = info;
  21315. /**
  21316. * Weak Map for managing attributes for wireframe rendering.
  21317. *
  21318. * @type {WeakMap<BufferGeometry,BufferAttribute>}
  21319. */
  21320. this.wireframes = new WeakMap();
  21321. /**
  21322. * This Weak Map is used to make sure buffer attributes are
  21323. * updated only once per render call.
  21324. *
  21325. * @type {WeakMap<BufferAttribute,number>}
  21326. */
  21327. this.attributeCall = new WeakMap();
  21328. /**
  21329. * Stores the event listeners attached to geometries.
  21330. *
  21331. * @private
  21332. * @type {Map<BufferGeometry,Function>}
  21333. */
  21334. this._geometryDisposeListeners = new Map();
  21335. }
  21336. /**
  21337. * Returns `true` if the given render object has an initialized geometry.
  21338. *
  21339. * @param {RenderObject} renderObject - The render object.
  21340. * @return {boolean} Whether if the given render object has an initialized geometry or not.
  21341. */
  21342. has( renderObject ) {
  21343. const geometry = renderObject.geometry;
  21344. return super.has( geometry ) && this.get( geometry ).initialized === true;
  21345. }
  21346. /**
  21347. * Prepares the geometry of the given render object for rendering.
  21348. *
  21349. * @param {RenderObject} renderObject - The render object.
  21350. */
  21351. updateForRender( renderObject ) {
  21352. if ( this.has( renderObject ) === false ) this.initGeometry( renderObject );
  21353. this.updateAttributes( renderObject );
  21354. }
  21355. /**
  21356. * Initializes the geometry of the given render object.
  21357. *
  21358. * @param {RenderObject} renderObject - The render object.
  21359. */
  21360. initGeometry( renderObject ) {
  21361. const geometry = renderObject.geometry;
  21362. const geometryData = this.get( geometry );
  21363. geometryData.initialized = true;
  21364. this.info.memory.geometries ++;
  21365. const onDispose = () => {
  21366. this.info.memory.geometries --;
  21367. const index = geometry.index;
  21368. const geometryAttributes = renderObject.getAttributes();
  21369. if ( index !== null ) {
  21370. this.attributes.delete( index );
  21371. }
  21372. for ( const geometryAttribute of geometryAttributes ) {
  21373. this.attributes.delete( geometryAttribute );
  21374. }
  21375. const wireframeAttribute = this.wireframes.get( geometry );
  21376. if ( wireframeAttribute !== undefined ) {
  21377. this.attributes.delete( wireframeAttribute );
  21378. }
  21379. geometry.removeEventListener( 'dispose', onDispose );
  21380. this._geometryDisposeListeners.delete( geometry );
  21381. };
  21382. geometry.addEventListener( 'dispose', onDispose );
  21383. // see #31798 why tracking separate remove listeners is required right now
  21384. // TODO: Re-evaluate how onDispose() is managed in this component
  21385. this._geometryDisposeListeners.set( geometry, onDispose );
  21386. }
  21387. /**
  21388. * Updates the geometry attributes of the given render object.
  21389. *
  21390. * @param {RenderObject} renderObject - The render object.
  21391. */
  21392. updateAttributes( renderObject ) {
  21393. // attributes
  21394. const attributes = renderObject.getAttributes();
  21395. for ( const attribute of attributes ) {
  21396. if ( attribute.isStorageBufferAttribute || attribute.isStorageInstancedBufferAttribute ) {
  21397. this.updateAttribute( attribute, AttributeType.STORAGE );
  21398. } else {
  21399. this.updateAttribute( attribute, AttributeType.VERTEX );
  21400. }
  21401. }
  21402. // indexes
  21403. const index = this.getIndex( renderObject );
  21404. if ( index !== null ) {
  21405. this.updateAttribute( index, AttributeType.INDEX );
  21406. }
  21407. // indirect
  21408. const indirect = renderObject.geometry.indirect;
  21409. if ( indirect !== null ) {
  21410. this.updateAttribute( indirect, AttributeType.INDIRECT );
  21411. }
  21412. }
  21413. /**
  21414. * Updates the given attribute.
  21415. *
  21416. * @param {BufferAttribute} attribute - The attribute to update.
  21417. * @param {number} type - The attribute type.
  21418. */
  21419. updateAttribute( attribute, type ) {
  21420. const callId = this.info.render.calls;
  21421. if ( ! attribute.isInterleavedBufferAttribute ) {
  21422. if ( this.attributeCall.get( attribute ) !== callId ) {
  21423. this.attributes.update( attribute, type );
  21424. this.attributeCall.set( attribute, callId );
  21425. }
  21426. } else {
  21427. if ( this.attributeCall.get( attribute ) === undefined ) {
  21428. this.attributes.update( attribute, type );
  21429. this.attributeCall.set( attribute, callId );
  21430. } else if ( this.attributeCall.get( attribute.data ) !== callId ) {
  21431. this.attributes.update( attribute, type );
  21432. this.attributeCall.set( attribute.data, callId );
  21433. this.attributeCall.set( attribute, callId );
  21434. }
  21435. }
  21436. }
  21437. /**
  21438. * Returns the indirect buffer attribute of the given render object.
  21439. *
  21440. * @param {RenderObject} renderObject - The render object.
  21441. * @return {?BufferAttribute} The indirect attribute. `null` if no indirect drawing is used.
  21442. */
  21443. getIndirect( renderObject ) {
  21444. return renderObject.geometry.indirect;
  21445. }
  21446. /**
  21447. * Returns the byte offset into the indirect attribute buffer of the given render object.
  21448. *
  21449. * @param {RenderObject} renderObject - The render object.
  21450. * @return {number} The byte offset into the indirect attribute buffer.
  21451. */
  21452. getIndirectOffset( renderObject ) {
  21453. return renderObject.geometry.indirectOffset;
  21454. }
  21455. /**
  21456. * Returns the index of the given render object's geometry. This is implemented
  21457. * in a method to return a wireframe index if necessary.
  21458. *
  21459. * @param {RenderObject} renderObject - The render object.
  21460. * @return {?BufferAttribute} The index. Returns `null` for non-indexed geometries.
  21461. */
  21462. getIndex( renderObject ) {
  21463. const { geometry, material } = renderObject;
  21464. let index = geometry.index;
  21465. if ( material.wireframe === true ) {
  21466. const wireframes = this.wireframes;
  21467. let wireframeAttribute = wireframes.get( geometry );
  21468. if ( wireframeAttribute === undefined ) {
  21469. wireframeAttribute = getWireframeIndex( geometry );
  21470. wireframes.set( geometry, wireframeAttribute );
  21471. } else if ( wireframeAttribute.version !== getWireframeVersion( geometry ) ) {
  21472. this.attributes.delete( wireframeAttribute );
  21473. wireframeAttribute = getWireframeIndex( geometry );
  21474. wireframes.set( geometry, wireframeAttribute );
  21475. }
  21476. index = wireframeAttribute;
  21477. }
  21478. return index;
  21479. }
  21480. dispose() {
  21481. for ( const [ geometry, onDispose ] of this._geometryDisposeListeners.entries() ) {
  21482. geometry.removeEventListener( 'dispose', onDispose );
  21483. }
  21484. this._geometryDisposeListeners.clear();
  21485. }
  21486. }
  21487. /**
  21488. * This renderer module provides a series of statistical information
  21489. * about the GPU memory and the rendering process. Useful for debugging
  21490. * and monitoring.
  21491. */
  21492. class Info {
  21493. /**
  21494. * Constructs a new info component.
  21495. */
  21496. constructor() {
  21497. /**
  21498. * Whether frame related metrics should automatically
  21499. * be resetted or not. This property should be set to `false`
  21500. * by apps which manage their own animation loop. They must
  21501. * then call `renderer.info.reset()` once per frame manually.
  21502. *
  21503. * @type {boolean}
  21504. * @default true
  21505. */
  21506. this.autoReset = true;
  21507. /**
  21508. * The current frame ID. This ID is managed
  21509. * by `NodeFrame`.
  21510. *
  21511. * @type {number}
  21512. * @readonly
  21513. * @default 0
  21514. */
  21515. this.frame = 0;
  21516. /**
  21517. * The number of render calls since the
  21518. * app has been started.
  21519. *
  21520. * @type {number}
  21521. * @readonly
  21522. * @default 0
  21523. */
  21524. this.calls = 0;
  21525. /**
  21526. * Render related metrics.
  21527. *
  21528. * @type {Object}
  21529. * @readonly
  21530. * @property {number} calls - The number of render calls since the app has been started.
  21531. * @property {number} frameCalls - The number of render calls of the current frame.
  21532. * @property {number} drawCalls - The number of draw calls of the current frame.
  21533. * @property {number} triangles - The number of rendered triangle primitives of the current frame.
  21534. * @property {number} points - The number of rendered point primitives of the current frame.
  21535. * @property {number} lines - The number of rendered line primitives of the current frame.
  21536. * @property {number} timestamp - The timestamp of the frame.
  21537. */
  21538. this.render = {
  21539. calls: 0,
  21540. frameCalls: 0,
  21541. drawCalls: 0,
  21542. triangles: 0,
  21543. points: 0,
  21544. lines: 0,
  21545. timestamp: 0,
  21546. };
  21547. /**
  21548. * Compute related metrics.
  21549. *
  21550. * @type {Object}
  21551. * @readonly
  21552. * @property {number} calls - The number of compute calls since the app has been started.
  21553. * @property {number} frameCalls - The number of compute calls of the current frame.
  21554. * @property {number} timestamp - The timestamp of the frame when using `renderer.computeAsync()`.
  21555. */
  21556. this.compute = {
  21557. calls: 0,
  21558. frameCalls: 0,
  21559. timestamp: 0
  21560. };
  21561. /**
  21562. * Memory related metrics.
  21563. *
  21564. * @type {Object}
  21565. * @readonly
  21566. * @property {number} geometries - The number of active geometries.
  21567. * @property {number} frameCalls - The number of active textures.
  21568. */
  21569. this.memory = {
  21570. geometries: 0,
  21571. textures: 0
  21572. };
  21573. }
  21574. /**
  21575. * This method should be executed per draw call and updates the corresponding metrics.
  21576. *
  21577. * @param {Object3D} object - The 3D object that is going to be rendered.
  21578. * @param {number} count - The vertex or index count.
  21579. * @param {number} instanceCount - The instance count.
  21580. */
  21581. update( object, count, instanceCount ) {
  21582. this.render.drawCalls ++;
  21583. if ( object.isMesh || object.isSprite ) {
  21584. this.render.triangles += instanceCount * ( count / 3 );
  21585. } else if ( object.isPoints ) {
  21586. this.render.points += instanceCount * count;
  21587. } else if ( object.isLineSegments ) {
  21588. this.render.lines += instanceCount * ( count / 2 );
  21589. } else if ( object.isLine ) {
  21590. this.render.lines += instanceCount * ( count - 1 );
  21591. } else {
  21592. error( 'WebGPUInfo: Unknown object type.' );
  21593. }
  21594. }
  21595. /**
  21596. * Resets frame related metrics.
  21597. */
  21598. reset() {
  21599. this.render.drawCalls = 0;
  21600. this.render.frameCalls = 0;
  21601. this.compute.frameCalls = 0;
  21602. this.render.triangles = 0;
  21603. this.render.points = 0;
  21604. this.render.lines = 0;
  21605. }
  21606. /**
  21607. * Performs a complete reset of the object.
  21608. */
  21609. dispose() {
  21610. this.reset();
  21611. this.calls = 0;
  21612. this.render.calls = 0;
  21613. this.compute.calls = 0;
  21614. this.render.timestamp = 0;
  21615. this.compute.timestamp = 0;
  21616. this.memory.geometries = 0;
  21617. this.memory.textures = 0;
  21618. }
  21619. }
  21620. /**
  21621. * Abstract class for representing pipelines.
  21622. *
  21623. * @private
  21624. * @abstract
  21625. */
  21626. class Pipeline {
  21627. /**
  21628. * Constructs a new pipeline.
  21629. *
  21630. * @param {string} cacheKey - The pipeline's cache key.
  21631. */
  21632. constructor( cacheKey ) {
  21633. /**
  21634. * The pipeline's cache key.
  21635. *
  21636. * @type {string}
  21637. */
  21638. this.cacheKey = cacheKey;
  21639. /**
  21640. * How often the pipeline is currently in use.
  21641. *
  21642. * @type {number}
  21643. * @default 0
  21644. */
  21645. this.usedTimes = 0;
  21646. }
  21647. }
  21648. /**
  21649. * Class for representing render pipelines.
  21650. *
  21651. * @private
  21652. * @augments Pipeline
  21653. */
  21654. class RenderPipeline extends Pipeline {
  21655. /**
  21656. * Constructs a new render pipeline.
  21657. *
  21658. * @param {string} cacheKey - The pipeline's cache key.
  21659. * @param {ProgrammableStage} vertexProgram - The pipeline's vertex shader.
  21660. * @param {ProgrammableStage} fragmentProgram - The pipeline's fragment shader.
  21661. */
  21662. constructor( cacheKey, vertexProgram, fragmentProgram ) {
  21663. super( cacheKey );
  21664. /**
  21665. * The pipeline's vertex shader.
  21666. *
  21667. * @type {ProgrammableStage}
  21668. */
  21669. this.vertexProgram = vertexProgram;
  21670. /**
  21671. * The pipeline's fragment shader.
  21672. *
  21673. * @type {ProgrammableStage}
  21674. */
  21675. this.fragmentProgram = fragmentProgram;
  21676. }
  21677. }
  21678. /**
  21679. * Class for representing compute pipelines.
  21680. *
  21681. * @private
  21682. * @augments Pipeline
  21683. */
  21684. class ComputePipeline extends Pipeline {
  21685. /**
  21686. * Constructs a new render pipeline.
  21687. *
  21688. * @param {string} cacheKey - The pipeline's cache key.
  21689. * @param {ProgrammableStage} computeProgram - The pipeline's compute shader.
  21690. */
  21691. constructor( cacheKey, computeProgram ) {
  21692. super( cacheKey );
  21693. /**
  21694. * The pipeline's compute shader.
  21695. *
  21696. * @type {ProgrammableStage}
  21697. */
  21698. this.computeProgram = computeProgram;
  21699. /**
  21700. * This flag can be used for type testing.
  21701. *
  21702. * @type {boolean}
  21703. * @readonly
  21704. * @default true
  21705. */
  21706. this.isComputePipeline = true;
  21707. }
  21708. }
  21709. let _id$9 = 0;
  21710. /**
  21711. * Class for representing programmable stages which are vertex,
  21712. * fragment or compute shaders. Unlike fixed-function states (like blending),
  21713. * they represent the programmable part of a pipeline.
  21714. *
  21715. * @private
  21716. */
  21717. class ProgrammableStage {
  21718. /**
  21719. * Constructs a new programmable stage.
  21720. *
  21721. * @param {string} code - The shader code.
  21722. * @param {('vertex'|'fragment'|'compute')} stage - The type of stage.
  21723. * @param {string} name - The name of the shader.
  21724. * @param {?Array<Object>} [transforms=null] - The transforms (only relevant for compute stages with WebGL 2 which uses Transform Feedback).
  21725. * @param {?Array<Object>} [attributes=null] - The attributes (only relevant for compute stages with WebGL 2 which uses Transform Feedback).
  21726. */
  21727. constructor( code, stage, name, transforms = null, attributes = null ) {
  21728. /**
  21729. * The id of the programmable stage.
  21730. *
  21731. * @type {number}
  21732. */
  21733. this.id = _id$9 ++;
  21734. /**
  21735. * The shader code.
  21736. *
  21737. * @type {string}
  21738. */
  21739. this.code = code;
  21740. /**
  21741. * The type of stage.
  21742. *
  21743. * @type {string}
  21744. */
  21745. this.stage = stage;
  21746. /**
  21747. * The name of the stage.
  21748. * This is used for debugging purposes.
  21749. *
  21750. * @type {string}
  21751. */
  21752. this.name = name;
  21753. /**
  21754. * The transforms (only relevant for compute stages with WebGL 2 which uses Transform Feedback).
  21755. *
  21756. * @type {?Array<Object>}
  21757. */
  21758. this.transforms = transforms;
  21759. /**
  21760. * The attributes (only relevant for compute stages with WebGL 2 which uses Transform Feedback).
  21761. *
  21762. * @type {?Array<Object>}
  21763. */
  21764. this.attributes = attributes;
  21765. /**
  21766. * How often the programmable stage is currently in use.
  21767. *
  21768. * @type {number}
  21769. * @default 0
  21770. */
  21771. this.usedTimes = 0;
  21772. }
  21773. }
  21774. /**
  21775. * This renderer module manages the pipelines of the renderer.
  21776. *
  21777. * @private
  21778. * @augments DataMap
  21779. */
  21780. class Pipelines extends DataMap {
  21781. /**
  21782. * Constructs a new pipeline management component.
  21783. *
  21784. * @param {Backend} backend - The renderer's backend.
  21785. * @param {Nodes} nodes - Renderer component for managing nodes related logic.
  21786. */
  21787. constructor( backend, nodes ) {
  21788. super();
  21789. /**
  21790. * The renderer's backend.
  21791. *
  21792. * @type {Backend}
  21793. */
  21794. this.backend = backend;
  21795. /**
  21796. * Renderer component for managing nodes related logic.
  21797. *
  21798. * @type {Nodes}
  21799. */
  21800. this.nodes = nodes;
  21801. /**
  21802. * A references to the bindings management component.
  21803. * This reference will be set inside the `Bindings`
  21804. * constructor.
  21805. *
  21806. * @type {?Bindings}
  21807. * @default null
  21808. */
  21809. this.bindings = null;
  21810. /**
  21811. * Internal cache for maintaining pipelines.
  21812. * The key of the map is a cache key, the value the pipeline.
  21813. *
  21814. * @type {Map<string,Pipeline>}
  21815. */
  21816. this.caches = new Map();
  21817. /**
  21818. * This dictionary maintains for each shader stage type (vertex,
  21819. * fragment and compute) the programmable stage objects which
  21820. * represent the actual shader code.
  21821. *
  21822. * @type {Object<string,Map<string, ProgrammableStage>>}
  21823. */
  21824. this.programs = {
  21825. vertex: new Map(),
  21826. fragment: new Map(),
  21827. compute: new Map()
  21828. };
  21829. }
  21830. /**
  21831. * Returns a compute pipeline for the given compute node.
  21832. *
  21833. * @param {Node} computeNode - The compute node.
  21834. * @param {Array<BindGroup>} bindings - The bindings.
  21835. * @return {ComputePipeline} The compute pipeline.
  21836. */
  21837. getForCompute( computeNode, bindings ) {
  21838. const { backend } = this;
  21839. const data = this.get( computeNode );
  21840. if ( this._needsComputeUpdate( computeNode ) ) {
  21841. const previousPipeline = data.pipeline;
  21842. if ( previousPipeline ) {
  21843. previousPipeline.usedTimes --;
  21844. previousPipeline.computeProgram.usedTimes --;
  21845. }
  21846. // get shader
  21847. const nodeBuilderState = this.nodes.getForCompute( computeNode );
  21848. // programmable stage
  21849. let stageCompute = this.programs.compute.get( nodeBuilderState.computeShader );
  21850. if ( stageCompute === undefined ) {
  21851. if ( previousPipeline && previousPipeline.computeProgram.usedTimes === 0 ) this._releaseProgram( previousPipeline.computeProgram );
  21852. stageCompute = new ProgrammableStage( nodeBuilderState.computeShader, 'compute', computeNode.name, nodeBuilderState.transforms, nodeBuilderState.nodeAttributes );
  21853. this.programs.compute.set( nodeBuilderState.computeShader, stageCompute );
  21854. backend.createProgram( stageCompute );
  21855. }
  21856. // determine compute pipeline
  21857. const cacheKey = this._getComputeCacheKey( computeNode, stageCompute );
  21858. let pipeline = this.caches.get( cacheKey );
  21859. if ( pipeline === undefined ) {
  21860. if ( previousPipeline && previousPipeline.usedTimes === 0 ) this._releasePipeline( previousPipeline );
  21861. pipeline = this._getComputePipeline( computeNode, stageCompute, cacheKey, bindings );
  21862. }
  21863. // keep track of all used times
  21864. pipeline.usedTimes ++;
  21865. stageCompute.usedTimes ++;
  21866. //
  21867. data.version = computeNode.version;
  21868. data.pipeline = pipeline;
  21869. }
  21870. return data.pipeline;
  21871. }
  21872. /**
  21873. * Returns a render pipeline for the given render object.
  21874. *
  21875. * @param {RenderObject} renderObject - The render object.
  21876. * @param {?Array<Promise>} [promises=null] - An array of compilation promises which is only relevant in context of `Renderer.compileAsync()`.
  21877. * @return {RenderPipeline} The render pipeline.
  21878. */
  21879. getForRender( renderObject, promises = null ) {
  21880. const { backend } = this;
  21881. const data = this.get( renderObject );
  21882. if ( this._needsRenderUpdate( renderObject ) ) {
  21883. const previousPipeline = data.pipeline;
  21884. if ( previousPipeline ) {
  21885. previousPipeline.usedTimes --;
  21886. previousPipeline.vertexProgram.usedTimes --;
  21887. previousPipeline.fragmentProgram.usedTimes --;
  21888. }
  21889. // get shader
  21890. const nodeBuilderState = renderObject.getNodeBuilderState();
  21891. const name = renderObject.material ? renderObject.material.name : '';
  21892. // programmable stages
  21893. let stageVertex = this.programs.vertex.get( nodeBuilderState.vertexShader );
  21894. if ( stageVertex === undefined ) {
  21895. if ( previousPipeline && previousPipeline.vertexProgram.usedTimes === 0 ) this._releaseProgram( previousPipeline.vertexProgram );
  21896. stageVertex = new ProgrammableStage( nodeBuilderState.vertexShader, 'vertex', name );
  21897. this.programs.vertex.set( nodeBuilderState.vertexShader, stageVertex );
  21898. backend.createProgram( stageVertex );
  21899. }
  21900. let stageFragment = this.programs.fragment.get( nodeBuilderState.fragmentShader );
  21901. if ( stageFragment === undefined ) {
  21902. if ( previousPipeline && previousPipeline.fragmentProgram.usedTimes === 0 ) this._releaseProgram( previousPipeline.fragmentProgram );
  21903. stageFragment = new ProgrammableStage( nodeBuilderState.fragmentShader, 'fragment', name );
  21904. this.programs.fragment.set( nodeBuilderState.fragmentShader, stageFragment );
  21905. backend.createProgram( stageFragment );
  21906. }
  21907. // determine render pipeline
  21908. const cacheKey = this._getRenderCacheKey( renderObject, stageVertex, stageFragment );
  21909. let pipeline = this.caches.get( cacheKey );
  21910. if ( pipeline === undefined ) {
  21911. if ( previousPipeline && previousPipeline.usedTimes === 0 ) this._releasePipeline( previousPipeline );
  21912. pipeline = this._getRenderPipeline( renderObject, stageVertex, stageFragment, cacheKey, promises );
  21913. } else {
  21914. renderObject.pipeline = pipeline;
  21915. }
  21916. // keep track of all used times
  21917. pipeline.usedTimes ++;
  21918. stageVertex.usedTimes ++;
  21919. stageFragment.usedTimes ++;
  21920. //
  21921. data.pipeline = pipeline;
  21922. }
  21923. return data.pipeline;
  21924. }
  21925. /**
  21926. * Deletes the pipeline for the given render object.
  21927. *
  21928. * @param {RenderObject} object - The render object.
  21929. * @return {?Object} The deleted dictionary.
  21930. */
  21931. delete( object ) {
  21932. const pipeline = this.get( object ).pipeline;
  21933. if ( pipeline ) {
  21934. // pipeline
  21935. pipeline.usedTimes --;
  21936. if ( pipeline.usedTimes === 0 ) this._releasePipeline( pipeline );
  21937. // programs
  21938. if ( pipeline.isComputePipeline ) {
  21939. pipeline.computeProgram.usedTimes --;
  21940. if ( pipeline.computeProgram.usedTimes === 0 ) this._releaseProgram( pipeline.computeProgram );
  21941. } else {
  21942. pipeline.fragmentProgram.usedTimes --;
  21943. pipeline.vertexProgram.usedTimes --;
  21944. if ( pipeline.vertexProgram.usedTimes === 0 ) this._releaseProgram( pipeline.vertexProgram );
  21945. if ( pipeline.fragmentProgram.usedTimes === 0 ) this._releaseProgram( pipeline.fragmentProgram );
  21946. }
  21947. }
  21948. return super.delete( object );
  21949. }
  21950. /**
  21951. * Frees internal resources.
  21952. */
  21953. dispose() {
  21954. super.dispose();
  21955. this.caches = new Map();
  21956. this.programs = {
  21957. vertex: new Map(),
  21958. fragment: new Map(),
  21959. compute: new Map()
  21960. };
  21961. }
  21962. /**
  21963. * Updates the pipeline for the given render object.
  21964. *
  21965. * @param {RenderObject} renderObject - The render object.
  21966. */
  21967. updateForRender( renderObject ) {
  21968. this.getForRender( renderObject );
  21969. }
  21970. /**
  21971. * Returns a compute pipeline for the given parameters.
  21972. *
  21973. * @private
  21974. * @param {Node} computeNode - The compute node.
  21975. * @param {ProgrammableStage} stageCompute - The programmable stage representing the compute shader.
  21976. * @param {string} cacheKey - The cache key.
  21977. * @param {Array<BindGroup>} bindings - The bindings.
  21978. * @return {ComputePipeline} The compute pipeline.
  21979. */
  21980. _getComputePipeline( computeNode, stageCompute, cacheKey, bindings ) {
  21981. // check for existing pipeline
  21982. cacheKey = cacheKey || this._getComputeCacheKey( computeNode, stageCompute );
  21983. let pipeline = this.caches.get( cacheKey );
  21984. if ( pipeline === undefined ) {
  21985. pipeline = new ComputePipeline( cacheKey, stageCompute );
  21986. this.caches.set( cacheKey, pipeline );
  21987. this.backend.createComputePipeline( pipeline, bindings );
  21988. }
  21989. return pipeline;
  21990. }
  21991. /**
  21992. * Returns a render pipeline for the given parameters.
  21993. *
  21994. * @private
  21995. * @param {RenderObject} renderObject - The render object.
  21996. * @param {ProgrammableStage} stageVertex - The programmable stage representing the vertex shader.
  21997. * @param {ProgrammableStage} stageFragment - The programmable stage representing the fragment shader.
  21998. * @param {string} cacheKey - The cache key.
  21999. * @param {?Array<Promise>} promises - An array of compilation promises which is only relevant in context of `Renderer.compileAsync()`.
  22000. * @return {ComputePipeline} The compute pipeline.
  22001. */
  22002. _getRenderPipeline( renderObject, stageVertex, stageFragment, cacheKey, promises ) {
  22003. // check for existing pipeline
  22004. cacheKey = cacheKey || this._getRenderCacheKey( renderObject, stageVertex, stageFragment );
  22005. let pipeline = this.caches.get( cacheKey );
  22006. if ( pipeline === undefined ) {
  22007. pipeline = new RenderPipeline( cacheKey, stageVertex, stageFragment );
  22008. this.caches.set( cacheKey, pipeline );
  22009. renderObject.pipeline = pipeline;
  22010. // The `promises` array is `null` by default and only set to an empty array when
  22011. // `Renderer.compileAsync()` is used. The next call actually fills the array with
  22012. // pending promises that resolve when the render pipelines are ready for rendering.
  22013. this.backend.createRenderPipeline( renderObject, promises );
  22014. }
  22015. return pipeline;
  22016. }
  22017. /**
  22018. * Computes a cache key representing a compute pipeline.
  22019. *
  22020. * @private
  22021. * @param {Node} computeNode - The compute node.
  22022. * @param {ProgrammableStage} stageCompute - The programmable stage representing the compute shader.
  22023. * @return {string} The cache key.
  22024. */
  22025. _getComputeCacheKey( computeNode, stageCompute ) {
  22026. return computeNode.id + ',' + stageCompute.id;
  22027. }
  22028. /**
  22029. * Computes a cache key representing a render pipeline.
  22030. *
  22031. * @private
  22032. * @param {RenderObject} renderObject - The render object.
  22033. * @param {ProgrammableStage} stageVertex - The programmable stage representing the vertex shader.
  22034. * @param {ProgrammableStage} stageFragment - The programmable stage representing the fragment shader.
  22035. * @return {string} The cache key.
  22036. */
  22037. _getRenderCacheKey( renderObject, stageVertex, stageFragment ) {
  22038. return stageVertex.id + ',' + stageFragment.id + ',' + this.backend.getRenderCacheKey( renderObject );
  22039. }
  22040. /**
  22041. * Releases the given pipeline.
  22042. *
  22043. * @private
  22044. * @param {Pipeline} pipeline - The pipeline to release.
  22045. */
  22046. _releasePipeline( pipeline ) {
  22047. this.caches.delete( pipeline.cacheKey );
  22048. }
  22049. /**
  22050. * Releases the shader program.
  22051. *
  22052. * @private
  22053. * @param {Object} program - The shader program to release.
  22054. */
  22055. _releaseProgram( program ) {
  22056. const code = program.code;
  22057. const stage = program.stage;
  22058. this.programs[ stage ].delete( code );
  22059. }
  22060. /**
  22061. * Returns `true` if the compute pipeline for the given compute node requires an update.
  22062. *
  22063. * @private
  22064. * @param {Node} computeNode - The compute node.
  22065. * @return {boolean} Whether the compute pipeline for the given compute node requires an update or not.
  22066. */
  22067. _needsComputeUpdate( computeNode ) {
  22068. const data = this.get( computeNode );
  22069. return data.pipeline === undefined || data.version !== computeNode.version;
  22070. }
  22071. /**
  22072. * Returns `true` if the render pipeline for the given render object requires an update.
  22073. *
  22074. * @private
  22075. * @param {RenderObject} renderObject - The render object.
  22076. * @return {boolean} Whether the render object for the given render object requires an update or not.
  22077. */
  22078. _needsRenderUpdate( renderObject ) {
  22079. const data = this.get( renderObject );
  22080. return data.pipeline === undefined || this.backend.needsRenderUpdate( renderObject );
  22081. }
  22082. }
  22083. /**
  22084. * This renderer module manages the bindings of the renderer.
  22085. *
  22086. * @private
  22087. * @augments DataMap
  22088. */
  22089. class Bindings extends DataMap {
  22090. /**
  22091. * Constructs a new bindings management component.
  22092. *
  22093. * @param {Backend} backend - The renderer's backend.
  22094. * @param {Nodes} nodes - Renderer component for managing nodes related logic.
  22095. * @param {Textures} textures - Renderer component for managing textures.
  22096. * @param {Attributes} attributes - Renderer component for managing attributes.
  22097. * @param {Pipelines} pipelines - Renderer component for managing pipelines.
  22098. * @param {Info} info - Renderer component for managing metrics and monitoring data.
  22099. */
  22100. constructor( backend, nodes, textures, attributes, pipelines, info ) {
  22101. super();
  22102. /**
  22103. * The renderer's backend.
  22104. *
  22105. * @type {Backend}
  22106. */
  22107. this.backend = backend;
  22108. /**
  22109. * Renderer component for managing textures.
  22110. *
  22111. * @type {Textures}
  22112. */
  22113. this.textures = textures;
  22114. /**
  22115. * Renderer component for managing pipelines.
  22116. *
  22117. * @type {Pipelines}
  22118. */
  22119. this.pipelines = pipelines;
  22120. /**
  22121. * Renderer component for managing attributes.
  22122. *
  22123. * @type {Attributes}
  22124. */
  22125. this.attributes = attributes;
  22126. /**
  22127. * Renderer component for managing nodes related logic.
  22128. *
  22129. * @type {Nodes}
  22130. */
  22131. this.nodes = nodes;
  22132. /**
  22133. * Renderer component for managing metrics and monitoring data.
  22134. *
  22135. * @type {Info}
  22136. */
  22137. this.info = info;
  22138. this.pipelines.bindings = this; // assign bindings to pipelines
  22139. }
  22140. /**
  22141. * Returns the bind groups for the given render object.
  22142. *
  22143. * @param {RenderObject} renderObject - The render object.
  22144. * @return {Array<BindGroup>} The bind groups.
  22145. */
  22146. getForRender( renderObject ) {
  22147. const bindings = renderObject.getBindings();
  22148. for ( const bindGroup of bindings ) {
  22149. const groupData = this.get( bindGroup );
  22150. if ( groupData.bindGroup === undefined ) {
  22151. // each object defines an array of bindings (ubos, textures, samplers etc.)
  22152. this._init( bindGroup );
  22153. this.backend.createBindings( bindGroup, bindings, 0 );
  22154. groupData.bindGroup = bindGroup;
  22155. }
  22156. }
  22157. return bindings;
  22158. }
  22159. /**
  22160. * Returns the bind groups for the given compute node.
  22161. *
  22162. * @param {Node} computeNode - The compute node.
  22163. * @return {Array<BindGroup>} The bind groups.
  22164. */
  22165. getForCompute( computeNode ) {
  22166. const bindings = this.nodes.getForCompute( computeNode ).bindings;
  22167. for ( const bindGroup of bindings ) {
  22168. const groupData = this.get( bindGroup );
  22169. if ( groupData.bindGroup === undefined ) {
  22170. this._init( bindGroup );
  22171. this.backend.createBindings( bindGroup, bindings, 0 );
  22172. groupData.bindGroup = bindGroup;
  22173. }
  22174. }
  22175. return bindings;
  22176. }
  22177. /**
  22178. * Updates the bindings for the given compute node.
  22179. *
  22180. * @param {Node} computeNode - The compute node.
  22181. */
  22182. updateForCompute( computeNode ) {
  22183. this._updateBindings( this.getForCompute( computeNode ) );
  22184. }
  22185. /**
  22186. * Updates the bindings for the given render object.
  22187. *
  22188. * @param {RenderObject} renderObject - The render object.
  22189. */
  22190. updateForRender( renderObject ) {
  22191. this._updateBindings( this.getForRender( renderObject ) );
  22192. }
  22193. /**
  22194. * Deletes the bindings for the given compute node.
  22195. *
  22196. * @param {Node} computeNode - The compute node.
  22197. */
  22198. deleteForCompute( computeNode ) {
  22199. const bindings = this.nodes.getForCompute( computeNode ).bindings;
  22200. for ( const bindGroup of bindings ) {
  22201. this.backend.deleteBindGroupData( bindGroup );
  22202. this.delete( bindGroup );
  22203. }
  22204. }
  22205. /**
  22206. * Deletes the bindings for the given renderObject node.
  22207. *
  22208. * @param {RenderObject} renderObject - The renderObject.
  22209. */
  22210. deleteForRender( renderObject ) {
  22211. const bindings = renderObject.getBindings();
  22212. for ( const bindGroup of bindings ) {
  22213. this.backend.deleteBindGroupData( bindGroup );
  22214. this.delete( bindGroup );
  22215. }
  22216. }
  22217. /**
  22218. * Updates the given array of bindings.
  22219. *
  22220. * @param {Array<BindGroup>} bindings - The bind groups.
  22221. */
  22222. _updateBindings( bindings ) {
  22223. for ( const bindGroup of bindings ) {
  22224. this._update( bindGroup, bindings );
  22225. }
  22226. }
  22227. /**
  22228. * Initializes the given bind group.
  22229. *
  22230. * @param {BindGroup} bindGroup - The bind group to initialize.
  22231. */
  22232. _init( bindGroup ) {
  22233. for ( const binding of bindGroup.bindings ) {
  22234. if ( binding.isSampledTexture ) {
  22235. this.textures.updateTexture( binding.texture );
  22236. } else if ( binding.isSampler ) {
  22237. this.textures.updateSampler( binding.texture );
  22238. } else if ( binding.isStorageBuffer ) {
  22239. const attribute = binding.attribute;
  22240. const attributeType = attribute.isIndirectStorageBufferAttribute ? AttributeType.INDIRECT : AttributeType.STORAGE;
  22241. this.attributes.update( attribute, attributeType );
  22242. }
  22243. }
  22244. }
  22245. /**
  22246. * Updates the given bind group.
  22247. *
  22248. * @param {BindGroup} bindGroup - The bind group to update.
  22249. * @param {Array<BindGroup>} bindings - The bind groups.
  22250. */
  22251. _update( bindGroup, bindings ) {
  22252. const { backend } = this;
  22253. let needsBindingsUpdate = false;
  22254. let cacheBindings = true;
  22255. let cacheIndex = 0;
  22256. let version = 0;
  22257. // iterate over all bindings and check if buffer updates or a new binding group is required
  22258. for ( const binding of bindGroup.bindings ) {
  22259. const updatedGroup = this.nodes.updateGroup( binding );
  22260. // every uniforms group is a uniform buffer. So if no update is required,
  22261. // we move one with the next binding. Otherwise the next if block will update the group.
  22262. if ( updatedGroup === false ) continue;
  22263. //
  22264. if ( binding.isStorageBuffer ) {
  22265. const attribute = binding.attribute;
  22266. const attributeType = attribute.isIndirectStorageBufferAttribute ? AttributeType.INDIRECT : AttributeType.STORAGE;
  22267. this.attributes.update( attribute, attributeType );
  22268. }
  22269. if ( binding.isUniformBuffer ) {
  22270. const updated = binding.update();
  22271. if ( updated ) {
  22272. backend.updateBinding( binding );
  22273. }
  22274. } else if ( binding.isSampledTexture ) {
  22275. const updated = binding.update();
  22276. // get the texture data after the update, to sync the texture reference from node
  22277. const texture = binding.texture;
  22278. const texturesTextureData = this.textures.get( texture );
  22279. if ( updated ) {
  22280. // version: update the texture data or create a new one
  22281. this.textures.updateTexture( texture );
  22282. // generation: update the bindings if a new texture has been created
  22283. if ( binding.generation !== texturesTextureData.generation ) {
  22284. binding.generation = texturesTextureData.generation;
  22285. needsBindingsUpdate = true;
  22286. cacheBindings = false;
  22287. }
  22288. }
  22289. const textureData = backend.get( texture );
  22290. if ( textureData.externalTexture !== undefined || texturesTextureData.isDefaultTexture ) {
  22291. cacheBindings = false;
  22292. } else {
  22293. cacheIndex = cacheIndex * 10 + texture.id;
  22294. version += texture.version;
  22295. }
  22296. if ( texture.isStorageTexture === true && texture.mipmapsAutoUpdate === true ) {
  22297. const textureData = this.get( texture );
  22298. if ( binding.store === true ) {
  22299. textureData.needsMipmap = true;
  22300. } else if ( this.textures.needsMipmaps( texture ) && textureData.needsMipmap === true ) {
  22301. this.backend.generateMipmaps( texture );
  22302. textureData.needsMipmap = false;
  22303. }
  22304. }
  22305. } else if ( binding.isSampler ) {
  22306. const updated = binding.update();
  22307. if ( updated ) {
  22308. const samplerKey = this.textures.updateSampler( binding.texture );
  22309. if ( binding.samplerKey !== samplerKey ) {
  22310. binding.samplerKey = samplerKey;
  22311. needsBindingsUpdate = true;
  22312. cacheBindings = false;
  22313. }
  22314. }
  22315. }
  22316. }
  22317. if ( needsBindingsUpdate === true ) {
  22318. this.backend.updateBindings( bindGroup, bindings, cacheBindings ? cacheIndex : 0, version );
  22319. }
  22320. }
  22321. }
  22322. /**
  22323. * Default sorting function for opaque render items.
  22324. *
  22325. * @private
  22326. * @function
  22327. * @param {Object} a - The first render item.
  22328. * @param {Object} b - The second render item.
  22329. * @return {number} A numeric value which defines the sort order.
  22330. */
  22331. function painterSortStable( a, b ) {
  22332. if ( a.groupOrder !== b.groupOrder ) {
  22333. return a.groupOrder - b.groupOrder;
  22334. } else if ( a.renderOrder !== b.renderOrder ) {
  22335. return a.renderOrder - b.renderOrder;
  22336. } else if ( a.z !== b.z ) {
  22337. return a.z - b.z;
  22338. } else {
  22339. return a.id - b.id;
  22340. }
  22341. }
  22342. /**
  22343. * Default sorting function for transparent render items.
  22344. *
  22345. * @private
  22346. * @function
  22347. * @param {Object} a - The first render item.
  22348. * @param {Object} b - The second render item.
  22349. * @return {number} A numeric value which defines the sort order.
  22350. */
  22351. function reversePainterSortStable( a, b ) {
  22352. if ( a.groupOrder !== b.groupOrder ) {
  22353. return a.groupOrder - b.groupOrder;
  22354. } else if ( a.renderOrder !== b.renderOrder ) {
  22355. return a.renderOrder - b.renderOrder;
  22356. } else if ( a.z !== b.z ) {
  22357. return b.z - a.z;
  22358. } else {
  22359. return a.id - b.id;
  22360. }
  22361. }
  22362. /**
  22363. * Returns `true` if the given transparent material requires a double pass.
  22364. *
  22365. * @private
  22366. * @function
  22367. * @param {Material} material - The transparent material.
  22368. * @return {boolean} Whether the given material requires a double pass or not.
  22369. */
  22370. function needsDoublePass( material ) {
  22371. const hasTransmission = material.transmission > 0 || ( material.transmissionNode && material.transmissionNode.isNode );
  22372. return hasTransmission && material.side === DoubleSide && material.forceSinglePass === false;
  22373. }
  22374. /**
  22375. * When the renderer analyzes the scene at the beginning of a render call,
  22376. * it stores 3D object for further processing in render lists. Depending on the
  22377. * properties of a 3D objects (like their transformation or material state), the
  22378. * objects are maintained in ordered lists for the actual rendering.
  22379. *
  22380. * Render lists are unique per scene and camera combination.
  22381. *
  22382. * @private
  22383. * @augments Pipeline
  22384. */
  22385. class RenderList {
  22386. /**
  22387. * Constructs a render list.
  22388. *
  22389. * @param {Lighting} lighting - The lighting management component.
  22390. * @param {Scene} scene - The scene.
  22391. * @param {Camera} camera - The camera the scene is rendered with.
  22392. */
  22393. constructor( lighting, scene, camera ) {
  22394. /**
  22395. * 3D objects are transformed into render items and stored in this array.
  22396. *
  22397. * @type {Array<Object>}
  22398. */
  22399. this.renderItems = [];
  22400. /**
  22401. * The current render items index.
  22402. *
  22403. * @type {number}
  22404. * @default 0
  22405. */
  22406. this.renderItemsIndex = 0;
  22407. /**
  22408. * A list with opaque render items.
  22409. *
  22410. * @type {Array<Object>}
  22411. */
  22412. this.opaque = [];
  22413. /**
  22414. * A list with transparent render items which require
  22415. * double pass rendering (e.g. transmissive objects).
  22416. *
  22417. * @type {Array<Object>}
  22418. */
  22419. this.transparentDoublePass = [];
  22420. /**
  22421. * A list with transparent render items.
  22422. *
  22423. * @type {Array<Object>}
  22424. */
  22425. this.transparent = [];
  22426. /**
  22427. * A list with transparent render bundle data.
  22428. *
  22429. * @type {Array<Object>}
  22430. */
  22431. this.bundles = [];
  22432. /**
  22433. * The render list's lights node. This node is later
  22434. * relevant for the actual analytical light nodes which
  22435. * compute the scene's lighting in the shader.
  22436. *
  22437. * @type {LightsNode}
  22438. */
  22439. this.lightsNode = lighting.getNode( scene, camera );
  22440. /**
  22441. * The scene's lights stored in an array. This array
  22442. * is used to setup the lights node.
  22443. *
  22444. * @type {Array<Light>}
  22445. */
  22446. this.lightsArray = [];
  22447. /**
  22448. * The scene.
  22449. *
  22450. * @type {Scene}
  22451. */
  22452. this.scene = scene;
  22453. /**
  22454. * The camera the scene is rendered with.
  22455. *
  22456. * @type {Camera}
  22457. */
  22458. this.camera = camera;
  22459. /**
  22460. * How many objects perform occlusion query tests.
  22461. *
  22462. * @type {number}
  22463. * @default 0
  22464. */
  22465. this.occlusionQueryCount = 0;
  22466. }
  22467. /**
  22468. * This method is called right at the beginning of a render call
  22469. * before the scene is analyzed. It prepares the internal data
  22470. * structures for the upcoming render lists generation.
  22471. *
  22472. * @return {RenderList} A reference to this render list.
  22473. */
  22474. begin() {
  22475. this.renderItemsIndex = 0;
  22476. this.opaque.length = 0;
  22477. this.transparentDoublePass.length = 0;
  22478. this.transparent.length = 0;
  22479. this.bundles.length = 0;
  22480. this.lightsArray.length = 0;
  22481. this.occlusionQueryCount = 0;
  22482. return this;
  22483. }
  22484. /**
  22485. * Returns a render item for the giving render item state. The state is defined
  22486. * by a series of object-related parameters.
  22487. *
  22488. * The method avoids object creation by holding render items and reusing them in
  22489. * subsequent render calls (just with different property values).
  22490. *
  22491. * @param {Object3D} object - The 3D object.
  22492. * @param {BufferGeometry} geometry - The 3D object's geometry.
  22493. * @param {Material} material - The 3D object's material.
  22494. * @param {number} groupOrder - The current group order.
  22495. * @param {number} z - Th 3D object's depth value (z value in clip space).
  22496. * @param {?number} group - {?Object} group - Only relevant for objects using multiple materials. This represents a group entry from the respective `BufferGeometry`.
  22497. * @param {ClippingContext} clippingContext - The current clipping context.
  22498. * @return {Object} The render item.
  22499. */
  22500. getNextRenderItem( object, geometry, material, groupOrder, z, group, clippingContext ) {
  22501. let renderItem = this.renderItems[ this.renderItemsIndex ];
  22502. if ( renderItem === undefined ) {
  22503. renderItem = {
  22504. id: object.id,
  22505. object: object,
  22506. geometry: geometry,
  22507. material: material,
  22508. groupOrder: groupOrder,
  22509. renderOrder: object.renderOrder,
  22510. z: z,
  22511. group: group,
  22512. clippingContext: clippingContext
  22513. };
  22514. this.renderItems[ this.renderItemsIndex ] = renderItem;
  22515. } else {
  22516. renderItem.id = object.id;
  22517. renderItem.object = object;
  22518. renderItem.geometry = geometry;
  22519. renderItem.material = material;
  22520. renderItem.groupOrder = groupOrder;
  22521. renderItem.renderOrder = object.renderOrder;
  22522. renderItem.z = z;
  22523. renderItem.group = group;
  22524. renderItem.clippingContext = clippingContext;
  22525. }
  22526. this.renderItemsIndex ++;
  22527. return renderItem;
  22528. }
  22529. /**
  22530. * Pushes the given object as a render item to the internal render lists.
  22531. * The selected lists depend on the object properties.
  22532. *
  22533. * @param {Object3D} object - The 3D object.
  22534. * @param {BufferGeometry} geometry - The 3D object's geometry.
  22535. * @param {Material} material - The 3D object's material.
  22536. * @param {number} groupOrder - The current group order.
  22537. * @param {number} z - Th 3D object's depth value (z value in clip space).
  22538. * @param {?number} group - {?Object} group - Only relevant for objects using multiple materials. This represents a group entry from the respective `BufferGeometry`.
  22539. * @param {ClippingContext} clippingContext - The current clipping context.
  22540. */
  22541. push( object, geometry, material, groupOrder, z, group, clippingContext ) {
  22542. const renderItem = this.getNextRenderItem( object, geometry, material, groupOrder, z, group, clippingContext );
  22543. if ( object.occlusionTest === true ) this.occlusionQueryCount ++;
  22544. if ( material.transparent === true || material.transmission > 0 ||
  22545. ( material.transmissionNode && material.transmissionNode.isNode ) ||
  22546. ( material.backdropNode && material.backdropNode.isNode ) ) {
  22547. if ( needsDoublePass( material ) ) this.transparentDoublePass.push( renderItem );
  22548. this.transparent.push( renderItem );
  22549. } else {
  22550. this.opaque.push( renderItem );
  22551. }
  22552. }
  22553. /**
  22554. * Inserts the given object as a render item at the start of the internal render lists.
  22555. * The selected lists depend on the object properties.
  22556. *
  22557. * @param {Object3D} object - The 3D object.
  22558. * @param {BufferGeometry} geometry - The 3D object's geometry.
  22559. * @param {Material} material - The 3D object's material.
  22560. * @param {number} groupOrder - The current group order.
  22561. * @param {number} z - Th 3D object's depth value (z value in clip space).
  22562. * @param {?number} group - {?Object} group - Only relevant for objects using multiple materials. This represents a group entry from the respective `BufferGeometry`.
  22563. * @param {ClippingContext} clippingContext - The current clipping context.
  22564. */
  22565. unshift( object, geometry, material, groupOrder, z, group, clippingContext ) {
  22566. const renderItem = this.getNextRenderItem( object, geometry, material, groupOrder, z, group, clippingContext );
  22567. if ( material.transparent === true || material.transmission > 0 ||
  22568. ( material.transmissionNode && material.transmissionNode.isNode ) ||
  22569. ( material.backdropNode && material.backdropNode.isNode ) ) {
  22570. if ( needsDoublePass( material ) ) this.transparentDoublePass.unshift( renderItem );
  22571. this.transparent.unshift( renderItem );
  22572. } else {
  22573. this.opaque.unshift( renderItem );
  22574. }
  22575. }
  22576. /**
  22577. * Pushes render bundle group data into the render list.
  22578. *
  22579. * @param {Object} group - Bundle group data.
  22580. */
  22581. pushBundle( group ) {
  22582. this.bundles.push( group );
  22583. }
  22584. /**
  22585. * Pushes a light into the render list.
  22586. *
  22587. * @param {Light} light - The light.
  22588. */
  22589. pushLight( light ) {
  22590. this.lightsArray.push( light );
  22591. }
  22592. /**
  22593. * Sorts the internal render lists.
  22594. *
  22595. * @param {?function(any, any): number} customOpaqueSort - A custom sort function for opaque objects.
  22596. * @param {?function(any, any): number} customTransparentSort - A custom sort function for transparent objects.
  22597. */
  22598. sort( customOpaqueSort, customTransparentSort ) {
  22599. if ( this.opaque.length > 1 ) this.opaque.sort( customOpaqueSort || painterSortStable );
  22600. if ( this.transparentDoublePass.length > 1 ) this.transparentDoublePass.sort( customTransparentSort || reversePainterSortStable );
  22601. if ( this.transparent.length > 1 ) this.transparent.sort( customTransparentSort || reversePainterSortStable );
  22602. }
  22603. /**
  22604. * This method performs finalizing tasks right after the render lists
  22605. * have been generated.
  22606. */
  22607. finish() {
  22608. // update lights
  22609. this.lightsNode.setLights( this.lightsArray );
  22610. // Clear references from inactive renderItems in the list
  22611. for ( let i = this.renderItemsIndex, il = this.renderItems.length; i < il; i ++ ) {
  22612. const renderItem = this.renderItems[ i ];
  22613. if ( renderItem.id === null ) break;
  22614. renderItem.id = null;
  22615. renderItem.object = null;
  22616. renderItem.geometry = null;
  22617. renderItem.material = null;
  22618. renderItem.groupOrder = null;
  22619. renderItem.renderOrder = null;
  22620. renderItem.z = null;
  22621. renderItem.group = null;
  22622. renderItem.clippingContext = null;
  22623. }
  22624. }
  22625. }
  22626. const _chainKeys$4 = [];
  22627. /**
  22628. * This renderer module manages the render lists which are unique
  22629. * per scene and camera combination.
  22630. *
  22631. * @private
  22632. */
  22633. class RenderLists {
  22634. /**
  22635. * Constructs a render lists management component.
  22636. *
  22637. * @param {Lighting} lighting - The lighting management component.
  22638. */
  22639. constructor( lighting ) {
  22640. /**
  22641. * The lighting management component.
  22642. *
  22643. * @type {Lighting}
  22644. */
  22645. this.lighting = lighting;
  22646. /**
  22647. * The internal chain map which holds the render lists.
  22648. *
  22649. * @type {ChainMap}
  22650. */
  22651. this.lists = new ChainMap();
  22652. }
  22653. /**
  22654. * Returns a render list for the given scene and camera.
  22655. *
  22656. * @param {Scene} scene - The scene.
  22657. * @param {Camera} camera - The camera.
  22658. * @return {RenderList} The render list.
  22659. */
  22660. get( scene, camera ) {
  22661. const lists = this.lists;
  22662. _chainKeys$4[ 0 ] = scene;
  22663. _chainKeys$4[ 1 ] = camera;
  22664. let list = lists.get( _chainKeys$4 );
  22665. if ( list === undefined ) {
  22666. list = new RenderList( this.lighting, scene, camera );
  22667. lists.set( _chainKeys$4, list );
  22668. }
  22669. _chainKeys$4.length = 0;
  22670. return list;
  22671. }
  22672. /**
  22673. * Frees all internal resources.
  22674. */
  22675. dispose() {
  22676. this.lists = new ChainMap();
  22677. }
  22678. }
  22679. let _id$8 = 0;
  22680. /**
  22681. * Any render or compute command is executed in a specific context that defines
  22682. * the state of the renderer and its backend. Typical examples for such context
  22683. * data are the current clear values or data from the active framebuffer. This
  22684. * module is used to represent these contexts as objects.
  22685. *
  22686. * @private
  22687. */
  22688. class RenderContext {
  22689. /**
  22690. * Constructs a new render context.
  22691. */
  22692. constructor() {
  22693. /**
  22694. * The context's ID.
  22695. *
  22696. * @type {number}
  22697. */
  22698. this.id = _id$8 ++;
  22699. /**
  22700. * Whether the current active framebuffer has a color attachment.
  22701. *
  22702. * @type {boolean}
  22703. * @default true
  22704. */
  22705. this.color = true;
  22706. /**
  22707. * Whether the color attachment should be cleared or not.
  22708. *
  22709. * @type {boolean}
  22710. * @default true
  22711. */
  22712. this.clearColor = true;
  22713. /**
  22714. * The clear color value.
  22715. *
  22716. * @type {Object}
  22717. * @default true
  22718. */
  22719. this.clearColorValue = { r: 0, g: 0, b: 0, a: 1 };
  22720. /**
  22721. * Whether the current active framebuffer has a depth attachment.
  22722. *
  22723. * @type {boolean}
  22724. * @default true
  22725. */
  22726. this.depth = true;
  22727. /**
  22728. * Whether the depth attachment should be cleared or not.
  22729. *
  22730. * @type {boolean}
  22731. * @default true
  22732. */
  22733. this.clearDepth = true;
  22734. /**
  22735. * The clear depth value.
  22736. *
  22737. * @type {number}
  22738. * @default 1
  22739. */
  22740. this.clearDepthValue = 1;
  22741. /**
  22742. * Whether the current active framebuffer has a stencil attachment.
  22743. *
  22744. * @type {boolean}
  22745. * @default false
  22746. */
  22747. this.stencil = false;
  22748. /**
  22749. * Whether the stencil attachment should be cleared or not.
  22750. *
  22751. * @type {boolean}
  22752. * @default true
  22753. */
  22754. this.clearStencil = true;
  22755. /**
  22756. * The clear stencil value.
  22757. *
  22758. * @type {number}
  22759. * @default 1
  22760. */
  22761. this.clearStencilValue = 1;
  22762. /**
  22763. * By default the viewport encloses the entire framebuffer If a smaller
  22764. * viewport is manually defined, this property is to `true` by the renderer.
  22765. *
  22766. * @type {boolean}
  22767. * @default false
  22768. */
  22769. this.viewport = false;
  22770. /**
  22771. * The viewport value. This value is in physical pixels meaning it incorporates
  22772. * the renderer's pixel ratio. The viewport property of render targets or
  22773. * the renderer is in logical pixels.
  22774. *
  22775. * @type {Vector4}
  22776. */
  22777. this.viewportValue = new Vector4();
  22778. /**
  22779. * When the scissor test is active and scissor rectangle smaller than the
  22780. * framebuffers dimensions, this property is to `true` by the renderer.
  22781. *
  22782. * @type {boolean}
  22783. * @default false
  22784. */
  22785. this.scissor = false;
  22786. /**
  22787. * The scissor rectangle.
  22788. *
  22789. * @type {Vector4}
  22790. */
  22791. this.scissorValue = new Vector4();
  22792. /**
  22793. * The active render target.
  22794. *
  22795. * @type {?RenderTarget}
  22796. * @default null
  22797. */
  22798. this.renderTarget = null;
  22799. /**
  22800. * The textures of the active render target.
  22801. * `null` when no render target is set.
  22802. *
  22803. * @type {?Array<Texture>}
  22804. * @default null
  22805. */
  22806. this.textures = null;
  22807. /**
  22808. * The depth texture of the active render target.
  22809. * `null` when no render target is set.
  22810. *
  22811. * @type {?DepthTexture}
  22812. * @default null
  22813. */
  22814. this.depthTexture = null;
  22815. /**
  22816. * The active cube face.
  22817. *
  22818. * @type {number}
  22819. * @default 0
  22820. */
  22821. this.activeCubeFace = 0;
  22822. /**
  22823. * The active mipmap level.
  22824. *
  22825. * @type {number}
  22826. * @default 0
  22827. */
  22828. this.activeMipmapLevel = 0;
  22829. /**
  22830. * The number of MSAA samples. This value is always `1` when
  22831. * MSAA isn't used.
  22832. *
  22833. * @type {number}
  22834. * @default 1
  22835. */
  22836. this.sampleCount = 1;
  22837. /**
  22838. * The active render target's width in physical pixels.
  22839. *
  22840. * @type {number}
  22841. * @default 0
  22842. */
  22843. this.width = 0;
  22844. /**
  22845. * The active render target's height in physical pixels.
  22846. *
  22847. * @type {number}
  22848. * @default 0
  22849. */
  22850. this.height = 0;
  22851. /**
  22852. * The occlusion query count.
  22853. *
  22854. * @type {number}
  22855. * @default 0
  22856. */
  22857. this.occlusionQueryCount = 0;
  22858. /**
  22859. * The current clipping context.
  22860. *
  22861. * @type {?ClippingContext}
  22862. * @default null
  22863. */
  22864. this.clippingContext = null;
  22865. /**
  22866. * This flag can be used for type testing.
  22867. *
  22868. * @type {boolean}
  22869. * @readonly
  22870. * @default true
  22871. */
  22872. this.isRenderContext = true;
  22873. }
  22874. /**
  22875. * Returns the cache key of this render context.
  22876. *
  22877. * @return {number} The cache key.
  22878. */
  22879. getCacheKey() {
  22880. return getCacheKey( this );
  22881. }
  22882. }
  22883. /**
  22884. * Computes a cache key for the given render context. This key
  22885. * should identify the render target state so it is possible to
  22886. * configure the correct attachments in the respective backend.
  22887. *
  22888. * @param {RenderContext} renderContext - The render context.
  22889. * @return {number} The cache key.
  22890. */
  22891. function getCacheKey( renderContext ) {
  22892. const { textures, activeCubeFace, activeMipmapLevel } = renderContext;
  22893. const values = [ activeCubeFace, activeMipmapLevel ];
  22894. for ( const texture of textures ) {
  22895. values.push( texture.id );
  22896. }
  22897. return hashArray( values );
  22898. }
  22899. const _chainKeys$3 = [];
  22900. const _defaultScene = /*@__PURE__*/ new Scene();
  22901. const _defaultCamera = /*@__PURE__*/ new Camera();
  22902. /**
  22903. * This module manages the render contexts of the renderer.
  22904. *
  22905. * @private
  22906. */
  22907. class RenderContexts {
  22908. /**
  22909. * Constructs a new render context management component.
  22910. */
  22911. constructor() {
  22912. /**
  22913. * A dictionary that manages render contexts in chain maps
  22914. * for each attachment state.
  22915. *
  22916. * @type {Object<string,ChainMap>}
  22917. */
  22918. this.chainMaps = {};
  22919. }
  22920. /**
  22921. * Returns a render context for the given scene, camera and render target.
  22922. *
  22923. * @param {Scene} scene - The scene.
  22924. * @param {Camera} camera - The camera that is used to render the scene.
  22925. * @param {?RenderTarget} [renderTarget=null] - The active render target.
  22926. * @param {?MRT} [mrt=null] - The active multiple render target.
  22927. * @return {RenderContext} The render context.
  22928. */
  22929. get( scene, camera, renderTarget = null, mrt = null ) {
  22930. _chainKeys$3[ 0 ] = scene;
  22931. _chainKeys$3[ 1 ] = camera;
  22932. if ( mrt !== null ) {
  22933. _chainKeys$3[ 2 ] = mrt;
  22934. }
  22935. let attachmentState;
  22936. if ( renderTarget === null ) {
  22937. attachmentState = 'default';
  22938. } else {
  22939. const format = renderTarget.texture.format;
  22940. const count = renderTarget.textures.length;
  22941. attachmentState = `${ count }:${ format }:${ renderTarget.samples }:${ renderTarget.depthBuffer }:${ renderTarget.stencilBuffer }`;
  22942. }
  22943. const chainMap = this._getChainMap( attachmentState );
  22944. let renderState = chainMap.get( _chainKeys$3 );
  22945. if ( renderState === undefined ) {
  22946. renderState = new RenderContext();
  22947. chainMap.set( _chainKeys$3, renderState );
  22948. }
  22949. _chainKeys$3.length = 0;
  22950. if ( renderTarget !== null ) renderState.sampleCount = renderTarget.samples === 0 ? 1 : renderTarget.samples;
  22951. return renderState;
  22952. }
  22953. /**
  22954. * Returns a render context intended for clear operations.
  22955. *
  22956. * @param {?RenderTarget} [renderTarget=null] - The active render target.
  22957. * @return {RenderContext} The render context.
  22958. */
  22959. getForClear( renderTarget = null ) {
  22960. return this.get( _defaultScene, _defaultCamera, renderTarget );
  22961. }
  22962. /**
  22963. * Returns a chain map for the given attachment state.
  22964. *
  22965. * @private
  22966. * @param {string} attachmentState - The attachment state.
  22967. * @return {ChainMap} The chain map.
  22968. */
  22969. _getChainMap( attachmentState ) {
  22970. return this.chainMaps[ attachmentState ] || ( this.chainMaps[ attachmentState ] = new ChainMap() );
  22971. }
  22972. /**
  22973. * Frees internal resources.
  22974. */
  22975. dispose() {
  22976. this.chainMaps = {};
  22977. }
  22978. }
  22979. const _size$3 = /*@__PURE__*/ new Vector3();
  22980. /**
  22981. * This module manages the textures of the renderer.
  22982. *
  22983. * @private
  22984. * @augments DataMap
  22985. */
  22986. class Textures extends DataMap {
  22987. /**
  22988. * Constructs a new texture management component.
  22989. *
  22990. * @param {Renderer} renderer - The renderer.
  22991. * @param {Backend} backend - The renderer's backend.
  22992. * @param {Info} info - Renderer component for managing metrics and monitoring data.
  22993. */
  22994. constructor( renderer, backend, info ) {
  22995. super();
  22996. /**
  22997. * The renderer.
  22998. *
  22999. * @type {Renderer}
  23000. */
  23001. this.renderer = renderer;
  23002. /**
  23003. * The backend.
  23004. *
  23005. * @type {Backend}
  23006. */
  23007. this.backend = backend;
  23008. /**
  23009. * Renderer component for managing metrics and monitoring data.
  23010. *
  23011. * @type {Info}
  23012. */
  23013. this.info = info;
  23014. }
  23015. /**
  23016. * Updates the given render target. Based on the given render target configuration,
  23017. * it updates the texture states representing the attachments of the framebuffer.
  23018. *
  23019. * @param {RenderTarget} renderTarget - The render target to update.
  23020. * @param {number} [activeMipmapLevel=0] - The active mipmap level.
  23021. */
  23022. updateRenderTarget( renderTarget, activeMipmapLevel = 0 ) {
  23023. const renderTargetData = this.get( renderTarget );
  23024. const sampleCount = renderTarget.samples === 0 ? 1 : renderTarget.samples;
  23025. const depthTextureMips = renderTargetData.depthTextureMips || ( renderTargetData.depthTextureMips = {} );
  23026. const textures = renderTarget.textures;
  23027. const size = this.getSize( textures[ 0 ] );
  23028. const mipWidth = size.width >> activeMipmapLevel;
  23029. const mipHeight = size.height >> activeMipmapLevel;
  23030. let depthTexture = renderTarget.depthTexture || depthTextureMips[ activeMipmapLevel ];
  23031. const useDepthTexture = renderTarget.depthBuffer === true || renderTarget.stencilBuffer === true;
  23032. let textureNeedsUpdate = false;
  23033. if ( depthTexture === undefined && useDepthTexture ) {
  23034. depthTexture = new DepthTexture();
  23035. depthTexture.format = renderTarget.stencilBuffer ? DepthStencilFormat : DepthFormat;
  23036. depthTexture.type = renderTarget.stencilBuffer ? UnsignedInt248Type : UnsignedIntType; // FloatType
  23037. depthTexture.image.width = mipWidth;
  23038. depthTexture.image.height = mipHeight;
  23039. depthTexture.image.depth = size.depth;
  23040. depthTexture.renderTarget = renderTarget;
  23041. depthTexture.isArrayTexture = renderTarget.multiview === true && size.depth > 1;
  23042. depthTextureMips[ activeMipmapLevel ] = depthTexture;
  23043. }
  23044. if ( renderTargetData.width !== size.width || size.height !== renderTargetData.height ) {
  23045. textureNeedsUpdate = true;
  23046. if ( depthTexture ) {
  23047. depthTexture.needsUpdate = true;
  23048. depthTexture.image.width = mipWidth;
  23049. depthTexture.image.height = mipHeight;
  23050. depthTexture.image.depth = depthTexture.isArrayTexture ? depthTexture.image.depth : 1;
  23051. }
  23052. }
  23053. renderTargetData.width = size.width;
  23054. renderTargetData.height = size.height;
  23055. renderTargetData.textures = textures;
  23056. renderTargetData.depthTexture = depthTexture || null;
  23057. renderTargetData.depth = renderTarget.depthBuffer;
  23058. renderTargetData.stencil = renderTarget.stencilBuffer;
  23059. renderTargetData.renderTarget = renderTarget;
  23060. if ( renderTargetData.sampleCount !== sampleCount ) {
  23061. textureNeedsUpdate = true;
  23062. if ( depthTexture ) {
  23063. depthTexture.needsUpdate = true;
  23064. }
  23065. renderTargetData.sampleCount = sampleCount;
  23066. }
  23067. //
  23068. const options = { sampleCount };
  23069. // XR render targets require no texture updates
  23070. if ( renderTarget.isXRRenderTarget !== true ) {
  23071. for ( let i = 0; i < textures.length; i ++ ) {
  23072. const texture = textures[ i ];
  23073. if ( textureNeedsUpdate ) texture.needsUpdate = true;
  23074. this.updateTexture( texture, options );
  23075. }
  23076. if ( depthTexture ) {
  23077. this.updateTexture( depthTexture, options );
  23078. }
  23079. }
  23080. // dispose handler
  23081. if ( renderTargetData.initialized !== true ) {
  23082. renderTargetData.initialized = true;
  23083. // dispose
  23084. renderTargetData.onDispose = () => {
  23085. this._destroyRenderTarget( renderTarget );
  23086. };
  23087. renderTarget.addEventListener( 'dispose', renderTargetData.onDispose );
  23088. }
  23089. }
  23090. /**
  23091. * Updates the given texture. Depending on the texture state, this method
  23092. * triggers the upload of texture data to the GPU memory. If the texture data are
  23093. * not yet ready for the upload, it uses default texture data for as a placeholder.
  23094. *
  23095. * @param {Texture} texture - The texture to update.
  23096. * @param {Object} [options={}] - The options.
  23097. */
  23098. updateTexture( texture, options = {} ) {
  23099. const textureData = this.get( texture );
  23100. if ( textureData.initialized === true && textureData.version === texture.version ) return;
  23101. const isRenderTarget = texture.isRenderTargetTexture || texture.isDepthTexture || texture.isFramebufferTexture;
  23102. const backend = this.backend;
  23103. if ( isRenderTarget && textureData.initialized === true ) {
  23104. // it's an update
  23105. backend.destroyTexture( texture );
  23106. }
  23107. //
  23108. if ( texture.isFramebufferTexture ) {
  23109. const renderTarget = this.renderer.getRenderTarget();
  23110. if ( renderTarget ) {
  23111. texture.type = renderTarget.texture.type;
  23112. } else {
  23113. texture.type = UnsignedByteType;
  23114. }
  23115. }
  23116. //
  23117. const { width, height, depth } = this.getSize( texture );
  23118. options.width = width;
  23119. options.height = height;
  23120. options.depth = depth;
  23121. options.needsMipmaps = this.needsMipmaps( texture );
  23122. options.levels = options.needsMipmaps ? this.getMipLevels( texture, width, height ) : 1;
  23123. // TODO: Uniformly handle mipmap definitions
  23124. // Normal textures and compressed cube textures define base level + mips with their mipmap array
  23125. // Uncompressed cube textures use their mipmap array only for mips (no base level)
  23126. if ( texture.isCubeTexture && texture.mipmaps.length > 0 ) options.levels ++;
  23127. //
  23128. if ( isRenderTarget || texture.isStorageTexture === true || texture.isExternalTexture === true ) {
  23129. backend.createTexture( texture, options );
  23130. textureData.generation = texture.version;
  23131. } else {
  23132. if ( texture.version > 0 ) {
  23133. const image = texture.image;
  23134. if ( image === undefined ) {
  23135. warn( 'Renderer: Texture marked for update but image is undefined.' );
  23136. } else if ( image.complete === false ) {
  23137. warn( 'Renderer: Texture marked for update but image is incomplete.' );
  23138. } else {
  23139. if ( texture.images ) {
  23140. const images = [];
  23141. for ( const image of texture.images ) {
  23142. images.push( image );
  23143. }
  23144. options.images = images;
  23145. } else {
  23146. options.image = image;
  23147. }
  23148. if ( textureData.isDefaultTexture === undefined || textureData.isDefaultTexture === true ) {
  23149. backend.createTexture( texture, options );
  23150. textureData.isDefaultTexture = false;
  23151. textureData.generation = texture.version;
  23152. }
  23153. if ( texture.source.dataReady === true ) backend.updateTexture( texture, options );
  23154. const skipAutoGeneration = texture.isStorageTexture === true && texture.mipmapsAutoUpdate === false;
  23155. if ( options.needsMipmaps && texture.mipmaps.length === 0 && ! skipAutoGeneration ) {
  23156. backend.generateMipmaps( texture );
  23157. }
  23158. if ( texture.onUpdate ) texture.onUpdate( texture );
  23159. }
  23160. } else {
  23161. // async update
  23162. backend.createDefaultTexture( texture );
  23163. textureData.isDefaultTexture = true;
  23164. textureData.generation = texture.version;
  23165. }
  23166. }
  23167. // dispose handler
  23168. if ( textureData.initialized !== true ) {
  23169. textureData.initialized = true;
  23170. textureData.generation = texture.version;
  23171. //
  23172. this.info.memory.textures ++;
  23173. //
  23174. if ( texture.isVideoTexture && ColorManagement.enabled === true && ColorManagement.getTransfer( texture.colorSpace ) !== SRGBTransfer ) {
  23175. warn( 'WebGPURenderer: Video textures must use a color space with a sRGB transfer function, e.g. SRGBColorSpace.' );
  23176. }
  23177. // dispose
  23178. textureData.onDispose = () => {
  23179. this._destroyTexture( texture );
  23180. };
  23181. texture.addEventListener( 'dispose', textureData.onDispose );
  23182. }
  23183. //
  23184. textureData.version = texture.version;
  23185. }
  23186. /**
  23187. * Updates the sampler for the given texture. This method has no effect
  23188. * for the WebGL backend since it has no concept of samplers. Texture
  23189. * parameters are configured with the `texParameter()` command for each
  23190. * texture.
  23191. *
  23192. * In WebGPU, samplers are objects like textures and it's possible to share
  23193. * them when the texture parameters match.
  23194. *
  23195. * @param {Texture} texture - The texture to update the sampler for.
  23196. * @return {string} The current sampler key.
  23197. */
  23198. updateSampler( texture ) {
  23199. return this.backend.updateSampler( texture );
  23200. }
  23201. /**
  23202. * Computes the size of the given texture and writes the result
  23203. * into the target vector. This vector is also returned by the
  23204. * method.
  23205. *
  23206. * If no texture data are available for the compute yet, the method
  23207. * returns default size values.
  23208. *
  23209. * @param {Texture} texture - The texture to compute the size for.
  23210. * @param {Vector3} target - The target vector.
  23211. * @return {Vector3} The target vector.
  23212. */
  23213. getSize( texture, target = _size$3 ) {
  23214. let image = texture.images ? texture.images[ 0 ] : texture.image;
  23215. if ( image ) {
  23216. if ( image.image !== undefined ) image = image.image;
  23217. if ( ( typeof HTMLVideoElement !== 'undefined' ) && ( image instanceof HTMLVideoElement ) ) {
  23218. target.width = image.videoWidth || 1;
  23219. target.height = image.videoHeight || 1;
  23220. target.depth = 1;
  23221. } else if ( ( typeof VideoFrame !== 'undefined' ) && ( image instanceof VideoFrame ) ) {
  23222. target.width = image.displayWidth || 1;
  23223. target.height = image.displayHeight || 1;
  23224. target.depth = 1;
  23225. } else {
  23226. target.width = image.width || 1;
  23227. target.height = image.height || 1;
  23228. target.depth = texture.isCubeTexture ? 6 : ( image.depth || 1 );
  23229. }
  23230. } else {
  23231. target.width = target.height = target.depth = 1;
  23232. }
  23233. return target;
  23234. }
  23235. /**
  23236. * Computes the number of mipmap levels for the given texture.
  23237. *
  23238. * @param {Texture} texture - The texture.
  23239. * @param {number} width - The texture's width.
  23240. * @param {number} height - The texture's height.
  23241. * @return {number} The number of mipmap levels.
  23242. */
  23243. getMipLevels( texture, width, height ) {
  23244. let mipLevelCount;
  23245. if ( texture.mipmaps.length > 0 ) {
  23246. mipLevelCount = texture.mipmaps.length;
  23247. } else {
  23248. if ( texture.isCompressedTexture === true ) {
  23249. // it is not possible to compute mipmaps for compressed textures. So
  23250. // when no mipmaps are defined in "texture.mipmaps", force a texture
  23251. // level of 1
  23252. mipLevelCount = 1;
  23253. } else {
  23254. mipLevelCount = Math.floor( Math.log2( Math.max( width, height ) ) ) + 1;
  23255. }
  23256. }
  23257. return mipLevelCount;
  23258. }
  23259. /**
  23260. * Returns `true` if the given texture makes use of mipmapping.
  23261. *
  23262. * @param {Texture} texture - The texture.
  23263. * @return {boolean} Whether mipmaps are required or not.
  23264. */
  23265. needsMipmaps( texture ) {
  23266. return texture.generateMipmaps === true || texture.mipmaps.length > 0;
  23267. }
  23268. /**
  23269. * Frees internal resources when the given render target isn't
  23270. * required anymore.
  23271. *
  23272. * @param {RenderTarget} renderTarget - The render target to destroy.
  23273. */
  23274. _destroyRenderTarget( renderTarget ) {
  23275. if ( this.has( renderTarget ) === true ) {
  23276. const renderTargetData = this.get( renderTarget );
  23277. const textures = renderTargetData.textures;
  23278. const depthTexture = renderTargetData.depthTexture;
  23279. //
  23280. renderTarget.removeEventListener( 'dispose', renderTargetData.onDispose );
  23281. //
  23282. for ( let i = 0; i < textures.length; i ++ ) {
  23283. this._destroyTexture( textures[ i ] );
  23284. }
  23285. if ( depthTexture ) {
  23286. this._destroyTexture( depthTexture );
  23287. }
  23288. this.delete( renderTarget );
  23289. this.backend.delete( renderTarget );
  23290. }
  23291. }
  23292. /**
  23293. * Frees internal resource when the given texture isn't
  23294. * required anymore.
  23295. *
  23296. * @param {Texture} texture - The texture to destroy.
  23297. */
  23298. _destroyTexture( texture ) {
  23299. if ( this.has( texture ) === true ) {
  23300. const textureData = this.get( texture );
  23301. //
  23302. texture.removeEventListener( 'dispose', textureData.onDispose );
  23303. // if a texture is not ready for use, it falls back to a default texture so it's possible
  23304. // to use it for rendering. If a texture in this state is disposed, it's important to
  23305. // not destroy/delete the underlying GPU texture object since it is cached and shared with
  23306. // other textures.
  23307. const isDefaultTexture = textureData.isDefaultTexture;
  23308. this.backend.destroyTexture( texture, isDefaultTexture );
  23309. this.delete( texture );
  23310. this.info.memory.textures --;
  23311. }
  23312. }
  23313. }
  23314. /**
  23315. * A four-component version of {@link Color} which is internally
  23316. * used by the renderer to represents clear color with alpha as
  23317. * one object.
  23318. *
  23319. * @private
  23320. * @augments Color
  23321. */
  23322. class Color4 extends Color {
  23323. /**
  23324. * Constructs a new four-component color.
  23325. * You can also pass a single THREE.Color, hex or
  23326. * string argument to this constructor.
  23327. *
  23328. * @param {number|string} [r=1] - The red value.
  23329. * @param {number} [g=1] - The green value.
  23330. * @param {number} [b=1] - The blue value.
  23331. * @param {number} [a=1] - The alpha value.
  23332. */
  23333. constructor( r, g, b, a = 1 ) {
  23334. super( r, g, b );
  23335. this.a = a;
  23336. }
  23337. /**
  23338. * Overwrites the default to honor alpha.
  23339. * You can also pass a single THREE.Color, hex or
  23340. * string argument to this method.
  23341. *
  23342. * @param {number|string|Color} r - The red value.
  23343. * @param {number} [g] - The green value.
  23344. * @param {number} [b] - The blue value.
  23345. * @param {number} [a=1] - The alpha value.
  23346. * @return {Color4} A reference to this object.
  23347. */
  23348. set( r, g, b, a = 1 ) {
  23349. this.a = a;
  23350. return super.set( r, g, b );
  23351. }
  23352. /**
  23353. * Overwrites the default to honor alpha.
  23354. *
  23355. * @param {Color4} color - The color to copy.
  23356. * @return {Color4} A reference to this object.
  23357. */
  23358. copy( color ) {
  23359. if ( color.a !== undefined ) this.a = color.a;
  23360. return super.copy( color );
  23361. }
  23362. /**
  23363. * Overwrites the default to honor alpha.
  23364. *
  23365. * @return {Color4} The cloned color.
  23366. */
  23367. clone() {
  23368. return new this.constructor( this.r, this.g, this.b, this.a );
  23369. }
  23370. }
  23371. /**
  23372. * Special version of {@link PropertyNode} which is used for parameters.
  23373. *
  23374. * @augments PropertyNode
  23375. */
  23376. class ParameterNode extends PropertyNode {
  23377. static get type() {
  23378. return 'ParameterNode';
  23379. }
  23380. /**
  23381. * Constructs a new parameter node.
  23382. *
  23383. * @param {string} nodeType - The type of the node.
  23384. * @param {?string} [name=null] - The name of the parameter in the shader.
  23385. */
  23386. constructor( nodeType, name = null ) {
  23387. super( nodeType, name );
  23388. /**
  23389. * This flag can be used for type testing.
  23390. *
  23391. * @type {boolean}
  23392. * @readonly
  23393. * @default true
  23394. */
  23395. this.isParameterNode = true;
  23396. }
  23397. /**
  23398. * Gets the type of a member variable in the parameter node.
  23399. *
  23400. * @param {NodeBuilder} builder - The node builder.
  23401. * @param {string} name - The name of the member variable.
  23402. * @returns {string}
  23403. */
  23404. getMemberType( builder, name ) {
  23405. const type = this.getNodeType( builder );
  23406. const struct = builder.getStructTypeNode( type );
  23407. let memberType;
  23408. if ( struct !== null ) {
  23409. memberType = struct.getMemberType( builder, name );
  23410. } else {
  23411. error( `TSL: Member "${ name }" not found in struct "${ type }".` );
  23412. memberType = 'float';
  23413. }
  23414. return memberType;
  23415. }
  23416. getHash() {
  23417. return this.uuid;
  23418. }
  23419. generate() {
  23420. return this.name;
  23421. }
  23422. }
  23423. /**
  23424. * TSL function for creating a parameter node.
  23425. *
  23426. * @tsl
  23427. * @function
  23428. * @param {string} type - The type of the node.
  23429. * @param {?string} name - The name of the parameter in the shader.
  23430. * @returns {ParameterNode}
  23431. */
  23432. const parameter = ( type, name ) => nodeObject( new ParameterNode( type, name ) );
  23433. /**
  23434. * Stack is a helper for Nodes that need to produce stack-based code instead of continuous flow.
  23435. * They are usually needed in cases like `If`, `Else`.
  23436. *
  23437. * @augments Node
  23438. */
  23439. class StackNode extends Node {
  23440. static get type() {
  23441. return 'StackNode';
  23442. }
  23443. /**
  23444. * Constructs a new stack node.
  23445. *
  23446. * @param {?StackNode} [parent=null] - The parent stack node.
  23447. */
  23448. constructor( parent = null ) {
  23449. super();
  23450. /**
  23451. * List of nodes.
  23452. *
  23453. * @type {Array<Node>}
  23454. */
  23455. this.nodes = [];
  23456. /**
  23457. * The output node.
  23458. *
  23459. * @type {?Node}
  23460. * @default null
  23461. */
  23462. this.outputNode = null;
  23463. /**
  23464. * The parent stack node.
  23465. *
  23466. * @type {?StackNode}
  23467. * @default null
  23468. */
  23469. this.parent = parent;
  23470. /**
  23471. * The current conditional node.
  23472. *
  23473. * @private
  23474. * @type {ConditionalNode}
  23475. * @default null
  23476. */
  23477. this._currentCond = null;
  23478. /**
  23479. * The expression node. Only
  23480. * relevant for Switch/Case.
  23481. *
  23482. * @private
  23483. * @type {Node}
  23484. * @default null
  23485. */
  23486. this._expressionNode = null;
  23487. /**
  23488. * The current node being processed.
  23489. *
  23490. * @private
  23491. * @type {Node}
  23492. * @default null
  23493. */
  23494. this._currentNode = null;
  23495. /**
  23496. * This flag can be used for type testing.
  23497. *
  23498. * @type {boolean}
  23499. * @readonly
  23500. * @default true
  23501. */
  23502. this.isStackNode = true;
  23503. }
  23504. getElementType( builder ) {
  23505. return this.hasOutput ? this.outputNode.getElementType( builder ) : 'void';
  23506. }
  23507. getNodeType( builder ) {
  23508. return this.hasOutput ? this.outputNode.getNodeType( builder ) : 'void';
  23509. }
  23510. getMemberType( builder, name ) {
  23511. return this.hasOutput ? this.outputNode.getMemberType( builder, name ) : 'void';
  23512. }
  23513. /**
  23514. * Adds a node to this stack.
  23515. *
  23516. * @param {Node} node - The node to add.
  23517. * @param {number} [index=this.nodes.length] - The index where the node should be added.
  23518. * @return {StackNode} A reference to this stack node.
  23519. */
  23520. addToStack( node, index = this.nodes.length ) {
  23521. if ( node.isNode !== true ) {
  23522. error( 'TSL: Invalid node added to stack.' );
  23523. return this;
  23524. }
  23525. this.nodes.splice( index, 0, node );
  23526. return this;
  23527. }
  23528. /**
  23529. * Adds a node to the stack before the current node.
  23530. *
  23531. * @param {Node} node - The node to add.
  23532. * @return {StackNode} A reference to this stack node.
  23533. */
  23534. addToStackBefore( node ) {
  23535. const index = this._currentNode ? this.nodes.indexOf( this._currentNode ) : 0;
  23536. return this.addToStack( node, index );
  23537. }
  23538. /**
  23539. * Represent an `if` statement in TSL.
  23540. *
  23541. * @param {Node} boolNode - Represents the condition.
  23542. * @param {Function} method - TSL code which is executed if the condition evaluates to `true`.
  23543. * @return {StackNode} A reference to this stack node.
  23544. */
  23545. If( boolNode, method ) {
  23546. const methodNode = new ShaderNode( method );
  23547. this._currentCond = select( boolNode, methodNode );
  23548. return this.addToStack( this._currentCond );
  23549. }
  23550. /**
  23551. * Represent an `elseif` statement in TSL.
  23552. *
  23553. * @param {Node} boolNode - Represents the condition.
  23554. * @param {Function} method - TSL code which is executed if the condition evaluates to `true`.
  23555. * @return {StackNode} A reference to this stack node.
  23556. */
  23557. ElseIf( boolNode, method ) {
  23558. const methodNode = new ShaderNode( method );
  23559. const ifNode = select( boolNode, methodNode );
  23560. this._currentCond.elseNode = ifNode;
  23561. this._currentCond = ifNode;
  23562. return this;
  23563. }
  23564. /**
  23565. * Represent an `else` statement in TSL.
  23566. *
  23567. * @param {Function} method - TSL code which is executed in the `else` case.
  23568. * @return {StackNode} A reference to this stack node.
  23569. */
  23570. Else( method ) {
  23571. this._currentCond.elseNode = new ShaderNode( method );
  23572. return this;
  23573. }
  23574. /**
  23575. * Represents a `switch` statement in TSL.
  23576. *
  23577. * @param {any} expression - Represents the expression.
  23578. * @param {Function} method - TSL code which is executed if the condition evaluates to `true`.
  23579. * @return {StackNode} A reference to this stack node.
  23580. */
  23581. Switch( expression ) {
  23582. this._expressionNode = nodeObject( expression );
  23583. return this;
  23584. }
  23585. /**
  23586. * Represents a `case` statement in TSL. The TSL version accepts an arbitrary numbers of values.
  23587. * The last parameter must be the callback method that should be executed in the `true` case.
  23588. *
  23589. * @param {...any} params - The values of the `Case()` statement as well as the callback method.
  23590. * @return {StackNode} A reference to this stack node.
  23591. */
  23592. Case( ...params ) {
  23593. const caseNodes = [];
  23594. // extract case nodes from the parameter list
  23595. if ( params.length >= 2 ) {
  23596. for ( let i = 0; i < params.length - 1; i ++ ) {
  23597. caseNodes.push( this._expressionNode.equal( nodeObject( params[ i ] ) ) );
  23598. }
  23599. } else {
  23600. error( 'TSL: Invalid parameter length. Case() requires at least two parameters.' );
  23601. }
  23602. // extract method
  23603. const method = params[ params.length - 1 ];
  23604. const methodNode = new ShaderNode( method );
  23605. // chain multiple cases when using Case( 1, 2, 3, () => {} )
  23606. let caseNode = caseNodes[ 0 ];
  23607. for ( let i = 1; i < caseNodes.length; i ++ ) {
  23608. caseNode = caseNode.or( caseNodes[ i ] );
  23609. }
  23610. // build condition
  23611. const condNode = select( caseNode, methodNode );
  23612. if ( this._currentCond === null ) {
  23613. this._currentCond = condNode;
  23614. return this.addToStack( this._currentCond );
  23615. } else {
  23616. this._currentCond.elseNode = condNode;
  23617. this._currentCond = condNode;
  23618. return this;
  23619. }
  23620. }
  23621. /**
  23622. * Represents the default code block of a Switch/Case statement.
  23623. *
  23624. * @param {Function} method - TSL code which is executed in the `else` case.
  23625. * @return {StackNode} A reference to this stack node.
  23626. */
  23627. Default( method ) {
  23628. this.Else( method );
  23629. return this;
  23630. }
  23631. setup( builder ) {
  23632. const nodeProperties = builder.getNodeProperties( this );
  23633. let index = 0;
  23634. for ( const childNode of this.getChildren() ) {
  23635. if ( childNode.isVarNode && childNode.isIntent( builder ) ) {
  23636. if ( childNode.isAssign( builder ) !== true ) {
  23637. continue;
  23638. }
  23639. }
  23640. nodeProperties[ 'node' + index ++ ] = childNode;
  23641. }
  23642. // return a outputNode if exists or null
  23643. return nodeProperties.outputNode || null;
  23644. }
  23645. get hasOutput() {
  23646. return this.outputNode && this.outputNode.isNode;
  23647. }
  23648. build( builder, ...params ) {
  23649. const previousStack = getCurrentStack();
  23650. const buildStage = builder.buildStage;
  23651. setCurrentStack( this );
  23652. builder.setActiveStack( this );
  23653. //
  23654. const buildNode = ( node ) => {
  23655. this._currentNode = node;
  23656. if ( node.isVarNode && node.isIntent( builder ) ) {
  23657. if ( node.isAssign( builder ) !== true ) {
  23658. return;
  23659. }
  23660. }
  23661. if ( buildStage === 'setup' ) {
  23662. node.build( builder );
  23663. } else if ( buildStage === 'analyze' ) {
  23664. node.build( builder, this );
  23665. } else if ( buildStage === 'generate' ) {
  23666. const stages = builder.getDataFromNode( node, 'any' ).stages;
  23667. const parents = stages && stages[ builder.shaderStage ];
  23668. if ( node.isVarNode && parents && parents.length === 1 && parents[ 0 ] && parents[ 0 ].isStackNode ) {
  23669. return; // skip var nodes that are only used in .toVarying()
  23670. }
  23671. node.build( builder, 'void' );
  23672. }
  23673. };
  23674. //
  23675. const nodes = [ ...this.nodes ];
  23676. for ( const node of nodes ) {
  23677. buildNode( node );
  23678. }
  23679. this._currentNode = null;
  23680. const newNodes = this.nodes.filter( ( node ) => nodes.indexOf( node ) === -1 );
  23681. for ( const node of newNodes ) {
  23682. buildNode( node );
  23683. }
  23684. //
  23685. let result;
  23686. if ( this.hasOutput ) {
  23687. result = this.outputNode.build( builder, ...params );
  23688. } else {
  23689. result = super.build( builder, ...params );
  23690. }
  23691. setCurrentStack( previousStack );
  23692. builder.removeActiveStack( this );
  23693. return result;
  23694. }
  23695. }
  23696. /**
  23697. * TSL function for creating a stack node.
  23698. *
  23699. * @tsl
  23700. * @function
  23701. * @param {?StackNode} [parent=null] - The parent stack node.
  23702. * @returns {StackNode}
  23703. */
  23704. const stack = /*@__PURE__*/ nodeProxy( StackNode ).setParameterLength( 0, 1 );
  23705. /**
  23706. * Generates a layout for struct members.
  23707. * This function takes an object representing struct members and returns an array of member layouts.
  23708. * Each member layout includes the member's name, type, and whether it is atomic.
  23709. *
  23710. * @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.
  23711. * @returns {Array.<{name: string, type: string, atomic: boolean}>} An array of member layouts.
  23712. */
  23713. function getMembersLayout( members ) {
  23714. return Object.entries( members ).map( ( [ name, value ] ) => {
  23715. if ( typeof value === 'string' ) {
  23716. return { name, type: value, atomic: false };
  23717. }
  23718. return { name, type: value.type, atomic: value.atomic || false };
  23719. } );
  23720. }
  23721. /**
  23722. * Represents a struct type node in the node-based system.
  23723. * This class is used to define and manage the layout and types of struct members.
  23724. * It extends the base Node class and provides methods to get the length of the struct,
  23725. * retrieve member types, and generate the struct type for a builder.
  23726. *
  23727. * @augments Node
  23728. */
  23729. class StructTypeNode extends Node {
  23730. static get type() {
  23731. return 'StructTypeNode';
  23732. }
  23733. /**
  23734. * Creates an instance of StructTypeNode.
  23735. *
  23736. * @param {Object} membersLayout - The layout of the members for the struct.
  23737. * @param {?string} [name=null] - The optional name of the struct.
  23738. */
  23739. constructor( membersLayout, name = null ) {
  23740. super( 'struct' );
  23741. /**
  23742. * The layout of the members for the struct
  23743. *
  23744. * @type {Array.<{name: string, type: string, atomic: boolean}>}
  23745. */
  23746. this.membersLayout = getMembersLayout( membersLayout );
  23747. /**
  23748. * The name of the struct.
  23749. *
  23750. * @type {?string}
  23751. * @default null
  23752. */
  23753. this.name = name;
  23754. /**
  23755. * This flag can be used for type testing.
  23756. *
  23757. * @type {boolean}
  23758. * @readonly
  23759. * @default true
  23760. */
  23761. this.isStructLayoutNode = true;
  23762. }
  23763. /**
  23764. * Returns the length of the struct.
  23765. * The length is calculated by summing the lengths of the struct's members.
  23766. *
  23767. * @returns {number} The length of the struct.
  23768. */
  23769. getLength() {
  23770. const BYTES_PER_ELEMENT = Float32Array.BYTES_PER_ELEMENT;
  23771. let maxAlignment = 1; // maximum alignment value in this struct
  23772. let offset = 0; // global buffer offset in 4 byte elements
  23773. for ( const member of this.membersLayout ) {
  23774. const type = member.type;
  23775. const itemSize = getMemoryLengthFromType( type );
  23776. const alignment = getAlignmentFromType( type ) / BYTES_PER_ELEMENT;
  23777. maxAlignment = Math.max( maxAlignment, alignment );
  23778. const chunkOffset = offset % maxAlignment; // offset in the current chunk of maxAlignment elements
  23779. const overhang = chunkOffset % alignment; // distance from the last aligned offset
  23780. if ( overhang !== 0 ) {
  23781. offset += alignment - overhang; // move to next aligned offset
  23782. }
  23783. offset += itemSize;
  23784. }
  23785. return ( Math.ceil( offset / maxAlignment ) * maxAlignment ); // ensure length is a multiple of maxAlignment
  23786. }
  23787. getMemberType( builder, name ) {
  23788. const member = this.membersLayout.find( m => m.name === name );
  23789. return member ? member.type : 'void';
  23790. }
  23791. getNodeType( builder ) {
  23792. const structType = builder.getStructTypeFromNode( this, this.membersLayout, this.name );
  23793. return structType.name;
  23794. }
  23795. setup( builder ) {
  23796. builder.getStructTypeFromNode( this, this.membersLayout, this.name );
  23797. builder.addInclude( this );
  23798. }
  23799. generate( builder ) {
  23800. return this.getNodeType( builder );
  23801. }
  23802. }
  23803. /**
  23804. * StructNode allows to create custom structures with multiple members.
  23805. * This can also be used to define structures in attribute and uniform data.
  23806. *
  23807. * ```js
  23808. * // Define a custom struct
  23809. * const BoundingBox = struct( { min: 'vec3', max: 'vec3' } );
  23810. *
  23811. * // Create a new instance of the struct
  23812. * const bb = BoundingBox( vec3( 0 ), vec3( 1 ) ); // style 1
  23813. * const bb = BoundingBox( { min: vec3( 0 ), max: vec3( 1 ) } ); // style 2
  23814. *
  23815. * // Access the struct members
  23816. * const min = bb.get( 'min' );
  23817. *
  23818. * // Assign a new value to a member
  23819. * min.assign( vec3() );
  23820. * ```
  23821. * @augments Node
  23822. */
  23823. class StructNode extends Node {
  23824. static get type() {
  23825. return 'StructNode';
  23826. }
  23827. constructor( structTypeNode, values ) {
  23828. super( 'vec3' );
  23829. this.structTypeNode = structTypeNode;
  23830. this.values = values;
  23831. this.isStructNode = true;
  23832. }
  23833. getNodeType( builder ) {
  23834. return this.structTypeNode.getNodeType( builder );
  23835. }
  23836. getMemberType( builder, name ) {
  23837. return this.structTypeNode.getMemberType( builder, name );
  23838. }
  23839. generate( builder ) {
  23840. const nodeVar = builder.getVarFromNode( this );
  23841. const structType = nodeVar.type;
  23842. const propertyName = builder.getPropertyName( nodeVar );
  23843. builder.addLineFlowCode( `${ propertyName } = ${ builder.generateStruct( structType, this.structTypeNode.membersLayout, this.values ) }`, this );
  23844. return nodeVar.name;
  23845. }
  23846. }
  23847. /**
  23848. * TSL function for creating a struct node.
  23849. *
  23850. * @tsl
  23851. * @function
  23852. * @param {Object} membersLayout - The layout of the struct members.
  23853. * @param {?string} [name=null] - The name of the struct.
  23854. * @returns {Function} The struct function.
  23855. */
  23856. const struct = ( membersLayout, name = null ) => {
  23857. const structLayout = new StructTypeNode( membersLayout, name );
  23858. const struct = ( ...params ) => {
  23859. let values = null;
  23860. if ( params.length > 0 ) {
  23861. if ( params[ 0 ].isNode ) {
  23862. values = {};
  23863. const names = Object.keys( membersLayout );
  23864. for ( let i = 0; i < params.length; i ++ ) {
  23865. values[ names[ i ] ] = params[ i ];
  23866. }
  23867. } else {
  23868. values = params[ 0 ];
  23869. }
  23870. }
  23871. return nodeObject( new StructNode( structLayout, values ) );
  23872. };
  23873. struct.layout = structLayout;
  23874. struct.isStruct = true;
  23875. return struct;
  23876. };
  23877. /**
  23878. * This node can be used to define multiple outputs in a shader programs.
  23879. *
  23880. * @augments Node
  23881. */
  23882. class OutputStructNode extends Node {
  23883. static get type() {
  23884. return 'OutputStructNode';
  23885. }
  23886. /**
  23887. * Constructs a new output struct node. The constructor can be invoked with an
  23888. * arbitrary number of nodes representing the members.
  23889. *
  23890. * @param {...Node} members - A parameter list of nodes.
  23891. */
  23892. constructor( ...members ) {
  23893. super();
  23894. /**
  23895. * An array of nodes which defines the output.
  23896. *
  23897. * @type {Array<Node>}
  23898. */
  23899. this.members = members;
  23900. /**
  23901. * This flag can be used for type testing.
  23902. *
  23903. * @type {boolean}
  23904. * @readonly
  23905. * @default true
  23906. */
  23907. this.isOutputStructNode = true;
  23908. }
  23909. getNodeType( builder ) {
  23910. const properties = builder.getNodeProperties( this );
  23911. if ( properties.membersLayout === undefined ) {
  23912. const members = this.members;
  23913. const membersLayout = [];
  23914. for ( let i = 0; i < members.length; i ++ ) {
  23915. const name = 'm' + i;
  23916. const type = members[ i ].getNodeType( builder );
  23917. membersLayout.push( { name, type, index: i } );
  23918. }
  23919. properties.membersLayout = membersLayout;
  23920. properties.structType = builder.getOutputStructTypeFromNode( this, properties.membersLayout );
  23921. }
  23922. return properties.structType.name;
  23923. }
  23924. generate( builder ) {
  23925. const propertyName = builder.getOutputStructName();
  23926. const members = this.members;
  23927. const structPrefix = propertyName !== '' ? propertyName + '.' : '';
  23928. for ( let i = 0; i < members.length; i ++ ) {
  23929. const snippet = members[ i ].build( builder );
  23930. builder.addLineFlowCode( `${ structPrefix }m${ i } = ${ snippet }`, this );
  23931. }
  23932. return propertyName;
  23933. }
  23934. }
  23935. /**
  23936. * TSL function for creating an output struct node.
  23937. *
  23938. * @tsl
  23939. * @function
  23940. * @param {...Node} members - A parameter list of nodes.
  23941. * @returns {OutputStructNode}
  23942. */
  23943. const outputStruct = /*@__PURE__*/ nodeProxy( OutputStructNode );
  23944. /**
  23945. * Returns the MRT texture index for the given name.
  23946. *
  23947. * @param {Array<Texture>} textures - The textures of a MRT-configured render target.
  23948. * @param {string} name - The name of the MRT texture which index is requested.
  23949. * @return {number} The texture index.
  23950. */
  23951. function getTextureIndex( textures, name ) {
  23952. for ( let i = 0; i < textures.length; i ++ ) {
  23953. if ( textures[ i ].name === name ) {
  23954. return i;
  23955. }
  23956. }
  23957. return -1;
  23958. }
  23959. /**
  23960. * This node can be used setup a MRT context for rendering. A typical MRT setup for
  23961. * post-processing is shown below:
  23962. * ```js
  23963. * const mrtNode = mrt( {
  23964. * output: output,
  23965. * normal: normalView
  23966. * } ) );
  23967. * ```
  23968. * The MRT output is defined as a dictionary.
  23969. *
  23970. * @augments OutputStructNode
  23971. */
  23972. class MRTNode extends OutputStructNode {
  23973. static get type() {
  23974. return 'MRTNode';
  23975. }
  23976. /**
  23977. * Constructs a new output struct node.
  23978. *
  23979. * @param {Object<string, Node>} outputNodes - The MRT outputs.
  23980. */
  23981. constructor( outputNodes ) {
  23982. super();
  23983. /**
  23984. * A dictionary representing the MRT outputs. The key
  23985. * is the name of the output, the value the node which produces
  23986. * the output result.
  23987. *
  23988. * @type {Object<string, Node>}
  23989. */
  23990. this.outputNodes = outputNodes;
  23991. /**
  23992. * This flag can be used for type testing.
  23993. *
  23994. * @type {boolean}
  23995. * @readonly
  23996. * @default true
  23997. */
  23998. this.isMRTNode = true;
  23999. }
  24000. /**
  24001. * Returns `true` if the MRT node has an output with the given name.
  24002. *
  24003. * @param {string} name - The name of the output.
  24004. * @return {NodeBuilder} Whether the MRT node has an output for the given name or not.
  24005. */
  24006. has( name ) {
  24007. return this.outputNodes[ name ] !== undefined;
  24008. }
  24009. /**
  24010. * Returns the output node for the given name.
  24011. *
  24012. * @param {string} name - The name of the output.
  24013. * @return {Node} The output node.
  24014. */
  24015. get( name ) {
  24016. return this.outputNodes[ name ];
  24017. }
  24018. /**
  24019. * Merges the outputs of the given MRT node with the outputs of this node.
  24020. *
  24021. * @param {MRTNode} mrtNode - The MRT to merge.
  24022. * @return {MRTNode} A new MRT node with merged outputs..
  24023. */
  24024. merge( mrtNode ) {
  24025. const outputs = { ...this.outputNodes, ...mrtNode.outputNodes };
  24026. return mrt( outputs );
  24027. }
  24028. setup( builder ) {
  24029. const outputNodes = this.outputNodes;
  24030. const mrt = builder.renderer.getRenderTarget();
  24031. const members = [];
  24032. const textures = mrt.textures;
  24033. for ( const name in outputNodes ) {
  24034. const index = getTextureIndex( textures, name );
  24035. members[ index ] = vec4( outputNodes[ name ] );
  24036. }
  24037. this.members = members;
  24038. return super.setup( builder );
  24039. }
  24040. }
  24041. /**
  24042. * TSL function for creating a MRT node.
  24043. *
  24044. * @tsl
  24045. * @function
  24046. * @param {Object<string, Node>} outputNodes - The MRT outputs.
  24047. * @returns {MRTNode}
  24048. */
  24049. const mrt = /*@__PURE__*/ nodeProxy( MRTNode );
  24050. /**
  24051. * This node represents an operation that reinterprets the bit representation of a value
  24052. * in one type as a value in another type.
  24053. *
  24054. * @augments TempNode
  24055. */
  24056. class BitcastNode extends TempNode {
  24057. static get type() {
  24058. return 'BitcastNode';
  24059. }
  24060. /**
  24061. * Constructs a new bitcast node.
  24062. *
  24063. * @param {Node} valueNode - The value to convert.
  24064. * @param {string} conversionType - The type to convert to.
  24065. * @param {?string} [inputType = null] - The expected input data type of the bitcast operation.
  24066. */
  24067. constructor( valueNode, conversionType, inputType = null ) {
  24068. super();
  24069. /**
  24070. * The data to bitcast to a new type.
  24071. *
  24072. * @type {Node}
  24073. */
  24074. this.valueNode = valueNode;
  24075. /**
  24076. * The type the value will be converted to.
  24077. *
  24078. * @type {string}
  24079. */
  24080. this.conversionType = conversionType;
  24081. /**
  24082. * The expected input data type of the bitcast operation.
  24083. *
  24084. *
  24085. * @type {string}
  24086. * @default null
  24087. */
  24088. this.inputType = inputType;
  24089. /**
  24090. * This flag can be used for type testing.
  24091. *
  24092. * @type {boolean}
  24093. * @readonly
  24094. * @default true
  24095. */
  24096. this.isBitcastNode = true;
  24097. }
  24098. getNodeType( builder ) {
  24099. // GLSL aliasing
  24100. if ( this.inputType !== null ) {
  24101. const valueType = this.valueNode.getNodeType( builder );
  24102. const valueLength = builder.getTypeLength( valueType );
  24103. return builder.getTypeFromLength( valueLength, this.conversionType );
  24104. }
  24105. return this.conversionType;
  24106. }
  24107. generate( builder ) {
  24108. const type = this.getNodeType( builder );
  24109. let inputType = '';
  24110. if ( this.inputType !== null ) {
  24111. const valueType = this.valueNode.getNodeType( builder );
  24112. const valueTypeLength = builder.getTypeLength( valueType );
  24113. inputType = valueTypeLength === 1 ? this.inputType : builder.changeComponentType( valueType, this.inputType );
  24114. } else {
  24115. inputType = this.valueNode.getNodeType( builder );
  24116. }
  24117. return `${ builder.getBitcastMethod( type, inputType ) }( ${ this.valueNode.build( builder, inputType ) } )`;
  24118. }
  24119. }
  24120. /**
  24121. * Reinterpret the bit representation of a value in one type as a value in another type.
  24122. *
  24123. * @tsl
  24124. * @function
  24125. * @param {Node | number} x - The parameter.
  24126. * @param {string} y - The new type.
  24127. * @returns {Node}
  24128. */
  24129. const bitcast = /*@__PURE__*/ nodeProxyIntent( BitcastNode ).setParameterLength( 2 );
  24130. /**
  24131. * Bitcasts a float or a vector of floats to a corresponding integer type with the same element size.
  24132. *
  24133. * @tsl
  24134. * @function
  24135. * @param {Node<float>} value - The float or vector of floats to bitcast.
  24136. * @returns {BitcastNode}
  24137. */
  24138. const floatBitsToInt = ( value ) => new BitcastNode( value, 'int', 'float' );
  24139. /**
  24140. * Bitcasts a float or a vector of floats to a corresponding unsigned integer type with the same element size.
  24141. *
  24142. * @tsl
  24143. * @function
  24144. * @param {Node<float>} value - The float or vector of floats to bitcast.
  24145. * @returns {BitcastNode}
  24146. */
  24147. const floatBitsToUint = ( value ) => new BitcastNode( value, 'uint', 'float' );
  24148. /**
  24149. * Bitcasts an integer or a vector of integers to a corresponding float type with the same element size.
  24150. *
  24151. * @tsl
  24152. * @function
  24153. * @param {Node<int>} value - The integer or vector of integers to bitcast.
  24154. * @returns {BitcastNode}
  24155. */
  24156. const intBitsToFloat = ( value ) => new BitcastNode( value, 'float', 'int' );
  24157. /**
  24158. * Bitcast an unsigned integer or a vector of unsigned integers to a corresponding float type with the same element size.
  24159. *
  24160. * @tsl
  24161. * @function
  24162. * @param {Node<uint>} value - The unsigned integer or vector of unsigned integers to bitcast.
  24163. * @returns {BitcastNode}
  24164. */
  24165. const uintBitsToFloat = ( value ) => new BitcastNode( value, 'float', 'uint' );
  24166. const registeredBitcountFunctions = {};
  24167. /**
  24168. * This node represents an operation that counts the bits of a piece of shader data.
  24169. *
  24170. * @augments MathNode
  24171. */
  24172. class BitcountNode extends MathNode {
  24173. static get type() {
  24174. return 'BitcountNode';
  24175. }
  24176. /**
  24177. * Constructs a new math node.
  24178. *
  24179. * @param {'countTrailingZeros'|'countLeadingZeros'|'countOneBits'} method - The method name.
  24180. * @param {Node} aNode - The first input.
  24181. */
  24182. constructor( method, aNode ) {
  24183. super( method, aNode );
  24184. /**
  24185. * This flag can be used for type testing.
  24186. *
  24187. * @type {boolean}
  24188. * @readonly
  24189. * @default true
  24190. */
  24191. this.isBitcountNode = true;
  24192. }
  24193. /**
  24194. * Casts the input value of the function to an integer if necessary.
  24195. *
  24196. * @private
  24197. * @param {Node<uint>|Node<int>} inputNode - The input value.
  24198. * @param {Node<uint>} outputNode - The output value.
  24199. * @param {string} elementType - The type of the input value.
  24200. */
  24201. _resolveElementType( inputNode, outputNode, elementType ) {
  24202. if ( elementType === 'int' ) {
  24203. outputNode.assign( bitcast( inputNode, 'uint' ) );
  24204. } else {
  24205. outputNode.assign( inputNode );
  24206. }
  24207. }
  24208. _returnDataNode( inputType ) {
  24209. switch ( inputType ) {
  24210. case 'uint': {
  24211. return uint;
  24212. }
  24213. case 'int': {
  24214. return int;
  24215. }
  24216. case 'uvec2': {
  24217. return uvec2;
  24218. }
  24219. case 'uvec3': {
  24220. return uvec3;
  24221. }
  24222. case 'uvec4': {
  24223. return uvec4;
  24224. }
  24225. case 'ivec2': {
  24226. return ivec2;
  24227. }
  24228. case 'ivec3': {
  24229. return ivec3;
  24230. }
  24231. case 'ivec4': {
  24232. return ivec4;
  24233. }
  24234. }
  24235. }
  24236. /**
  24237. * Creates and registers a reusable GLSL function that emulates the behavior of countTrailingZeros.
  24238. *
  24239. * @private
  24240. * @param {string} method - The name of the function to create.
  24241. * @param {string} elementType - The type of the input value.
  24242. * @returns {Function} - The generated function
  24243. */
  24244. _createTrailingZerosBaseLayout( method, elementType ) {
  24245. const outputConvertNode = this._returnDataNode( elementType );
  24246. const fnDef = Fn( ( [ value ] ) => {
  24247. const v = uint( 0.0 );
  24248. this._resolveElementType( value, v, elementType );
  24249. const f = float( v.bitAnd( negate( v ) ) );
  24250. const uintBits = floatBitsToUint( f );
  24251. const numTrailingZeros = ( uintBits.shiftRight( 23 ) ).sub( 127 );
  24252. return outputConvertNode( numTrailingZeros );
  24253. } ).setLayout( {
  24254. name: method,
  24255. type: elementType,
  24256. inputs: [
  24257. { name: 'value', type: elementType }
  24258. ]
  24259. } );
  24260. return fnDef;
  24261. }
  24262. /**
  24263. * Creates and registers a reusable GLSL function that emulates the behavior of countLeadingZeros.
  24264. *
  24265. * @private
  24266. * @param {string} method - The name of the function to create.
  24267. * @param {string} elementType - The type of the input value.
  24268. * @returns {Function} - The generated function
  24269. */
  24270. _createLeadingZerosBaseLayout( method, elementType ) {
  24271. const outputConvertNode = this._returnDataNode( elementType );
  24272. const fnDef = Fn( ( [ value ] ) => {
  24273. If( value.equal( uint( 0 ) ), () => {
  24274. return uint( 32 );
  24275. } );
  24276. const v = uint( 0 );
  24277. const n = uint( 0 );
  24278. this._resolveElementType( value, v, elementType );
  24279. If( v.shiftRight( 16 ).equal( 0 ), () => {
  24280. n.addAssign( 16 );
  24281. v.shiftLeftAssign( 16 );
  24282. } );
  24283. If( v.shiftRight( 24 ).equal( 0 ), () => {
  24284. n.addAssign( 8 );
  24285. v.shiftLeftAssign( 8 );
  24286. } );
  24287. If( v.shiftRight( 28 ).equal( 0 ), () => {
  24288. n.addAssign( 4 );
  24289. v.shiftLeftAssign( 4 );
  24290. } );
  24291. If( v.shiftRight( 30 ).equal( 0 ), () => {
  24292. n.addAssign( 2 );
  24293. v.shiftLeftAssign( 2 );
  24294. } );
  24295. If( v.shiftRight( 31 ).equal( 0 ), () => {
  24296. n.addAssign( 1 );
  24297. } );
  24298. return outputConvertNode( n );
  24299. } ).setLayout( {
  24300. name: method,
  24301. type: elementType,
  24302. inputs: [
  24303. { name: 'value', type: elementType }
  24304. ]
  24305. } );
  24306. return fnDef;
  24307. }
  24308. /**
  24309. * Creates and registers a reusable GLSL function that emulates the behavior of countOneBits.
  24310. *
  24311. * @private
  24312. * @param {string} method - The name of the function to create.
  24313. * @param {string} elementType - The type of the input value.
  24314. * @returns {Function} - The generated function
  24315. */
  24316. _createOneBitsBaseLayout( method, elementType ) {
  24317. const outputConvertNode = this._returnDataNode( elementType );
  24318. const fnDef = Fn( ( [ value ] ) => {
  24319. const v = uint( 0.0 );
  24320. this._resolveElementType( value, v, elementType );
  24321. v.assign( v.sub( v.shiftRight( uint( 1 ) ).bitAnd( uint( 0x55555555 ) ) ) );
  24322. v.assign( v.bitAnd( uint( 0x33333333 ) ).add( v.shiftRight( uint( 2 ) ).bitAnd( uint( 0x33333333 ) ) ) );
  24323. const numBits = v.add( v.shiftRight( uint( 4 ) ) ).bitAnd( uint( 0xF0F0F0F ) ).mul( uint( 0x1010101 ) ).shiftRight( uint( 24 ) );
  24324. return outputConvertNode( numBits );
  24325. } ).setLayout( {
  24326. name: method,
  24327. type: elementType,
  24328. inputs: [
  24329. { name: 'value', type: elementType }
  24330. ]
  24331. } );
  24332. return fnDef;
  24333. }
  24334. /**
  24335. * Creates and registers a reusable GLSL function that emulates the behavior of the specified bitcount function.
  24336. * including considerations for component-wise bitcounts on vector type inputs.
  24337. *
  24338. * @private
  24339. * @param {string} method - The name of the function to create.
  24340. * @param {string} inputType - The type of the input value.
  24341. * @param {number} typeLength - The vec length of the input value.
  24342. * @param {Function} baseFn - The base function that operates on an individual component of the vector.
  24343. * @returns {Function} - The alias function for the specified bitcount method.
  24344. */
  24345. _createMainLayout( method, inputType, typeLength, baseFn ) {
  24346. const outputConvertNode = this._returnDataNode( inputType );
  24347. const fnDef = Fn( ( [ value ] ) => {
  24348. if ( typeLength === 1 ) {
  24349. return outputConvertNode( baseFn( value ) );
  24350. } else {
  24351. const vec = outputConvertNode( 0 );
  24352. const components = [ 'x', 'y', 'z', 'w' ];
  24353. for ( let i = 0; i < typeLength; i ++ ) {
  24354. const component = components[ i ];
  24355. vec[ component ].assign( baseFn( value[ component ] ) );
  24356. }
  24357. return vec;
  24358. }
  24359. } ).setLayout( {
  24360. name: method,
  24361. type: inputType,
  24362. inputs: [
  24363. { name: 'value', type: inputType }
  24364. ]
  24365. } );
  24366. return fnDef;
  24367. }
  24368. setup( builder ) {
  24369. const { method, aNode } = this;
  24370. const { renderer } = builder;
  24371. if ( renderer.backend.isWebGPUBackend ) {
  24372. // use built-in WGSL functions for WebGPU
  24373. return super.setup( builder );
  24374. }
  24375. const inputType = this.getInputType( builder );
  24376. const elementType = builder.getElementType( inputType );
  24377. const typeLength = builder.getTypeLength( inputType );
  24378. const baseMethod = `${method}_base_${elementType}`;
  24379. const newMethod = `${method}_${inputType}`;
  24380. let baseFn = registeredBitcountFunctions[ baseMethod ];
  24381. if ( baseFn === undefined ) {
  24382. switch ( method ) {
  24383. case BitcountNode.COUNT_LEADING_ZEROS: {
  24384. baseFn = this._createLeadingZerosBaseLayout( baseMethod, elementType );
  24385. break;
  24386. }
  24387. case BitcountNode.COUNT_TRAILING_ZEROS: {
  24388. baseFn = this._createTrailingZerosBaseLayout( baseMethod, elementType );
  24389. break;
  24390. }
  24391. case BitcountNode.COUNT_ONE_BITS: {
  24392. baseFn = this._createOneBitsBaseLayout( baseMethod, elementType );
  24393. break;
  24394. }
  24395. }
  24396. registeredBitcountFunctions[ baseMethod ] = baseFn;
  24397. }
  24398. let fn = registeredBitcountFunctions[ newMethod ];
  24399. if ( fn === undefined ) {
  24400. fn = this._createMainLayout( newMethod, inputType, typeLength, baseFn );
  24401. registeredBitcountFunctions[ newMethod ] = fn;
  24402. }
  24403. const output = Fn( () => {
  24404. return fn(
  24405. aNode,
  24406. );
  24407. } );
  24408. return output();
  24409. }
  24410. }
  24411. BitcountNode.COUNT_TRAILING_ZEROS = 'countTrailingZeros';
  24412. BitcountNode.COUNT_LEADING_ZEROS = 'countLeadingZeros';
  24413. BitcountNode.COUNT_ONE_BITS = 'countOneBits';
  24414. /**
  24415. * Finds the number of consecutive 0 bits from the least significant bit of the input value,
  24416. * which is also the index of the least significant bit of the input value.
  24417. *
  24418. * Can only be used with {@link WebGPURenderer} and a WebGPU backend.
  24419. *
  24420. * @tsl
  24421. * @function
  24422. * @param {Node | number} x - The input value.
  24423. * @returns {Node}
  24424. */
  24425. const countTrailingZeros = /*@__PURE__*/ nodeProxyIntent( BitcountNode, BitcountNode.COUNT_TRAILING_ZEROS ).setParameterLength( 1 );
  24426. /**
  24427. * Finds the number of consecutive 0 bits starting from the most significant bit of the input value.
  24428. *
  24429. * Can only be used with {@link WebGPURenderer} and a WebGPU backend.
  24430. *
  24431. * @tsl
  24432. * @function
  24433. * @param {Node | number} x - The input value.
  24434. * @returns {Node}
  24435. */
  24436. const countLeadingZeros = /*@__PURE__*/ nodeProxyIntent( BitcountNode, BitcountNode.COUNT_LEADING_ZEROS ).setParameterLength( 1 );
  24437. /**
  24438. * Finds the number of '1' bits set in the input value
  24439. *
  24440. * Can only be used with {@link WebGPURenderer} and a WebGPU backend.
  24441. *
  24442. * @tsl
  24443. * @function
  24444. * @returns {Node}
  24445. */
  24446. const countOneBits = /*@__PURE__*/ nodeProxyIntent( BitcountNode, BitcountNode.COUNT_ONE_BITS ).setParameterLength( 1 );
  24447. /**
  24448. * Generates a hash value in the range `[0, 1]` from the given seed.
  24449. *
  24450. * @tsl
  24451. * @function
  24452. * @param {Node<float>} seed - The seed.
  24453. * @return {Node<float>} The hash value.
  24454. */
  24455. const hash = /*@__PURE__*/ Fn( ( [ seed ] ) => {
  24456. // Taken from https://www.shadertoy.com/view/XlGcRh, originally from pcg-random.org
  24457. const state = seed.toUint().mul( 747796405 ).add( 2891336453 );
  24458. const word = state.shiftRight( state.shiftRight( 28 ).add( 4 ) ).bitXor( state ).mul( 277803737 );
  24459. const result = word.shiftRight( 22 ).bitXor( word );
  24460. return result.toFloat().mul( 1 / 2 ** 32 ); // Convert to range [0, 1)
  24461. } );
  24462. /**
  24463. * A function that remaps the `[0,1]` interval into the `[0,1]` interval.
  24464. * The corners are mapped to `0` and the center to `1`.
  24465. * Reference: {@link https://iquilezles.org/articles/functions/}.
  24466. *
  24467. * @tsl
  24468. * @function
  24469. * @param {Node<float>} x - The value to remap.
  24470. * @param {Node<float>} k - Allows to control the remapping functions shape by rising the parabola to a power `k`.
  24471. * @return {Node<float>} The remapped value.
  24472. */
  24473. const parabola = ( x, k ) => pow( mul( 4.0, x.mul( sub( 1.0, x ) ) ), k );
  24474. /**
  24475. * A function that remaps the `[0,1]` interval into the `[0,1]` interval.
  24476. * Expands the sides and compresses the center, and keeps `0.5` mapped to `0.5`.
  24477. * Reference: {@link https://iquilezles.org/articles/functions/}.
  24478. *
  24479. * @tsl
  24480. * @function
  24481. * @param {Node<float>} x - The value to remap.
  24482. * @param {Node<float>} k - `k=1` is the identity curve,`k<1` produces the classic `gain()` shape, and `k>1` produces "s" shaped curves.
  24483. * @return {Node<float>} The remapped value.
  24484. */
  24485. 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 ) );
  24486. /**
  24487. * A function that remaps the `[0,1]` interval into the `[0,1]` interval.
  24488. * A generalization of the `parabola()`. Keeps the corners mapped to 0 but allows the control of the shape one either side of the curve.
  24489. * Reference: {@link https://iquilezles.org/articles/functions/}.
  24490. *
  24491. * @tsl
  24492. * @function
  24493. * @param {Node<float>} x - The value to remap.
  24494. * @param {Node<float>} a - First control parameter.
  24495. * @param {Node<float>} b - Second control parameter.
  24496. * @return {Node<float>} The remapped value.
  24497. */
  24498. const pcurve = ( x, a, b ) => pow( div( pow( x, a ), add( pow( x, a ), pow( sub( 1.0, x ), b ) ) ), 1.0 / a );
  24499. /**
  24500. * A phase shifted sinus curve that starts at zero and ends at zero, with bouncing behavior.
  24501. * Reference: {@link https://iquilezles.org/articles/functions/}.
  24502. *
  24503. * @tsl
  24504. * @function
  24505. * @param {Node<float>} x - The value to compute the sin for.
  24506. * @param {Node<float>} k - Controls the amount of bounces.
  24507. * @return {Node<float>} The result value.
  24508. */
  24509. const sinc = ( x, k ) => sin( PI.mul( k.mul( x ).sub( 1.0 ) ) ).div( PI.mul( k.mul( x ).sub( 1.0 ) ) );
  24510. /**
  24511. * This node represents an operation that packs floating-point values of a vector into an unsigned 32-bit integer
  24512. *
  24513. * @augments TempNode
  24514. */
  24515. class PackFloatNode extends TempNode {
  24516. static get type() {
  24517. return 'PackFloatNode';
  24518. }
  24519. /**
  24520. *
  24521. * @param {'snorm' | 'unorm' | 'float16'} encoding - The numeric encoding that describes how the float values are mapped to the integer range.
  24522. * @param {Node} vectorNode - The vector node to be packed
  24523. */
  24524. constructor( encoding, vectorNode ) {
  24525. super();
  24526. /**
  24527. * The vector to be packed.
  24528. *
  24529. * @type {Node}
  24530. */
  24531. this.vectorNode = vectorNode;
  24532. /**
  24533. * The numeric encoding.
  24534. *
  24535. * @type {string}
  24536. */
  24537. this.encoding = encoding;
  24538. /**
  24539. * This flag can be used for type testing.
  24540. *
  24541. * @type {boolean}
  24542. * @readonly
  24543. * @default true
  24544. */
  24545. this.isPackFloatNode = true;
  24546. }
  24547. getNodeType() {
  24548. return 'uint';
  24549. }
  24550. generate( builder ) {
  24551. const inputType = this.vectorNode.getNodeType( builder );
  24552. return `${ builder.getFloatPackingMethod( this.encoding ) }(${ this.vectorNode.build( builder, inputType )})`;
  24553. }
  24554. }
  24555. /**
  24556. * Converts each component of the normalized float to 16-bit integer values. The results are packed into a single unsigned integer.
  24557. * round(clamp(c, -1, +1) * 32767.0)
  24558. *
  24559. * @tsl
  24560. * @function
  24561. * @param {Node<vec2>} value - The 2-component vector to be packed
  24562. * @returns {Node}
  24563. */
  24564. const packSnorm2x16 = /*@__PURE__*/ nodeProxyIntent( PackFloatNode, 'snorm' ).setParameterLength( 1 );
  24565. /**
  24566. * Converts each component of the normalized float to 16-bit integer values. The results are packed into a single unsigned integer.
  24567. * round(clamp(c, 0, +1) * 65535.0)
  24568. *
  24569. * @tsl
  24570. * @function
  24571. * @param {Node<vec2>} value - The 2-component vector to be packed
  24572. * @returns {Node}
  24573. */
  24574. const packUnorm2x16 = /*@__PURE__*/ nodeProxyIntent( PackFloatNode, 'unorm' ).setParameterLength( 1 );
  24575. /**
  24576. * Converts each component of the vec2 to 16-bit floating-point values. The results are packed into a single unsigned integer.
  24577. *
  24578. * @tsl
  24579. * @function
  24580. * @param {Node<vec2>} value - The 2-component vector to be packed
  24581. * @returns {Node}
  24582. */
  24583. const packHalf2x16 = /*@__PURE__*/ nodeProxyIntent( PackFloatNode, 'float16' ).setParameterLength( 1 );
  24584. /**
  24585. * This node represents an operation that unpacks values from a 32-bit unsigned integer, reinterpreting the results as a floating-point vector
  24586. *
  24587. * @augments TempNode
  24588. */
  24589. class UnpackFloatNode extends TempNode {
  24590. static get type() {
  24591. return 'UnpackFloatNode';
  24592. }
  24593. /**
  24594. *
  24595. * @param {'snorm' | 'unorm' | 'float16'} encoding - The numeric encoding that describes how the integer values are mapped to the float range
  24596. * @param {Node} uintNode - The uint node to be unpacked
  24597. */
  24598. constructor( encoding, uintNode ) {
  24599. super();
  24600. /**
  24601. * The unsigned integer to be unpacked.
  24602. *
  24603. * @type {Node}
  24604. */
  24605. this.uintNode = uintNode;
  24606. /**
  24607. * The numeric encoding.
  24608. *
  24609. * @type {string}
  24610. */
  24611. this.encoding = encoding;
  24612. /**
  24613. * This flag can be used for type testing.
  24614. *
  24615. * @type {boolean}
  24616. * @readonly
  24617. * @default true
  24618. */
  24619. this.isUnpackFloatNode = true;
  24620. }
  24621. getNodeType() {
  24622. return 'vec2';
  24623. }
  24624. generate( builder ) {
  24625. const inputType = this.uintNode.getNodeType( builder );
  24626. return `${ builder.getFloatUnpackingMethod( this.encoding ) }(${ this.uintNode.build( builder, inputType )})`;
  24627. }
  24628. }
  24629. /**
  24630. * Unpacks a 32-bit unsigned integer into two 16-bit values, interpreted as normalized signed integers. Returns a vec2 with both values.
  24631. *
  24632. * @tsl
  24633. * @function
  24634. * @param {Node<uint>} value - The unsigned integer to be unpacked
  24635. * @returns {Node}
  24636. */
  24637. const unpackSnorm2x16 = /*@__PURE__*/ nodeProxyIntent( UnpackFloatNode, 'snorm' ).setParameterLength( 1 );
  24638. /**
  24639. * Unpacks a 32-bit unsigned integer into two 16-bit values, interpreted as normalized unsigned integers. Returns a vec2 with both values.
  24640. *
  24641. * @tsl
  24642. * @function
  24643. * @param {Node<uint>} value - The unsigned integer to be unpacked
  24644. * @returns {Node}
  24645. */
  24646. const unpackUnorm2x16 = /*@__PURE__*/ nodeProxyIntent( UnpackFloatNode, 'unorm' ).setParameterLength( 1 );
  24647. /**
  24648. * Unpacks a 32-bit unsigned integer into two 16-bit values, interpreted as 16-bit floating-point numbers. Returns a vec2 with both values.
  24649. *
  24650. * @tsl
  24651. * @function
  24652. * @param {Node<uint>} value - The unsigned integer to be unpacked
  24653. * @returns {Node}
  24654. */
  24655. const unpackHalf2x16 = /*@__PURE__*/ nodeProxyIntent( UnpackFloatNode, 'float16' ).setParameterLength( 1 );
  24656. // https://github.com/cabbibo/glsl-tri-noise-3d
  24657. const tri = /*@__PURE__*/ Fn( ( [ x ] ) => {
  24658. return x.fract().sub( .5 ).abs();
  24659. } ).setLayout( {
  24660. name: 'tri',
  24661. type: 'float',
  24662. inputs: [
  24663. { name: 'x', type: 'float' }
  24664. ]
  24665. } );
  24666. const tri3 = /*@__PURE__*/ Fn( ( [ p ] ) => {
  24667. 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. ) ) ) ) );
  24668. } ).setLayout( {
  24669. name: 'tri3',
  24670. type: 'vec3',
  24671. inputs: [
  24672. { name: 'p', type: 'vec3' }
  24673. ]
  24674. } );
  24675. /**
  24676. * Generates a noise value from the given position, speed and time parameters.
  24677. *
  24678. * @tsl
  24679. * @function
  24680. * @param {Node<vec3>} position - The position.
  24681. * @param {Node<float>} speed - The speed.
  24682. * @param {Node<float>} time - The time.
  24683. * @return {Node<float>} The generated noise.
  24684. */
  24685. const triNoise3D = /*@__PURE__*/ Fn( ( [ position, speed, time ] ) => {
  24686. const p = vec3( position ).toVar();
  24687. const z = float( 1.4 ).toVar();
  24688. const rz = float( 0.0 ).toVar();
  24689. const bp = vec3( p ).toVar();
  24690. Loop( { start: float( 0.0 ), end: float( 3.0 ), type: 'float', condition: '<=' }, () => {
  24691. const dg = vec3( tri3( bp.mul( 2.0 ) ) ).toVar();
  24692. p.addAssign( dg.add( time.mul( float( 0.1 ).mul( speed ) ) ) );
  24693. bp.mulAssign( 1.8 );
  24694. z.mulAssign( 1.5 );
  24695. p.mulAssign( 1.2 );
  24696. const t = float( tri( p.z.add( tri( p.x.add( tri( p.y ) ) ) ) ) ).toVar();
  24697. rz.addAssign( t.div( z ) );
  24698. bp.addAssign( 0.14 );
  24699. } );
  24700. return rz;
  24701. } ).setLayout( {
  24702. name: 'triNoise3D',
  24703. type: 'float',
  24704. inputs: [
  24705. { name: 'position', type: 'vec3' },
  24706. { name: 'speed', type: 'float' },
  24707. { name: 'time', type: 'float' }
  24708. ]
  24709. } );
  24710. /**
  24711. * This class allows to define multiple overloaded versions
  24712. * of the same function. Depending on the parameters of the function
  24713. * call, the node picks the best-fit overloaded version.
  24714. *
  24715. * @augments Node
  24716. */
  24717. class FunctionOverloadingNode extends Node {
  24718. static get type() {
  24719. return 'FunctionOverloadingNode';
  24720. }
  24721. /**
  24722. * Constructs a new function overloading node.
  24723. *
  24724. * @param {Array<Function>} functionNodes - Array of `Fn` function definitions.
  24725. * @param {...Node} parametersNodes - A list of parameter nodes.
  24726. */
  24727. constructor( functionNodes = [], ...parametersNodes ) {
  24728. super();
  24729. /**
  24730. * Array of `Fn` function definitions.
  24731. *
  24732. * @type {Array<Function>}
  24733. */
  24734. this.functionNodes = functionNodes;
  24735. /**
  24736. * A list of parameter nodes.
  24737. *
  24738. * @type {Array<Node>}
  24739. */
  24740. this.parametersNodes = parametersNodes;
  24741. /**
  24742. * The selected overloaded function call.
  24743. *
  24744. * @private
  24745. * @type {ShaderCallNodeInternal}
  24746. */
  24747. this._candidateFn = null;
  24748. /**
  24749. * This node is marked as global.
  24750. *
  24751. * @type {boolean}
  24752. * @default true
  24753. */
  24754. this.global = true;
  24755. }
  24756. /**
  24757. * This method is overwritten since the node type is inferred from
  24758. * the function's return type.
  24759. *
  24760. * @param {NodeBuilder} builder - The current node builder.
  24761. * @return {string} The node type.
  24762. */
  24763. getNodeType( builder ) {
  24764. const candidateFn = this.getCandidateFn( builder );
  24765. return candidateFn.shaderNode.layout.type;
  24766. }
  24767. /**
  24768. * Returns the candidate function for the current parameters.
  24769. *
  24770. * @param {NodeBuilder} builder - The current node builder.
  24771. * @return {FunctionNode} The candidate function.
  24772. */
  24773. getCandidateFn( builder ) {
  24774. const params = this.parametersNodes;
  24775. let candidateFn = this._candidateFn;
  24776. if ( candidateFn === null ) {
  24777. let bestCandidateFn = null;
  24778. let bestScore = -1;
  24779. for ( const functionNode of this.functionNodes ) {
  24780. const shaderNode = functionNode.shaderNode;
  24781. const layout = shaderNode.layout;
  24782. if ( layout === null ) {
  24783. throw new Error( 'FunctionOverloadingNode: FunctionNode must be a layout.' );
  24784. }
  24785. const inputs = layout.inputs;
  24786. if ( params.length === inputs.length ) {
  24787. let currentScore = 0;
  24788. for ( let i = 0; i < params.length; i ++ ) {
  24789. const param = params[ i ];
  24790. const input = inputs[ i ];
  24791. if ( param.getNodeType( builder ) === input.type ) {
  24792. currentScore ++;
  24793. }
  24794. }
  24795. if ( currentScore > bestScore ) {
  24796. bestCandidateFn = functionNode;
  24797. bestScore = currentScore;
  24798. }
  24799. }
  24800. }
  24801. this._candidateFn = candidateFn = bestCandidateFn;
  24802. }
  24803. return candidateFn;
  24804. }
  24805. /**
  24806. * Sets up the node for the current parameters.
  24807. *
  24808. * @param {NodeBuilder} builder - The current node builder.
  24809. * @return {Node} The setup node.
  24810. */
  24811. setup( builder ) {
  24812. const candidateFn = this.getCandidateFn( builder );
  24813. return candidateFn( ...this.parametersNodes );
  24814. }
  24815. }
  24816. const overloadingBaseFn = /*@__PURE__*/ nodeProxy( FunctionOverloadingNode );
  24817. /**
  24818. * TSL function for creating a function overloading node.
  24819. *
  24820. * @tsl
  24821. * @function
  24822. * @param {Array<Function>} functionNodes - Array of `Fn` function definitions.
  24823. * @returns {FunctionOverloadingNode}
  24824. */
  24825. const overloadingFn = ( functionNodes ) => ( ...params ) => overloadingBaseFn( functionNodes, ...params );
  24826. /**
  24827. * Represents the elapsed time in seconds.
  24828. *
  24829. * @tsl
  24830. * @type {UniformNode<float>}
  24831. */
  24832. const time = /*@__PURE__*/ uniform( 0 ).setGroup( renderGroup ).onRenderUpdate( ( frame ) => frame.time );
  24833. /**
  24834. * Represents the delta time in seconds.
  24835. *
  24836. * @tsl
  24837. * @type {UniformNode<float>}
  24838. */
  24839. const deltaTime = /*@__PURE__*/ uniform( 0 ).setGroup( renderGroup ).onRenderUpdate( ( frame ) => frame.deltaTime );
  24840. /**
  24841. * Represents the current frame ID.
  24842. *
  24843. * @tsl
  24844. * @type {UniformNode<uint>}
  24845. */
  24846. const frameId = /*@__PURE__*/ uniform( 0, 'uint' ).setGroup( renderGroup ).onRenderUpdate( ( frame ) => frame.frameId );
  24847. /**
  24848. * Generates a sine wave oscillation based on a timer.
  24849. *
  24850. * @tsl
  24851. * @function
  24852. * @param {Node<float>} t - The timer to generate the oscillation with.
  24853. * @return {Node<float>} The oscillation node.
  24854. */
  24855. const oscSine = ( t = time ) => t.add( 0.75 ).mul( Math.PI * 2 ).sin().mul( 0.5 ).add( 0.5 );
  24856. /**
  24857. * Generates a square wave oscillation based on a timer.
  24858. *
  24859. * @tsl
  24860. * @function
  24861. * @param {Node<float>} t - The timer to generate the oscillation with.
  24862. * @return {Node<float>} The oscillation node.
  24863. */
  24864. const oscSquare = ( t = time ) => t.fract().round();
  24865. /**
  24866. * Generates a triangle wave oscillation based on a timer.
  24867. *
  24868. * @tsl
  24869. * @function
  24870. * @param {Node<float>} t - The timer to generate the oscillation with.
  24871. * @return {Node<float>} The oscillation node.
  24872. */
  24873. const oscTriangle = ( t = time ) => t.add( 0.5 ).fract().mul( 2 ).sub( 1 ).abs();
  24874. /**
  24875. * Generates a sawtooth wave oscillation based on a timer.
  24876. *
  24877. * @tsl
  24878. * @function
  24879. * @param {Node<float>} t - The timer to generate the oscillation with.
  24880. * @return {Node<float>} The oscillation node.
  24881. */
  24882. const oscSawtooth = ( t = time ) => t.fract();
  24883. /**
  24884. * Replaces the default UV coordinates used in texture lookups.
  24885. *
  24886. * ```js
  24887. *material.contextNode = replaceDefaultUV( ( textureNode ) => {
  24888. *
  24889. * // ...
  24890. * return customUVCoordinates;
  24891. *
  24892. *} );
  24893. *```
  24894. *
  24895. * @tsl
  24896. * @function
  24897. * @param {function(Node):Node<vec2>} callback - A callback that receives the texture node
  24898. * and must return the new uv coordinates.
  24899. * @param {Node} [node=null] - An optional node to which the context will be applied.
  24900. * @return {ContextNode} A context node that replaces the default UV coordinates.
  24901. */
  24902. function replaceDefaultUV( callback, node = null ) {
  24903. return context( node, { getUV: callback } );
  24904. }
  24905. /**
  24906. * Rotates the given uv coordinates around a center point
  24907. *
  24908. * @tsl
  24909. * @function
  24910. * @param {Node<vec2>} uv - The uv coordinates.
  24911. * @param {Node<float>} rotation - The rotation defined in radians.
  24912. * @param {Node<vec2>} center - The center of rotation
  24913. * @return {Node<vec2>} The rotated uv coordinates.
  24914. */
  24915. const rotateUV = /*@__PURE__*/ Fn( ( [ uv, rotation, center = vec2( 0.5 ) ] ) => {
  24916. return rotate( uv.sub( center ), rotation ).add( center );
  24917. } );
  24918. /**
  24919. * Applies a spherical warping effect to the given uv coordinates.
  24920. *
  24921. * @tsl
  24922. * @function
  24923. * @param {Node<vec2>} uv - The uv coordinates.
  24924. * @param {Node<float>} strength - The strength of the effect.
  24925. * @param {Node<vec2>} center - The center point
  24926. * @return {Node<vec2>} The updated uv coordinates.
  24927. */
  24928. const spherizeUV = /*@__PURE__*/ Fn( ( [ uv, strength, center = vec2( 0.5 ) ] ) => {
  24929. const delta = uv.sub( center );
  24930. const delta2 = delta.dot( delta );
  24931. const delta4 = delta2.mul( delta2 );
  24932. const deltaOffset = delta4.mul( strength );
  24933. return uv.add( delta.mul( deltaOffset ) );
  24934. } );
  24935. /**
  24936. * This can be used to achieve a billboarding behavior for flat meshes. That means they are
  24937. * oriented always towards the camera.
  24938. *
  24939. * ```js
  24940. * material.vertexNode = billboarding();
  24941. * ```
  24942. *
  24943. * @tsl
  24944. * @function
  24945. * @param {Object} config - The configuration object.
  24946. * @param {?Node<vec3>} [config.position=null] - Can be used to define the vertex positions in world space.
  24947. * @param {boolean} [config.horizontal=true] - Whether to follow the camera rotation horizontally or not.
  24948. * @param {boolean} [config.vertical=false] - Whether to follow the camera rotation vertically or not.
  24949. * @return {Node<vec3>} The updated vertex position in clip space.
  24950. */
  24951. const billboarding = /*@__PURE__*/ Fn( ( { position = null, horizontal = true, vertical = false } ) => {
  24952. let worldMatrix;
  24953. if ( position !== null ) {
  24954. worldMatrix = modelWorldMatrix.toVar();
  24955. worldMatrix[ 3 ][ 0 ] = position.x;
  24956. worldMatrix[ 3 ][ 1 ] = position.y;
  24957. worldMatrix[ 3 ][ 2 ] = position.z;
  24958. } else {
  24959. worldMatrix = modelWorldMatrix;
  24960. }
  24961. const modelViewMatrix = cameraViewMatrix.mul( worldMatrix );
  24962. if ( defined( horizontal ) ) {
  24963. modelViewMatrix[ 0 ][ 0 ] = modelWorldMatrix[ 0 ].length();
  24964. modelViewMatrix[ 0 ][ 1 ] = 0;
  24965. modelViewMatrix[ 0 ][ 2 ] = 0;
  24966. }
  24967. if ( defined( vertical ) ) {
  24968. modelViewMatrix[ 1 ][ 0 ] = 0;
  24969. modelViewMatrix[ 1 ][ 1 ] = modelWorldMatrix[ 1 ].length();
  24970. modelViewMatrix[ 1 ][ 2 ] = 0;
  24971. }
  24972. modelViewMatrix[ 2 ][ 0 ] = 0;
  24973. modelViewMatrix[ 2 ][ 1 ] = 0;
  24974. modelViewMatrix[ 2 ][ 2 ] = 1;
  24975. return cameraProjectionMatrix.mul( modelViewMatrix ).mul( positionLocal );
  24976. } );
  24977. /**
  24978. * A special version of a screen uv function that involves a depth comparison
  24979. * when computing the final uvs. The function mitigates visual errors when
  24980. * using viewport texture nodes for refraction purposes. Without this function
  24981. * objects in front of a refractive surface might appear on the refractive surface
  24982. * which is incorrect.
  24983. *
  24984. * @tsl
  24985. * @function
  24986. * @param {?Node<vec2>} uv - Optional uv coordinates. By default `screenUV` is used.
  24987. * @return {Node<vec2>} The update uv coordinates.
  24988. */
  24989. const viewportSafeUV = /*@__PURE__*/ Fn( ( [ uv = null ] ) => {
  24990. const depth = linearDepth();
  24991. const depthDiff = linearDepth( viewportDepthTexture( uv ) ).sub( depth );
  24992. const finalUV = depthDiff.lessThan( 0 ).select( screenUV, uv );
  24993. return finalUV;
  24994. } );
  24995. /**
  24996. * Can be used to compute texture coordinates for animated sprite sheets.
  24997. *
  24998. * ```js
  24999. * const uvNode = spritesheetUV( vec2( 6, 6 ), uv(), time.mul( animationSpeed ) );
  25000. *
  25001. * material.colorNode = texture( spriteSheet, uvNode );
  25002. * ```
  25003. *
  25004. * @augments Node
  25005. */
  25006. class SpriteSheetUVNode extends Node {
  25007. static get type() {
  25008. return 'SpriteSheetUVNode';
  25009. }
  25010. /**
  25011. * Constructs a new sprite sheet uv node.
  25012. *
  25013. * @param {Node<vec2>} countNode - The node that defines the number of sprites in the x and y direction (e.g 6x6).
  25014. * @param {Node<vec2>} [uvNode=uv()] - The uv node.
  25015. * @param {Node<float>} [frameNode=float()] - The node that defines the current frame/sprite.
  25016. */
  25017. constructor( countNode, uvNode = uv$1(), frameNode = float( 0 ) ) {
  25018. super( 'vec2' );
  25019. /**
  25020. * The node that defines the number of sprites in the x and y direction (e.g 6x6).
  25021. *
  25022. * @type {Node<vec2>}
  25023. */
  25024. this.countNode = countNode;
  25025. /**
  25026. * The uv node.
  25027. *
  25028. * @type {Node<vec2>}
  25029. */
  25030. this.uvNode = uvNode;
  25031. /**
  25032. * The node that defines the current frame/sprite.
  25033. *
  25034. * @type {Node<float>}
  25035. */
  25036. this.frameNode = frameNode;
  25037. }
  25038. setup() {
  25039. const { frameNode, uvNode, countNode } = this;
  25040. const { width, height } = countNode;
  25041. const frameNum = frameNode.mod( width.mul( height ) ).floor();
  25042. const column = frameNum.mod( width );
  25043. const row = height.sub( frameNum.add( 1 ).div( width ).ceil() );
  25044. const scale = countNode.reciprocal();
  25045. const uvFrameOffset = vec2( column, row );
  25046. return uvNode.add( uvFrameOffset ).mul( scale );
  25047. }
  25048. }
  25049. /**
  25050. * TSL function for creating a sprite sheet uv node.
  25051. *
  25052. * @tsl
  25053. * @function
  25054. * @param {Node<vec2>} countNode - The node that defines the number of sprites in the x and y direction (e.g 6x6).
  25055. * @param {?Node<vec2>} [uvNode=uv()] - The uv node.
  25056. * @param {?Node<float>} [frameNode=float()] - The node that defines the current frame/sprite.
  25057. * @returns {SpriteSheetUVNode}
  25058. */
  25059. const spritesheetUV = /*@__PURE__*/ nodeProxy( SpriteSheetUVNode ).setParameterLength( 3 );
  25060. /**
  25061. * TSL function for creating a triplanar textures node.
  25062. *
  25063. * Can be used for triplanar texture mapping.
  25064. *
  25065. * ```js
  25066. * material.colorNode = triplanarTexture( texture( diffuseMap ) );
  25067. * ```
  25068. *
  25069. * @tsl
  25070. * @function
  25071. * @param {Node} textureXNode - First texture node.
  25072. * @param {?Node} [textureYNode=null] - Second texture node. When not set, the shader will sample from `textureXNode` instead.
  25073. * @param {?Node} [textureZNode=null] - Third texture node. When not set, the shader will sample from `textureXNode` instead.
  25074. * @param {?Node<float>} [scaleNode=float(1)] - The scale node.
  25075. * @param {?Node<vec3>} [positionNode=positionLocal] - Vertex positions in local space.
  25076. * @param {?Node<vec3>} [normalNode=normalLocal] - Normals in local space.
  25077. * @returns {Node<vec4>}
  25078. */
  25079. const triplanarTextures = /*@__PURE__*/ Fn( ( [ textureXNode, textureYNode = null, textureZNode = null, scaleNode = float( 1 ), positionNode = positionLocal, normalNode = normalLocal ] ) => {
  25080. // Reference: https://github.com/keijiro/StandardTriplanar
  25081. // Blending factor of triplanar mapping
  25082. let bf = normalNode.abs().normalize();
  25083. bf = bf.div( bf.dot( vec3( 1.0 ) ) );
  25084. // Triplanar mapping
  25085. const tx = positionNode.yz.mul( scaleNode );
  25086. const ty = positionNode.zx.mul( scaleNode );
  25087. const tz = positionNode.xy.mul( scaleNode );
  25088. // Base color
  25089. const textureX = textureXNode.value;
  25090. const textureY = textureYNode !== null ? textureYNode.value : textureX;
  25091. const textureZ = textureZNode !== null ? textureZNode.value : textureX;
  25092. const cx = texture( textureX, tx ).mul( bf.x );
  25093. const cy = texture( textureY, ty ).mul( bf.y );
  25094. const cz = texture( textureZ, tz ).mul( bf.z );
  25095. return add( cx, cy, cz );
  25096. } );
  25097. /**
  25098. * TSL function for creating a triplanar textures node.
  25099. *
  25100. * @tsl
  25101. * @function
  25102. * @param {Node} textureXNode - First texture node.
  25103. * @param {?Node} [textureYNode=null] - Second texture node. When not set, the shader will sample from `textureXNode` instead.
  25104. * @param {?Node} [textureZNode=null] - Third texture node. When not set, the shader will sample from `textureXNode` instead.
  25105. * @param {?Node<float>} [scaleNode=float(1)] - The scale node.
  25106. * @param {?Node<vec3>} [positionNode=positionLocal] - Vertex positions in local space.
  25107. * @param {?Node<vec3>} [normalNode=normalLocal] - Normals in local space.
  25108. * @returns {Node<vec4>}
  25109. */
  25110. const triplanarTexture = ( ...params ) => triplanarTextures( ...params );
  25111. const _reflectorPlane = new Plane();
  25112. const _normal = new Vector3();
  25113. const _reflectorWorldPosition = new Vector3();
  25114. const _cameraWorldPosition = new Vector3();
  25115. const _rotationMatrix = new Matrix4();
  25116. const _lookAtPosition = new Vector3( 0, 0, -1 );
  25117. const clipPlane = new Vector4();
  25118. const _view = new Vector3();
  25119. const _target = new Vector3();
  25120. const _q = new Vector4();
  25121. const _size$2 = new Vector2();
  25122. const _defaultRT = new RenderTarget();
  25123. const _defaultUV = screenUV.flipX();
  25124. _defaultRT.depthTexture = new DepthTexture( 1, 1 );
  25125. let _inReflector = false;
  25126. /**
  25127. * This node can be used to implement mirror-like flat reflective surfaces.
  25128. *
  25129. * ```js
  25130. * const groundReflector = reflector();
  25131. * material.colorNode = groundReflector;
  25132. *
  25133. * const plane = new Mesh( geometry, material );
  25134. * plane.add( groundReflector.target );
  25135. * ```
  25136. *
  25137. * @augments TextureNode
  25138. */
  25139. class ReflectorNode extends TextureNode {
  25140. static get type() {
  25141. return 'ReflectorNode';
  25142. }
  25143. /**
  25144. * Constructs a new reflector node.
  25145. *
  25146. * @param {Object} [parameters={}] - An object holding configuration parameters.
  25147. * @param {Object3D} [parameters.target=new Object3D()] - The 3D object the reflector is linked to.
  25148. * @param {number} [parameters.resolutionScale=1] - The resolution scale.
  25149. * @param {boolean} [parameters.generateMipmaps=false] - Whether mipmaps should be generated or not.
  25150. * @param {boolean} [parameters.bounces=true] - Whether reflectors can render other reflector nodes or not.
  25151. * @param {boolean} [parameters.depth=false] - Whether depth data should be generated or not.
  25152. * @param {number} [parameters.samples] - Anti-Aliasing samples of the internal render-target.
  25153. * @param {TextureNode} [parameters.defaultTexture] - The default texture node.
  25154. * @param {ReflectorBaseNode} [parameters.reflector] - The reflector base node.
  25155. */
  25156. constructor( parameters = {} ) {
  25157. super( parameters.defaultTexture || _defaultRT.texture, _defaultUV );
  25158. /**
  25159. * A reference to the internal reflector base node which holds the actual implementation.
  25160. *
  25161. * @private
  25162. * @type {ReflectorBaseNode}
  25163. * @default ReflectorBaseNode
  25164. */
  25165. this._reflectorBaseNode = parameters.reflector || new ReflectorBaseNode( this, parameters );
  25166. /**
  25167. * A reference to the internal depth node.
  25168. *
  25169. * @private
  25170. * @type {?Node}
  25171. * @default null
  25172. */
  25173. this._depthNode = null;
  25174. this.setUpdateMatrix( false );
  25175. }
  25176. /**
  25177. * A reference to the internal reflector node.
  25178. *
  25179. * @type {ReflectorBaseNode}
  25180. */
  25181. get reflector() {
  25182. return this._reflectorBaseNode;
  25183. }
  25184. /**
  25185. * A reference to 3D object the reflector is linked to.
  25186. *
  25187. * @type {Object3D}
  25188. */
  25189. get target() {
  25190. return this._reflectorBaseNode.target;
  25191. }
  25192. /**
  25193. * Returns a node representing the mirror's depth. That can be used
  25194. * to implement more advanced reflection effects like distance attenuation.
  25195. *
  25196. * @return {Node} The depth node.
  25197. */
  25198. getDepthNode() {
  25199. if ( this._depthNode === null ) {
  25200. if ( this._reflectorBaseNode.depth !== true ) {
  25201. throw new Error( 'THREE.ReflectorNode: Depth node can only be requested when the reflector is created with { depth: true }. ' );
  25202. }
  25203. this._depthNode = nodeObject( new ReflectorNode( {
  25204. defaultTexture: _defaultRT.depthTexture,
  25205. reflector: this._reflectorBaseNode
  25206. } ) );
  25207. }
  25208. return this._depthNode;
  25209. }
  25210. setup( builder ) {
  25211. // ignore if used in post-processing
  25212. if ( ! builder.object.isQuadMesh ) this._reflectorBaseNode.build( builder );
  25213. return super.setup( builder );
  25214. }
  25215. clone() {
  25216. const newNode = new this.constructor( this.reflectorNode );
  25217. newNode.uvNode = this.uvNode;
  25218. newNode.levelNode = this.levelNode;
  25219. newNode.biasNode = this.biasNode;
  25220. newNode.sampler = this.sampler;
  25221. newNode.depthNode = this.depthNode;
  25222. newNode.compareNode = this.compareNode;
  25223. newNode.gradNode = this.gradNode;
  25224. newNode.offsetNode = this.offsetNode;
  25225. newNode._reflectorBaseNode = this._reflectorBaseNode;
  25226. return newNode;
  25227. }
  25228. /**
  25229. * Frees internal resources. Should be called when the node is no longer in use.
  25230. */
  25231. dispose() {
  25232. super.dispose();
  25233. this._reflectorBaseNode.dispose();
  25234. }
  25235. }
  25236. /**
  25237. * Holds the actual implementation of the reflector.
  25238. *
  25239. * TODO: Explain why `ReflectorBaseNode`. Originally the entire logic was implemented
  25240. * in `ReflectorNode`, see #29619.
  25241. *
  25242. * @private
  25243. * @augments Node
  25244. */
  25245. class ReflectorBaseNode extends Node {
  25246. static get type() {
  25247. return 'ReflectorBaseNode';
  25248. }
  25249. /**
  25250. * Constructs a new reflector base node.
  25251. *
  25252. * @param {TextureNode} textureNode - Represents the rendered reflections as a texture node.
  25253. * @param {Object} [parameters={}] - An object holding configuration parameters.
  25254. * @param {Object3D} [parameters.target=new Object3D()] - The 3D object the reflector is linked to.
  25255. * @param {number} [parameters.resolutionScale=1] - The resolution scale.
  25256. * @param {boolean} [parameters.generateMipmaps=false] - Whether mipmaps should be generated or not.
  25257. * @param {boolean} [parameters.bounces=true] - Whether reflectors can render other reflector nodes or not.
  25258. * @param {boolean} [parameters.depth=false] - Whether depth data should be generated or not.
  25259. * @param {number} [parameters.samples] - Anti-Aliasing samples of the internal render-target.
  25260. */
  25261. constructor( textureNode, parameters = {} ) {
  25262. super();
  25263. const {
  25264. target = new Object3D(),
  25265. resolutionScale = 1,
  25266. generateMipmaps = false,
  25267. bounces = true,
  25268. depth = false,
  25269. samples = 0
  25270. } = parameters;
  25271. /**
  25272. * Represents the rendered reflections as a texture node.
  25273. *
  25274. * @type {TextureNode}
  25275. */
  25276. this.textureNode = textureNode;
  25277. /**
  25278. * The 3D object the reflector is linked to.
  25279. *
  25280. * @type {Object3D}
  25281. * @default {new Object3D()}
  25282. */
  25283. this.target = target;
  25284. /**
  25285. * The resolution scale.
  25286. *
  25287. * @type {number}
  25288. * @default {1}
  25289. */
  25290. this.resolutionScale = resolutionScale;
  25291. if ( parameters.resolution !== undefined ) {
  25292. warnOnce( 'ReflectorNode: The "resolution" parameter has been renamed to "resolutionScale".' ); // @deprecated r180
  25293. this.resolutionScale = parameters.resolution;
  25294. }
  25295. /**
  25296. * Whether mipmaps should be generated or not.
  25297. *
  25298. * @type {boolean}
  25299. * @default {false}
  25300. */
  25301. this.generateMipmaps = generateMipmaps;
  25302. /**
  25303. * Whether reflectors can render other reflector nodes or not.
  25304. *
  25305. * @type {boolean}
  25306. * @default {true}
  25307. */
  25308. this.bounces = bounces;
  25309. /**
  25310. * Whether depth data should be generated or not.
  25311. *
  25312. * @type {boolean}
  25313. * @default {false}
  25314. */
  25315. this.depth = depth;
  25316. /**
  25317. * The number of anti-aliasing samples for the render-target
  25318. *
  25319. * @type {number}
  25320. * @default {0}
  25321. */
  25322. this.samples = samples;
  25323. /**
  25324. * The `updateBeforeType` is set to `NodeUpdateType.RENDER` when {@link ReflectorBaseNode#bounces}
  25325. * is `true`. Otherwise it's `NodeUpdateType.FRAME`.
  25326. *
  25327. * @type {string}
  25328. * @default 'render'
  25329. */
  25330. this.updateBeforeType = bounces ? NodeUpdateType.RENDER : NodeUpdateType.FRAME;
  25331. /**
  25332. * Weak map for managing virtual cameras.
  25333. *
  25334. * @type {WeakMap<Camera, Camera>}
  25335. */
  25336. this.virtualCameras = new WeakMap();
  25337. /**
  25338. * Weak map for managing render targets.
  25339. *
  25340. * @type {Map<Camera, RenderTarget>}
  25341. */
  25342. this.renderTargets = new Map();
  25343. /**
  25344. * Force render even if reflector is facing away from camera.
  25345. *
  25346. * @type {boolean}
  25347. * @default {false}
  25348. */
  25349. this.forceUpdate = false;
  25350. /**
  25351. * Whether the reflector has been rendered or not.
  25352. *
  25353. * When the reflector is facing away from the camera,
  25354. * this flag is set to `false` and the texture will be empty(black).
  25355. *
  25356. * @type {boolean}
  25357. * @default {false}
  25358. */
  25359. this.hasOutput = false;
  25360. }
  25361. /**
  25362. * Updates the resolution of the internal render target.
  25363. *
  25364. * @private
  25365. * @param {RenderTarget} renderTarget - The render target to resize.
  25366. * @param {Renderer} renderer - The renderer that is used to determine the new size.
  25367. */
  25368. _updateResolution( renderTarget, renderer ) {
  25369. const resolution = this.resolutionScale;
  25370. renderer.getDrawingBufferSize( _size$2 );
  25371. renderTarget.setSize( Math.round( _size$2.width * resolution ), Math.round( _size$2.height * resolution ) );
  25372. }
  25373. setup( builder ) {
  25374. this._updateResolution( _defaultRT, builder.renderer );
  25375. return super.setup( builder );
  25376. }
  25377. /**
  25378. * Frees internal resources. Should be called when the node is no longer in use.
  25379. */
  25380. dispose() {
  25381. super.dispose();
  25382. for ( const renderTarget of this.renderTargets.values() ) {
  25383. renderTarget.dispose();
  25384. }
  25385. }
  25386. /**
  25387. * Returns a virtual camera for the given camera. The virtual camera is used to
  25388. * render the scene from the reflector's view so correct reflections can be produced.
  25389. *
  25390. * @param {Camera} camera - The scene's camera.
  25391. * @return {Camera} The corresponding virtual camera.
  25392. */
  25393. getVirtualCamera( camera ) {
  25394. let virtualCamera = this.virtualCameras.get( camera );
  25395. if ( virtualCamera === undefined ) {
  25396. virtualCamera = camera.clone();
  25397. this.virtualCameras.set( camera, virtualCamera );
  25398. }
  25399. return virtualCamera;
  25400. }
  25401. /**
  25402. * Returns a render target for the given camera. The reflections are rendered
  25403. * into this render target.
  25404. *
  25405. * @param {Camera} camera - The scene's camera.
  25406. * @return {RenderTarget} The render target.
  25407. */
  25408. getRenderTarget( camera ) {
  25409. let renderTarget = this.renderTargets.get( camera );
  25410. if ( renderTarget === undefined ) {
  25411. renderTarget = new RenderTarget( 0, 0, { type: HalfFloatType, samples: this.samples } );
  25412. if ( this.generateMipmaps === true ) {
  25413. renderTarget.texture.minFilter = LinearMipMapLinearFilter;
  25414. renderTarget.texture.generateMipmaps = true;
  25415. }
  25416. if ( this.depth === true ) {
  25417. renderTarget.depthTexture = new DepthTexture();
  25418. }
  25419. this.renderTargets.set( camera, renderTarget );
  25420. }
  25421. return renderTarget;
  25422. }
  25423. updateBefore( frame ) {
  25424. if ( this.bounces === false && _inReflector ) return false;
  25425. _inReflector = true;
  25426. const { scene, camera, renderer, material } = frame;
  25427. const { target } = this;
  25428. const virtualCamera = this.getVirtualCamera( camera );
  25429. const renderTarget = this.getRenderTarget( virtualCamera );
  25430. renderer.getDrawingBufferSize( _size$2 );
  25431. this._updateResolution( renderTarget, renderer );
  25432. //
  25433. _reflectorWorldPosition.setFromMatrixPosition( target.matrixWorld );
  25434. _cameraWorldPosition.setFromMatrixPosition( camera.matrixWorld );
  25435. _rotationMatrix.extractRotation( target.matrixWorld );
  25436. _normal.set( 0, 0, 1 );
  25437. _normal.applyMatrix4( _rotationMatrix );
  25438. _view.subVectors( _reflectorWorldPosition, _cameraWorldPosition );
  25439. // Avoid rendering when reflector is facing away unless forcing an update
  25440. const isFacingAway = _view.dot( _normal ) > 0;
  25441. let needsClear = false;
  25442. if ( isFacingAway === true && this.forceUpdate === false ) {
  25443. if ( this.hasOutput === false ) {
  25444. _inReflector = false;
  25445. return;
  25446. }
  25447. needsClear = true;
  25448. }
  25449. _view.reflect( _normal ).negate();
  25450. _view.add( _reflectorWorldPosition );
  25451. _rotationMatrix.extractRotation( camera.matrixWorld );
  25452. _lookAtPosition.set( 0, 0, -1 );
  25453. _lookAtPosition.applyMatrix4( _rotationMatrix );
  25454. _lookAtPosition.add( _cameraWorldPosition );
  25455. _target.subVectors( _reflectorWorldPosition, _lookAtPosition );
  25456. _target.reflect( _normal ).negate();
  25457. _target.add( _reflectorWorldPosition );
  25458. //
  25459. virtualCamera.coordinateSystem = camera.coordinateSystem;
  25460. virtualCamera.position.copy( _view );
  25461. virtualCamera.up.set( 0, 1, 0 );
  25462. virtualCamera.up.applyMatrix4( _rotationMatrix );
  25463. virtualCamera.up.reflect( _normal );
  25464. virtualCamera.lookAt( _target );
  25465. virtualCamera.near = camera.near;
  25466. virtualCamera.far = camera.far;
  25467. virtualCamera.updateMatrixWorld();
  25468. virtualCamera.projectionMatrix.copy( camera.projectionMatrix );
  25469. // Now update projection matrix with new clip plane, implementing code from: http://www.terathon.com/code/oblique.html
  25470. // Paper explaining this technique: http://www.terathon.com/lengyel/Lengyel-Oblique.pdf
  25471. _reflectorPlane.setFromNormalAndCoplanarPoint( _normal, _reflectorWorldPosition );
  25472. _reflectorPlane.applyMatrix4( virtualCamera.matrixWorldInverse );
  25473. clipPlane.set( _reflectorPlane.normal.x, _reflectorPlane.normal.y, _reflectorPlane.normal.z, _reflectorPlane.constant );
  25474. const projectionMatrix = virtualCamera.projectionMatrix;
  25475. _q.x = ( Math.sign( clipPlane.x ) + projectionMatrix.elements[ 8 ] ) / projectionMatrix.elements[ 0 ];
  25476. _q.y = ( Math.sign( clipPlane.y ) + projectionMatrix.elements[ 9 ] ) / projectionMatrix.elements[ 5 ];
  25477. _q.z = -1;
  25478. _q.w = ( 1.0 + projectionMatrix.elements[ 10 ] ) / projectionMatrix.elements[ 14 ];
  25479. // Calculate the scaled plane vector
  25480. clipPlane.multiplyScalar( 1.0 / clipPlane.dot( _q ) );
  25481. const clipBias = 0;
  25482. // Replacing the third row of the projection matrix
  25483. projectionMatrix.elements[ 2 ] = clipPlane.x;
  25484. projectionMatrix.elements[ 6 ] = clipPlane.y;
  25485. projectionMatrix.elements[ 10 ] = ( renderer.coordinateSystem === WebGPUCoordinateSystem ) ? ( clipPlane.z - clipBias ) : ( clipPlane.z + 1.0 - clipBias );
  25486. projectionMatrix.elements[ 14 ] = clipPlane.w;
  25487. //
  25488. this.textureNode.value = renderTarget.texture;
  25489. if ( this.depth === true ) {
  25490. this.textureNode.getDepthNode().value = renderTarget.depthTexture;
  25491. }
  25492. material.visible = false;
  25493. const currentRenderTarget = renderer.getRenderTarget();
  25494. const currentMRT = renderer.getMRT();
  25495. const currentAutoClear = renderer.autoClear;
  25496. renderer.setMRT( null );
  25497. renderer.setRenderTarget( renderTarget );
  25498. renderer.autoClear = true;
  25499. const previousName = scene.name;
  25500. scene.name = ( scene.name || 'Scene' ) + ' [ Reflector ]'; // TODO: Add bounce index
  25501. if ( needsClear ) {
  25502. renderer.clear();
  25503. this.hasOutput = false;
  25504. } else {
  25505. renderer.render( scene, virtualCamera );
  25506. this.hasOutput = true;
  25507. }
  25508. scene.name = previousName;
  25509. renderer.setMRT( currentMRT );
  25510. renderer.setRenderTarget( currentRenderTarget );
  25511. renderer.autoClear = currentAutoClear;
  25512. material.visible = true;
  25513. _inReflector = false;
  25514. this.forceUpdate = false;
  25515. }
  25516. /**
  25517. * The resolution scale.
  25518. *
  25519. * @deprecated
  25520. * @type {number}
  25521. * @default {1}
  25522. */
  25523. get resolution() {
  25524. warnOnce( 'ReflectorNode: The "resolution" property has been renamed to "resolutionScale".' ); // @deprecated r180
  25525. return this.resolutionScale;
  25526. }
  25527. set resolution( value ) {
  25528. warnOnce( 'ReflectorNode: The "resolution" property has been renamed to "resolutionScale".' ); // @deprecated r180
  25529. this.resolutionScale = value;
  25530. }
  25531. }
  25532. /**
  25533. * TSL function for creating a reflector node.
  25534. *
  25535. * @tsl
  25536. * @function
  25537. * @param {Object} [parameters={}] - An object holding configuration parameters.
  25538. * @param {Object3D} [parameters.target=new Object3D()] - The 3D object the reflector is linked to.
  25539. * @param {number} [parameters.resolution=1] - The resolution scale.
  25540. * @param {boolean} [parameters.generateMipmaps=false] - Whether mipmaps should be generated or not.
  25541. * @param {boolean} [parameters.bounces=true] - Whether reflectors can render other reflector nodes or not.
  25542. * @param {boolean} [parameters.depth=false] - Whether depth data should be generated or not.
  25543. * @param {number} [parameters.samples] - Anti-Aliasing samples of the internal render-target.
  25544. * @param {TextureNode} [parameters.defaultTexture] - The default texture node.
  25545. * @param {ReflectorBaseNode} [parameters.reflector] - The reflector base node.
  25546. * @returns {ReflectorNode}
  25547. */
  25548. const reflector = ( parameters ) => nodeObject( new ReflectorNode( parameters ) );
  25549. const _camera = /*@__PURE__*/ new OrthographicCamera( -1, 1, 1, -1, 0, 1 );
  25550. /**
  25551. * The purpose of this special geometry is to fill the entire viewport with a single triangle.
  25552. *
  25553. * Reference: {@link https://github.com/mrdoob/three.js/pull/21358}
  25554. *
  25555. * @private
  25556. * @augments BufferGeometry
  25557. */
  25558. class QuadGeometry extends BufferGeometry {
  25559. /**
  25560. * Constructs a new quad geometry.
  25561. *
  25562. * @param {boolean} [flipY=false] - Whether the uv coordinates should be flipped along the vertical axis or not.
  25563. */
  25564. constructor( flipY = false ) {
  25565. super();
  25566. const uv = flipY === false ? [ 0, -1, 0, 1, 2, 1 ] : [ 0, 2, 0, 0, 2, 0 ];
  25567. this.setAttribute( 'position', new Float32BufferAttribute( [ -1, 3, 0, -1, -1, 0, 3, -1, 0 ], 3 ) );
  25568. this.setAttribute( 'uv', new Float32BufferAttribute( uv, 2 ) );
  25569. }
  25570. }
  25571. const _geometry = /*@__PURE__*/ new QuadGeometry();
  25572. /**
  25573. * This module is a helper for passes which need to render a full
  25574. * screen effect which is quite common in context of post processing.
  25575. *
  25576. * The intended usage is to reuse a single quad mesh for rendering
  25577. * subsequent passes by just reassigning the `material` reference.
  25578. *
  25579. * Note: This module can only be used with `WebGPURenderer`.
  25580. *
  25581. * @augments Mesh
  25582. */
  25583. class QuadMesh extends Mesh {
  25584. /**
  25585. * Constructs a new quad mesh.
  25586. *
  25587. * @param {?Material} [material=null] - The material to render the quad mesh with.
  25588. */
  25589. constructor( material = null ) {
  25590. super( _geometry, material );
  25591. /**
  25592. * The camera to render the quad mesh with.
  25593. *
  25594. * @type {OrthographicCamera}
  25595. * @readonly
  25596. */
  25597. this.camera = _camera;
  25598. /**
  25599. * This flag can be used for type testing.
  25600. *
  25601. * @type {boolean}
  25602. * @readonly
  25603. * @default true
  25604. */
  25605. this.isQuadMesh = true;
  25606. }
  25607. /**
  25608. * Async version of `render()`.
  25609. *
  25610. * @async
  25611. * @deprecated
  25612. * @param {Renderer} renderer - The renderer.
  25613. * @return {Promise} A Promise that resolves when the render has been finished.
  25614. */
  25615. async renderAsync( renderer ) {
  25616. warnOnce( 'QuadMesh: "renderAsync()" has been deprecated. Use "render()" and "await renderer.init();" when creating the renderer.' ); // @deprecated r181
  25617. await renderer.init();
  25618. renderer.render( this, _camera );
  25619. }
  25620. /**
  25621. * Renders the quad mesh
  25622. *
  25623. * @param {Renderer} renderer - The renderer.
  25624. */
  25625. render( renderer ) {
  25626. renderer.render( this, _camera );
  25627. }
  25628. }
  25629. const _size$1 = /*@__PURE__*/ new Vector2();
  25630. /**
  25631. * `RTTNode` takes another node and uses it with a `QuadMesh` to render into a texture (RTT).
  25632. * This module is especially relevant in context of post processing where certain nodes require
  25633. * texture input for their effects. With the helper function `convertToTexture()` which is based
  25634. * on this module, the node system can automatically ensure texture input if required.
  25635. *
  25636. * @augments TextureNode
  25637. */
  25638. class RTTNode extends TextureNode {
  25639. static get type() {
  25640. return 'RTTNode';
  25641. }
  25642. /**
  25643. * Constructs a new RTT node.
  25644. *
  25645. * @param {Node} node - The node to render a texture with.
  25646. * @param {?number} [width=null] - The width of the internal render target. If not width is applied, the render target is automatically resized.
  25647. * @param {?number} [height=null] - The height of the internal render target.
  25648. * @param {Object} [options={type:HalfFloatType}] - The options for the internal render target.
  25649. */
  25650. constructor( node, width = null, height = null, options = { type: HalfFloatType } ) {
  25651. const renderTarget = new RenderTarget( width, height, options );
  25652. super( renderTarget.texture, uv$1() );
  25653. /**
  25654. * This flag can be used for type testing.
  25655. *
  25656. * @type {boolean}
  25657. * @readonly
  25658. * @default true
  25659. */
  25660. this.isRTTNode = true;
  25661. /**
  25662. * The node to render a texture with.
  25663. *
  25664. * @type {Node}
  25665. */
  25666. this.node = node;
  25667. /**
  25668. * The width of the internal render target.
  25669. * If not width is applied, the render target is automatically resized.
  25670. *
  25671. * @type {?number}
  25672. * @default null
  25673. */
  25674. this.width = width;
  25675. /**
  25676. * The height of the internal render target.
  25677. *
  25678. * @type {?number}
  25679. * @default null
  25680. */
  25681. this.height = height;
  25682. /**
  25683. * The pixel ratio
  25684. *
  25685. * @type {number}
  25686. * @default 1
  25687. */
  25688. this.pixelRatio = 1;
  25689. /**
  25690. * The render target
  25691. *
  25692. * @type {RenderTarget}
  25693. */
  25694. this.renderTarget = renderTarget;
  25695. /**
  25696. * Whether the texture requires an update or not.
  25697. *
  25698. * @type {boolean}
  25699. * @default true
  25700. */
  25701. this.textureNeedsUpdate = true;
  25702. /**
  25703. * Whether the texture should automatically be updated or not.
  25704. *
  25705. * @type {boolean}
  25706. * @default true
  25707. */
  25708. this.autoUpdate = true;
  25709. /**
  25710. * The node which is used with the quad mesh for RTT.
  25711. *
  25712. * @private
  25713. * @type {Node}
  25714. * @default null
  25715. */
  25716. this._rttNode = null;
  25717. /**
  25718. * The internal quad mesh for RTT.
  25719. *
  25720. * @private
  25721. * @type {QuadMesh}
  25722. */
  25723. this._quadMesh = new QuadMesh( new NodeMaterial() );
  25724. /**
  25725. * The `updateBeforeType` is set to `NodeUpdateType.RENDER` since the node updates
  25726. * the texture once per render in its {@link RTTNode#updateBefore} method.
  25727. *
  25728. * @type {string}
  25729. * @default 'render'
  25730. */
  25731. this.updateBeforeType = NodeUpdateType.RENDER;
  25732. }
  25733. /**
  25734. * Whether the internal render target should automatically be resized or not.
  25735. *
  25736. * @type {boolean}
  25737. * @readonly
  25738. * @default true
  25739. */
  25740. get autoResize() {
  25741. return this.width === null;
  25742. }
  25743. setup( builder ) {
  25744. this._rttNode = this.node.context( builder.getSharedContext() );
  25745. this._quadMesh.material.name = 'RTT';
  25746. this._quadMesh.material.needsUpdate = true;
  25747. return super.setup( builder );
  25748. }
  25749. /**
  25750. * Sets the size of the internal render target
  25751. *
  25752. * @param {number} width - The width to set.
  25753. * @param {number} height - The width to set.
  25754. */
  25755. setSize( width, height ) {
  25756. this.width = width;
  25757. this.height = height;
  25758. const effectiveWidth = width * this.pixelRatio;
  25759. const effectiveHeight = height * this.pixelRatio;
  25760. this.renderTarget.setSize( effectiveWidth, effectiveHeight );
  25761. this.textureNeedsUpdate = true;
  25762. }
  25763. /**
  25764. * Sets the pixel ratio. This will also resize the render target.
  25765. *
  25766. * @param {number} pixelRatio - The pixel ratio to set.
  25767. */
  25768. setPixelRatio( pixelRatio ) {
  25769. this.pixelRatio = pixelRatio;
  25770. this.setSize( this.width, this.height );
  25771. }
  25772. updateBefore( { renderer } ) {
  25773. if ( this.textureNeedsUpdate === false && this.autoUpdate === false ) return;
  25774. this.textureNeedsUpdate = false;
  25775. //
  25776. if ( this.autoResize === true ) {
  25777. const pixelRatio = renderer.getPixelRatio();
  25778. const size = renderer.getSize( _size$1 );
  25779. const effectiveWidth = Math.floor( size.width * pixelRatio );
  25780. const effectiveHeight = Math.floor( size.height * pixelRatio );
  25781. if ( effectiveWidth !== this.renderTarget.width || effectiveHeight !== this.renderTarget.height ) {
  25782. this.renderTarget.setSize( effectiveWidth, effectiveHeight );
  25783. this.textureNeedsUpdate = true;
  25784. }
  25785. }
  25786. //
  25787. let name = 'RTT';
  25788. if ( this.node.name ) {
  25789. name = this.node.name + ' [ ' + name + ' ]';
  25790. }
  25791. this._quadMesh.material.fragmentNode = this._rttNode;
  25792. this._quadMesh.name = name;
  25793. //
  25794. const currentRenderTarget = renderer.getRenderTarget();
  25795. renderer.setRenderTarget( this.renderTarget );
  25796. this._quadMesh.render( renderer );
  25797. renderer.setRenderTarget( currentRenderTarget );
  25798. }
  25799. clone() {
  25800. const newNode = new TextureNode( this.value, this.uvNode, this.levelNode );
  25801. newNode.sampler = this.sampler;
  25802. newNode.referenceNode = this;
  25803. return newNode;
  25804. }
  25805. }
  25806. /**
  25807. * TSL function for creating a RTT node.
  25808. *
  25809. * @tsl
  25810. * @function
  25811. * @param {Node} node - The node to render a texture with.
  25812. * @param {?number} [width=null] - The width of the internal render target. If not width is applied, the render target is automatically resized.
  25813. * @param {?number} [height=null] - The height of the internal render target.
  25814. * @param {Object} [options={type:HalfFloatType}] - The options for the internal render target.
  25815. * @returns {RTTNode}
  25816. */
  25817. const rtt = ( node, ...params ) => nodeObject( new RTTNode( nodeObject( node ), ...params ) );
  25818. /**
  25819. * TSL function for converting nodes to textures nodes.
  25820. *
  25821. * @tsl
  25822. * @function
  25823. * @param {Node} node - The node to render a texture with.
  25824. * @param {?number} [width=null] - The width of the internal render target. If not width is applied, the render target is automatically resized.
  25825. * @param {?number} [height=null] - The height of the internal render target.
  25826. * @param {Object} [options={type:HalfFloatType}] - The options for the internal render target.
  25827. * @returns {RTTNode}
  25828. */
  25829. const convertToTexture = ( node, ...params ) => {
  25830. if ( node.isSampleNode || node.isTextureNode ) return node;
  25831. if ( node.isPassNode ) return node.getTextureNode();
  25832. return rtt( node, ...params );
  25833. };
  25834. /**
  25835. * Computes a position in view space based on a fragment's screen position expressed as uv coordinates, the fragments
  25836. * depth value and the camera's inverse projection matrix.
  25837. *
  25838. * @tsl
  25839. * @function
  25840. * @param {Node<vec2>} screenPosition - The fragment's screen position expressed as uv coordinates.
  25841. * @param {Node<float>} depth - The fragment's depth value.
  25842. * @param {Node<mat4>} projectionMatrixInverse - The camera's inverse projection matrix.
  25843. * @return {Node<vec3>} The fragments position in view space.
  25844. */
  25845. const getViewPosition = /*@__PURE__*/ Fn( ( [ screenPosition, depth, projectionMatrixInverse ], builder ) => {
  25846. let clipSpacePosition;
  25847. if ( builder.renderer.coordinateSystem === WebGPUCoordinateSystem ) {
  25848. screenPosition = vec2( screenPosition.x, screenPosition.y.oneMinus() ).mul( 2.0 ).sub( 1.0 );
  25849. clipSpacePosition = vec4( vec3( screenPosition, depth ), 1.0 );
  25850. } else {
  25851. clipSpacePosition = vec4( vec3( screenPosition.x, screenPosition.y.oneMinus(), depth ).mul( 2.0 ).sub( 1.0 ), 1.0 );
  25852. }
  25853. const viewSpacePosition = vec4( projectionMatrixInverse.mul( clipSpacePosition ) );
  25854. return viewSpacePosition.xyz.div( viewSpacePosition.w );
  25855. } );
  25856. /**
  25857. * Computes a screen position expressed as uv coordinates based on a fragment's position in view space
  25858. * and the camera's projection matrix
  25859. *
  25860. * @tsl
  25861. * @function
  25862. * @param {Node<vec3>} viewPosition - The fragments position in view space.
  25863. * @param {Node<mat4>} projectionMatrix - The camera's projection matrix.
  25864. * @return {Node<vec2>} The fragment's screen position expressed as uv coordinates.
  25865. */
  25866. const getScreenPosition = /*@__PURE__*/ Fn( ( [ viewPosition, projectionMatrix ] ) => {
  25867. const sampleClipPos = projectionMatrix.mul( vec4( viewPosition, 1.0 ) );
  25868. const sampleUv = sampleClipPos.xy.div( sampleClipPos.w ).mul( 0.5 ).add( 0.5 ).toVar();
  25869. return vec2( sampleUv.x, sampleUv.y.oneMinus() );
  25870. } );
  25871. /**
  25872. * Computes a normal vector based on depth data. Can be used as a fallback when no normal render
  25873. * target is available or if flat surface normals are required.
  25874. *
  25875. * @tsl
  25876. * @function
  25877. * @param {Node<vec2>} uv - The texture coordinate.
  25878. * @param {DepthTexture} depthTexture - The depth texture.
  25879. * @param {Node<mat4>} projectionMatrixInverse - The camera's inverse projection matrix.
  25880. * @return {Node<vec3>} The computed normal vector.
  25881. */
  25882. const getNormalFromDepth = /*@__PURE__*/ Fn( ( [ uv, depthTexture, projectionMatrixInverse ] ) => {
  25883. const size = textureSize( textureLoad( depthTexture ) );
  25884. const p = ivec2( uv.mul( size ) ).toVar();
  25885. const c0 = textureLoad( depthTexture, p ).toVar();
  25886. const l2 = textureLoad( depthTexture, p.sub( ivec2( 2, 0 ) ) ).toVar();
  25887. const l1 = textureLoad( depthTexture, p.sub( ivec2( 1, 0 ) ) ).toVar();
  25888. const r1 = textureLoad( depthTexture, p.add( ivec2( 1, 0 ) ) ).toVar();
  25889. const r2 = textureLoad( depthTexture, p.add( ivec2( 2, 0 ) ) ).toVar();
  25890. const b2 = textureLoad( depthTexture, p.add( ivec2( 0, 2 ) ) ).toVar();
  25891. const b1 = textureLoad( depthTexture, p.add( ivec2( 0, 1 ) ) ).toVar();
  25892. const t1 = textureLoad( depthTexture, p.sub( ivec2( 0, 1 ) ) ).toVar();
  25893. const t2 = textureLoad( depthTexture, p.sub( ivec2( 0, 2 ) ) ).toVar();
  25894. const dl = abs( sub( float( 2 ).mul( l1 ).sub( l2 ), c0 ) ).toVar();
  25895. const dr = abs( sub( float( 2 ).mul( r1 ).sub( r2 ), c0 ) ).toVar();
  25896. const db = abs( sub( float( 2 ).mul( b1 ).sub( b2 ), c0 ) ).toVar();
  25897. const dt = abs( sub( float( 2 ).mul( t1 ).sub( t2 ), c0 ) ).toVar();
  25898. const ce = getViewPosition( uv, c0, projectionMatrixInverse ).toVar();
  25899. 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 ) ) );
  25900. 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 ) ) );
  25901. return normalize( cross( dpdx, dpdy ) );
  25902. } );
  25903. /**
  25904. * Interleaved Gradient Noise (IGN) from Jimenez 2014.
  25905. *
  25906. * IGN has "low discrepancy" resulting in evenly distributed samples. It's superior compared to
  25907. * default white noise, blue noise or Bayer.
  25908. *
  25909. * References:
  25910. * - {@link https://www.iryoku.com/next-generation-post-processing-in-call-of-duty-advanced-warfare/}
  25911. * - {@link https://blog.demofox.org/2022/01/01/interleaved-gradient-noise-a-different-kind-of-low-discrepancy-sequence/}
  25912. *
  25913. * @tsl
  25914. * @function
  25915. * @param {Node<vec2>} position - The input position, usually screen coordinates.
  25916. * @return {Node<float>} The noise value.
  25917. */
  25918. const interleavedGradientNoise = Fn( ( [ position ] ) => {
  25919. return fract( float( 52.9829189 ).mul( fract( dot( position, vec2( 0.06711056, 0.00583715 ) ) ) ) );
  25920. } ).setLayout( {
  25921. name: 'interleavedGradientNoise',
  25922. type: 'float',
  25923. inputs: [
  25924. { name: 'position', type: 'vec2' }
  25925. ]
  25926. } );
  25927. /**
  25928. * Vogel disk sampling for uniform circular distribution.
  25929. *
  25930. * This function generates sample points distributed uniformly on a disk using the golden angle,
  25931. * resulting in an efficient low-discrepancy sequence for sampling. The rotation parameter (phi)
  25932. * allows randomizing the pattern per-pixel when combined with IGN.
  25933. *
  25934. * @tsl
  25935. * @function
  25936. * @param {Node<int>} sampleIndex - The index of the current sample (0-based).
  25937. * @param {Node<int>} samplesCount - The total number of samples.
  25938. * @param {Node<float>} phi - Rotation angle in radians (typically from IGN * 2π).
  25939. * @return {Node<vec2>} A 2D point on the unit disk.
  25940. */
  25941. const vogelDiskSample = Fn( ( [ sampleIndex, samplesCount, phi ] ) => {
  25942. const goldenAngle = float( 2.399963229728653 ); // 2π * (2 - φ) where φ is golden ratio
  25943. const r = sqrt( float( sampleIndex ).add( 0.5 ).div( float( samplesCount ) ) );
  25944. const theta = float( sampleIndex ).mul( goldenAngle ).add( phi );
  25945. return vec2( cos( theta ), sin( theta ) ).mul( r );
  25946. } ).setLayout( {
  25947. name: 'vogelDiskSample',
  25948. type: 'vec2',
  25949. inputs: [
  25950. { name: 'sampleIndex', type: 'int' },
  25951. { name: 'samplesCount', type: 'int' },
  25952. { name: 'phi', type: 'float' }
  25953. ]
  25954. } );
  25955. /**
  25956. * Class representing a node that samples a value using a provided callback function.
  25957. *
  25958. * @extends Node
  25959. */
  25960. class SampleNode extends Node {
  25961. /**
  25962. * Returns the type of the node.
  25963. *
  25964. * @type {string}
  25965. * @readonly
  25966. * @static
  25967. */
  25968. static get type() {
  25969. return 'SampleNode';
  25970. }
  25971. /**
  25972. * Creates an instance of SampleNode.
  25973. *
  25974. * @param {Function} callback - The function to be called when sampling. Should accept a UV node and return a value.
  25975. * @param {?Node<vec2>} [uvNode=null] - The UV node to be used in the texture sampling.
  25976. */
  25977. constructor( callback, uvNode = null ) {
  25978. super();
  25979. this.callback = callback;
  25980. /**
  25981. * Represents the texture coordinates.
  25982. *
  25983. * @type {?Node<vec2|vec3>}
  25984. * @default null
  25985. */
  25986. this.uvNode = uvNode;
  25987. /**
  25988. * This flag can be used for type testing.
  25989. *
  25990. * @type {boolean}
  25991. * @readonly
  25992. * @default true
  25993. */
  25994. this.isSampleNode = true;
  25995. }
  25996. /**
  25997. * Sets up the node by sampling with the default UV accessor.
  25998. *
  25999. * @returns {Node} The result of the callback function when called with the UV node.
  26000. */
  26001. setup() {
  26002. return this.sample( uv$1() );
  26003. }
  26004. /**
  26005. * Calls the callback function with the provided UV node.
  26006. *
  26007. * @param {Node<vec2>} uv - The UV node or value to be passed to the callback.
  26008. * @returns {Node} The result of the callback function.
  26009. */
  26010. sample( uv ) {
  26011. return this.callback( uv );
  26012. }
  26013. }
  26014. /**
  26015. * Helper function to create a SampleNode wrapped as a node object.
  26016. *
  26017. * @function
  26018. * @param {Function} callback - The function to be called when sampling. Should accept a UV node and return a value.
  26019. * @param {?Node<vec2>} [uv=null] - The UV node to be used in the texture sampling.
  26020. * @returns {SampleNode} The created SampleNode instance wrapped as a node object.
  26021. */
  26022. const sample = ( callback, uv = null ) => nodeObject( new SampleNode( callback, nodeObject( uv ) ) );
  26023. /**
  26024. * EventNode is a node that executes a callback during specific update phases.
  26025. *
  26026. * @augments Node
  26027. */
  26028. class EventNode extends Node {
  26029. static get type() {
  26030. return 'EventNode';
  26031. }
  26032. /**
  26033. * Creates an EventNode.
  26034. *
  26035. * @param {string} eventType - The type of event
  26036. * @param {Function} callback - The callback to execute on update.
  26037. */
  26038. constructor( eventType, callback ) {
  26039. super( 'void' );
  26040. this.eventType = eventType;
  26041. this.callback = callback;
  26042. if ( eventType === EventNode.OBJECT ) {
  26043. this.updateType = NodeUpdateType.OBJECT;
  26044. } else if ( eventType === EventNode.MATERIAL ) {
  26045. this.updateType = NodeUpdateType.RENDER;
  26046. } else if ( eventType === EventNode.BEFORE_OBJECT ) {
  26047. this.updateBeforeType = NodeUpdateType.OBJECT;
  26048. } else if ( eventType === EventNode.BEFORE_MATERIAL ) {
  26049. this.updateBeforeType = NodeUpdateType.RENDER;
  26050. }
  26051. }
  26052. update( frame ) {
  26053. this.callback( frame );
  26054. }
  26055. updateBefore( frame ) {
  26056. this.callback( frame );
  26057. }
  26058. }
  26059. EventNode.OBJECT = 'object';
  26060. EventNode.MATERIAL = 'material';
  26061. EventNode.BEFORE_OBJECT = 'beforeObject';
  26062. EventNode.BEFORE_MATERIAL = 'beforeMaterial';
  26063. /**
  26064. * Helper to create an EventNode and add it to the stack.
  26065. *
  26066. * @param {string} type - The event type.
  26067. * @param {Function} callback - The callback function.
  26068. * @returns {EventNode}
  26069. */
  26070. const createEvent = ( type, callback ) => nodeObject( new EventNode( type, callback ) ).toStack();
  26071. /**
  26072. * Creates an event that triggers a function every time an object (Mesh|Sprite) is rendered.
  26073. *
  26074. * 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.
  26075. *
  26076. * @param {Function} callback - The callback function.
  26077. * @returns {EventNode}
  26078. */
  26079. const OnObjectUpdate = ( callback ) => createEvent( EventNode.OBJECT, callback );
  26080. /**
  26081. * Creates an event that triggers a function when the first object that uses the material is rendered.
  26082. *
  26083. * 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.
  26084. *
  26085. * @param {Function} callback - The callback function.
  26086. * @returns {EventNode}
  26087. */
  26088. const OnMaterialUpdate = ( callback ) => createEvent( EventNode.MATERIAL, callback );
  26089. /**
  26090. * Creates an event that triggers a function before an object (Mesh|Sprite) is updated.
  26091. *
  26092. * 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.
  26093. *
  26094. * @param {Function} callback - The callback function.
  26095. * @returns {EventNode}
  26096. */
  26097. const OnBeforeObjectUpdate = ( callback ) => createEvent( EventNode.BEFORE_OBJECT, callback );
  26098. /**
  26099. * Creates an event that triggers a function before the material is updated.
  26100. *
  26101. * 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.
  26102. *
  26103. * @param {Function} callback - The callback function.
  26104. * @returns {EventNode}
  26105. */
  26106. const OnBeforeMaterialUpdate = ( callback ) => createEvent( EventNode.BEFORE_MATERIAL, callback );
  26107. /**
  26108. * This special type of instanced buffer attribute is intended for compute shaders.
  26109. * In earlier three.js versions it was only possible to update attribute data
  26110. * on the CPU via JavaScript and then upload the data to the GPU. With the
  26111. * new material system and renderer it is now possible to use compute shaders
  26112. * to compute the data for an attribute more efficiently on the GPU.
  26113. *
  26114. * The idea is to create an instance of this class and provide it as an input
  26115. * to {@link StorageBufferNode}.
  26116. *
  26117. * Note: This type of buffer attribute can only be used with `WebGPURenderer`.
  26118. *
  26119. * @augments InstancedBufferAttribute
  26120. */
  26121. class StorageInstancedBufferAttribute extends InstancedBufferAttribute {
  26122. /**
  26123. * Constructs a new storage instanced buffer attribute.
  26124. *
  26125. * @param {number|TypedArray} count - The item count. It is also valid to pass a typed array as an argument.
  26126. * The subsequent parameters are then obsolete.
  26127. * @param {number} itemSize - The item size.
  26128. * @param {TypedArray.constructor} [typeClass=Float32Array] - A typed array constructor.
  26129. */
  26130. constructor( count, itemSize, typeClass = Float32Array ) {
  26131. const array = ArrayBuffer.isView( count ) ? count : new typeClass( count * itemSize );
  26132. super( array, itemSize );
  26133. /**
  26134. * This flag can be used for type testing.
  26135. *
  26136. * @type {boolean}
  26137. * @readonly
  26138. * @default true
  26139. */
  26140. this.isStorageInstancedBufferAttribute = true;
  26141. }
  26142. }
  26143. /**
  26144. * This special type of buffer attribute is intended for compute shaders.
  26145. * In earlier three.js versions it was only possible to update attribute data
  26146. * on the CPU via JavaScript and then upload the data to the GPU. With the
  26147. * new material system and renderer it is now possible to use compute shaders
  26148. * to compute the data for an attribute more efficiently on the GPU.
  26149. *
  26150. * The idea is to create an instance of this class and provide it as an input
  26151. * to {@link StorageBufferNode}.
  26152. *
  26153. * Note: This type of buffer attribute can only be used with `WebGPURenderer`.
  26154. *
  26155. * @augments BufferAttribute
  26156. */
  26157. class StorageBufferAttribute extends BufferAttribute {
  26158. /**
  26159. * Constructs a new storage buffer attribute.
  26160. *
  26161. * @param {number|TypedArray} count - The item count. It is also valid to pass a typed array as an argument.
  26162. * The subsequent parameters are then obsolete.
  26163. * @param {number} itemSize - The item size.
  26164. * @param {TypedArray.constructor} [typeClass=Float32Array] - A typed array constructor.
  26165. */
  26166. constructor( count, itemSize, typeClass = Float32Array ) {
  26167. const array = ArrayBuffer.isView( count ) ? count : new typeClass( count * itemSize );
  26168. super( array, itemSize );
  26169. /**
  26170. * This flag can be used for type testing.
  26171. *
  26172. * @type {boolean}
  26173. * @readonly
  26174. * @default true
  26175. */
  26176. this.isStorageBufferAttribute = true;
  26177. }
  26178. }
  26179. /**
  26180. * TSL function for creating a storage buffer node with a configured `StorageBufferAttribute`.
  26181. *
  26182. * @tsl
  26183. * @function
  26184. * @param {number|TypedArray} count - The data count. It is also valid to pass a typed array as an argument.
  26185. * @param {string|Struct} [type='float'] - The data type.
  26186. * @returns {StorageBufferNode}
  26187. */
  26188. const attributeArray = ( count, type = 'float' ) => {
  26189. let itemSize, typedArray;
  26190. if ( type.isStruct === true ) {
  26191. itemSize = type.layout.getLength();
  26192. typedArray = getTypedArrayFromType( 'float' );
  26193. } else {
  26194. itemSize = getLengthFromType( type );
  26195. typedArray = getTypedArrayFromType( type );
  26196. }
  26197. const buffer = new StorageBufferAttribute( count, itemSize, typedArray );
  26198. const node = storage( buffer, type, count );
  26199. return node;
  26200. };
  26201. /**
  26202. * TSL function for creating a storage buffer node with a configured `StorageInstancedBufferAttribute`.
  26203. *
  26204. * @tsl
  26205. * @function
  26206. * @param {number|TypedArray} count - The data count. It is also valid to pass a typed array as an argument.
  26207. * @param {string|Struct} [type='float'] - The data type.
  26208. * @returns {StorageBufferNode}
  26209. */
  26210. const instancedArray = ( count, type = 'float' ) => {
  26211. let itemSize, typedArray;
  26212. if ( type.isStruct === true ) {
  26213. itemSize = type.layout.getLength();
  26214. typedArray = getTypedArrayFromType( 'float' );
  26215. } else {
  26216. itemSize = getLengthFromType( type );
  26217. typedArray = getTypedArrayFromType( type );
  26218. }
  26219. const buffer = new StorageInstancedBufferAttribute( count, itemSize, typedArray );
  26220. const node = storage( buffer, type, count );
  26221. return node;
  26222. };
  26223. /**
  26224. * A node for representing the uv coordinates of points.
  26225. *
  26226. * Can only be used with a WebGL backend. In WebGPU, point
  26227. * primitives always have the size of one pixel and can thus
  26228. * can't be used as sprite-like objects that display textures.
  26229. *
  26230. * @augments Node
  26231. */
  26232. class PointUVNode extends Node {
  26233. static get type() {
  26234. return 'PointUVNode';
  26235. }
  26236. /**
  26237. * Constructs a new point uv node.
  26238. */
  26239. constructor() {
  26240. super( 'vec2' );
  26241. /**
  26242. * This flag can be used for type testing.
  26243. *
  26244. * @type {boolean}
  26245. * @readonly
  26246. * @default true
  26247. */
  26248. this.isPointUVNode = true;
  26249. }
  26250. generate( /*builder*/ ) {
  26251. return 'vec2( gl_PointCoord.x, 1.0 - gl_PointCoord.y )';
  26252. }
  26253. }
  26254. /**
  26255. * TSL object that represents the uv coordinates of points.
  26256. *
  26257. * @tsl
  26258. * @type {PointUVNode}
  26259. */
  26260. const pointUV = /*@__PURE__*/ nodeImmutable( PointUVNode );
  26261. const _e1 = /*@__PURE__*/ new Euler();
  26262. const _m1 = /*@__PURE__*/ new Matrix4();
  26263. /**
  26264. * This module allows access to a collection of scene properties. The following predefined TSL objects
  26265. * are available for easier use:
  26266. *
  26267. * - `backgroundBlurriness`: A node that represents the scene's background blurriness.
  26268. * - `backgroundIntensity`: A node that represents the scene's background intensity.
  26269. * - `backgroundRotation`: A node that represents the scene's background rotation.
  26270. *
  26271. * @augments Node
  26272. */
  26273. class SceneNode extends Node {
  26274. static get type() {
  26275. return 'SceneNode';
  26276. }
  26277. /**
  26278. * Constructs a new scene node.
  26279. *
  26280. * @param {('backgroundBlurriness'|'backgroundIntensity'|'backgroundRotation')} scope - The scope defines the type of scene property that is accessed.
  26281. * @param {?Scene} [scene=null] - A reference to the scene.
  26282. */
  26283. constructor( scope = SceneNode.BACKGROUND_BLURRINESS, scene = null ) {
  26284. super();
  26285. /**
  26286. * The scope defines the type of scene property that is accessed.
  26287. *
  26288. * @type {('backgroundBlurriness'|'backgroundIntensity'|'backgroundRotation')}
  26289. */
  26290. this.scope = scope;
  26291. /**
  26292. * A reference to the scene that is going to be accessed.
  26293. *
  26294. * @type {?Scene}
  26295. * @default null
  26296. */
  26297. this.scene = scene;
  26298. }
  26299. /**
  26300. * Depending on the scope, the method returns a different type of node that represents
  26301. * the respective scene property.
  26302. *
  26303. * @param {NodeBuilder} builder - The current node builder.
  26304. * @return {Node} The output node.
  26305. */
  26306. setup( builder ) {
  26307. const scope = this.scope;
  26308. const scene = this.scene !== null ? this.scene : builder.scene;
  26309. let output;
  26310. if ( scope === SceneNode.BACKGROUND_BLURRINESS ) {
  26311. output = reference( 'backgroundBlurriness', 'float', scene );
  26312. } else if ( scope === SceneNode.BACKGROUND_INTENSITY ) {
  26313. output = reference( 'backgroundIntensity', 'float', scene );
  26314. } else if ( scope === SceneNode.BACKGROUND_ROTATION ) {
  26315. output = uniform( 'mat4' ).setName( 'backgroundRotation' ).setGroup( renderGroup ).onRenderUpdate( () => {
  26316. const background = scene.background;
  26317. if ( background !== null && background.isTexture && background.mapping !== UVMapping ) {
  26318. _e1.copy( scene.backgroundRotation );
  26319. // accommodate left-handed frame
  26320. _e1.x *= -1; _e1.y *= -1; _e1.z *= -1;
  26321. _m1.makeRotationFromEuler( _e1 );
  26322. } else {
  26323. _m1.identity();
  26324. }
  26325. return _m1;
  26326. } );
  26327. } else {
  26328. error( 'SceneNode: Unknown scope:', scope );
  26329. }
  26330. return output;
  26331. }
  26332. }
  26333. SceneNode.BACKGROUND_BLURRINESS = 'backgroundBlurriness';
  26334. SceneNode.BACKGROUND_INTENSITY = 'backgroundIntensity';
  26335. SceneNode.BACKGROUND_ROTATION = 'backgroundRotation';
  26336. /**
  26337. * TSL object that represents the scene's background blurriness.
  26338. *
  26339. * @tsl
  26340. * @type {SceneNode}
  26341. */
  26342. const backgroundBlurriness = /*@__PURE__*/ nodeImmutable( SceneNode, SceneNode.BACKGROUND_BLURRINESS );
  26343. /**
  26344. * TSL object that represents the scene's background intensity.
  26345. *
  26346. * @tsl
  26347. * @type {SceneNode}
  26348. */
  26349. const backgroundIntensity = /*@__PURE__*/ nodeImmutable( SceneNode, SceneNode.BACKGROUND_INTENSITY );
  26350. /**
  26351. * TSL object that represents the scene's background rotation.
  26352. *
  26353. * @tsl
  26354. * @type {SceneNode}
  26355. */
  26356. const backgroundRotation = /*@__PURE__*/ nodeImmutable( SceneNode, SceneNode.BACKGROUND_ROTATION );
  26357. /**
  26358. * This special version of a texture node can be used to
  26359. * write data into a storage texture with a compute shader.
  26360. *
  26361. * ```js
  26362. * const storageTexture = new THREE.StorageTexture( width, height );
  26363. *
  26364. * const computeTexture = Fn( ( { storageTexture } ) => {
  26365. *
  26366. * const posX = instanceIndex.mod( width );
  26367. * const posY = instanceIndex.div( width );
  26368. * const indexUV = uvec2( posX, posY );
  26369. *
  26370. * // generate RGB values
  26371. *
  26372. * const r = 1;
  26373. * const g = 1;
  26374. * const b = 1;
  26375. *
  26376. * textureStore( storageTexture, indexUV, vec4( r, g, b, 1 ) ).toWriteOnly();
  26377. *
  26378. * } );
  26379. *
  26380. * const computeNode = computeTexture( { storageTexture } ).compute( width * height );
  26381. * renderer.computeAsync( computeNode );
  26382. * ```
  26383. *
  26384. * This node can only be used with a WebGPU backend.
  26385. *
  26386. * @augments TextureNode
  26387. */
  26388. class StorageTextureNode extends TextureNode {
  26389. static get type() {
  26390. return 'StorageTextureNode';
  26391. }
  26392. /**
  26393. * Constructs a new storage texture node.
  26394. *
  26395. * @param {StorageTexture} value - The storage texture.
  26396. * @param {Node<vec2|vec3>} uvNode - The uv node.
  26397. * @param {?Node} [storeNode=null] - The value node that should be stored in the texture.
  26398. */
  26399. constructor( value, uvNode, storeNode = null ) {
  26400. super( value, uvNode );
  26401. /**
  26402. * The value node that should be stored in the texture.
  26403. *
  26404. * @type {?Node}
  26405. * @default null
  26406. */
  26407. this.storeNode = storeNode;
  26408. /**
  26409. * The mip level to write to for storage textures.
  26410. *
  26411. * @type {number}
  26412. * @default 0
  26413. */
  26414. this.mipLevel = 0;
  26415. /**
  26416. * This flag can be used for type testing.
  26417. *
  26418. * @type {boolean}
  26419. * @readonly
  26420. * @default true
  26421. */
  26422. this.isStorageTextureNode = true;
  26423. /**
  26424. * The access type of the texture node.
  26425. *
  26426. * @type {string}
  26427. * @default 'writeOnly'
  26428. */
  26429. this.access = NodeAccess.WRITE_ONLY;
  26430. }
  26431. /**
  26432. * Overwrites the default implementation to return a fixed value `'storageTexture'`.
  26433. *
  26434. * @param {NodeBuilder} builder - The current node builder.
  26435. * @return {string} The input type.
  26436. */
  26437. getInputType( /*builder*/ ) {
  26438. return 'storageTexture';
  26439. }
  26440. setup( builder ) {
  26441. super.setup( builder );
  26442. const properties = builder.getNodeProperties( this );
  26443. properties.storeNode = this.storeNode;
  26444. return properties;
  26445. }
  26446. /**
  26447. * Defines the node access.
  26448. *
  26449. * @param {string} value - The node access.
  26450. * @return {StorageTextureNode} A reference to this node.
  26451. */
  26452. setAccess( value ) {
  26453. this.access = value;
  26454. return this;
  26455. }
  26456. /**
  26457. * Sets the mip level to write to.
  26458. *
  26459. * @param {number} level - The mip level.
  26460. * @return {StorageTextureNode} A reference to this node.
  26461. */
  26462. setMipLevel( level ) {
  26463. this.mipLevel = level;
  26464. return this;
  26465. }
  26466. /**
  26467. * Generates the code snippet of the storage node. If no `storeNode`
  26468. * is defined, the texture node is generated as normal texture.
  26469. *
  26470. * @param {NodeBuilder} builder - The current node builder.
  26471. * @param {string} output - The current output.
  26472. * @return {string} The generated code snippet.
  26473. */
  26474. generate( builder, output ) {
  26475. let snippet;
  26476. if ( this.storeNode !== null ) {
  26477. snippet = this.generateStore( builder );
  26478. } else {
  26479. snippet = super.generate( builder, output );
  26480. }
  26481. return snippet;
  26482. }
  26483. /**
  26484. * Convenience method for configuring a read/write node access.
  26485. *
  26486. * @return {StorageTextureNode} A reference to this node.
  26487. */
  26488. toReadWrite() {
  26489. return this.setAccess( NodeAccess.READ_WRITE );
  26490. }
  26491. /**
  26492. * Convenience method for configuring a read-only node access.
  26493. *
  26494. * @return {StorageTextureNode} A reference to this node.
  26495. */
  26496. toReadOnly() {
  26497. return this.setAccess( NodeAccess.READ_ONLY );
  26498. }
  26499. /**
  26500. * Convenience method for configuring a write-only node access.
  26501. *
  26502. * @return {StorageTextureNode} A reference to this node.
  26503. */
  26504. toWriteOnly() {
  26505. return this.setAccess( NodeAccess.WRITE_ONLY );
  26506. }
  26507. /**
  26508. * Generates the code snippet of the storage texture node.
  26509. *
  26510. * @param {NodeBuilder} builder - The current node builder.
  26511. */
  26512. generateStore( builder ) {
  26513. const properties = builder.getNodeProperties( this );
  26514. const { uvNode, storeNode, depthNode } = properties;
  26515. const textureProperty = super.generate( builder, 'property' );
  26516. const uvSnippet = uvNode.build( builder, this.value.is3DTexture === true ? 'uvec3' : 'uvec2' );
  26517. const storeSnippet = storeNode.build( builder, 'vec4' );
  26518. const depthSnippet = depthNode ? depthNode.build( builder, 'int' ) : null;
  26519. const snippet = builder.generateTextureStore( builder, textureProperty, uvSnippet, depthSnippet, storeSnippet );
  26520. builder.addLineFlowCode( snippet, this );
  26521. }
  26522. clone() {
  26523. const newNode = super.clone();
  26524. newNode.storeNode = this.storeNode;
  26525. newNode.mipLevel = this.mipLevel;
  26526. return newNode;
  26527. }
  26528. }
  26529. /**
  26530. * TSL function for creating a storage texture node.
  26531. *
  26532. * @tsl
  26533. * @function
  26534. * @param {StorageTexture} value - The storage texture.
  26535. * @param {?Node<vec2|vec3>} uvNode - The uv node.
  26536. * @param {?Node} [storeNode=null] - The value node that should be stored in the texture.
  26537. * @returns {StorageTextureNode}
  26538. */
  26539. const storageTexture = /*@__PURE__*/ nodeProxy( StorageTextureNode ).setParameterLength( 1, 3 );
  26540. /**
  26541. * TODO: Explain difference to `storageTexture()`.
  26542. *
  26543. * @tsl
  26544. * @function
  26545. * @param {StorageTexture} value - The storage texture.
  26546. * @param {Node<vec2|vec3>} uvNode - The uv node.
  26547. * @param {?Node} [storeNode=null] - The value node that should be stored in the texture.
  26548. * @returns {StorageTextureNode}
  26549. */
  26550. const textureStore = ( value, uvNode, storeNode ) => {
  26551. const node = storageTexture( value, uvNode, storeNode );
  26552. if ( storeNode !== null ) node.toStack();
  26553. return node;
  26554. };
  26555. const normal = Fn( ( { texture, uv } ) => {
  26556. const epsilon = 0.0001;
  26557. const ret = vec3().toVar();
  26558. If( uv.x.lessThan( epsilon ), () => {
  26559. ret.assign( vec3( 1, 0, 0 ) );
  26560. } ).ElseIf( uv.y.lessThan( epsilon ), () => {
  26561. ret.assign( vec3( 0, 1, 0 ) );
  26562. } ).ElseIf( uv.z.lessThan( epsilon ), () => {
  26563. ret.assign( vec3( 0, 0, 1 ) );
  26564. } ).ElseIf( uv.x.greaterThan( 1 - epsilon ), () => {
  26565. ret.assign( vec3( -1, 0, 0 ) );
  26566. } ).ElseIf( uv.y.greaterThan( 1 - epsilon ), () => {
  26567. ret.assign( vec3( 0, -1, 0 ) );
  26568. } ).ElseIf( uv.z.greaterThan( 1 - epsilon ), () => {
  26569. ret.assign( vec3( 0, 0, -1 ) );
  26570. } ).Else( () => {
  26571. const step = 0.01;
  26572. 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 );
  26573. 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 );
  26574. 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 );
  26575. ret.assign( vec3( x, y, z ) );
  26576. } );
  26577. return ret.normalize();
  26578. } );
  26579. /**
  26580. * This type of uniform node represents a 3D texture.
  26581. *
  26582. * @augments TextureNode
  26583. */
  26584. class Texture3DNode extends TextureNode {
  26585. static get type() {
  26586. return 'Texture3DNode';
  26587. }
  26588. /**
  26589. * Constructs a new 3D texture node.
  26590. *
  26591. * @param {Data3DTexture} value - The 3D texture.
  26592. * @param {?Node<vec2|vec3>} [uvNode=null] - The uv node.
  26593. * @param {?Node<int>} [levelNode=null] - The level node.
  26594. */
  26595. constructor( value, uvNode = null, levelNode = null ) {
  26596. super( value, uvNode, levelNode );
  26597. /**
  26598. * This flag can be used for type testing.
  26599. *
  26600. * @type {boolean}
  26601. * @readonly
  26602. * @default true
  26603. */
  26604. this.isTexture3DNode = true;
  26605. }
  26606. /**
  26607. * Overwrites the default implementation to return a fixed value `'texture3D'`.
  26608. *
  26609. * @param {NodeBuilder} builder - The current node builder.
  26610. * @return {string} The input type.
  26611. */
  26612. getInputType( /*builder*/ ) {
  26613. return 'texture3D';
  26614. }
  26615. /**
  26616. * Returns a default uv node which is in context of 3D textures a three-dimensional
  26617. * uv node.
  26618. *
  26619. * @return {Node<vec3>} The default uv node.
  26620. */
  26621. getDefaultUV() {
  26622. return vec3( 0.5, 0.5, 0.5 );
  26623. }
  26624. /**
  26625. * Overwritten with an empty implementation since the `updateMatrix` flag is ignored
  26626. * for 3D textures. The uv transformation matrix is not applied to 3D textures.
  26627. *
  26628. * @param {boolean} value - The update toggle.
  26629. */
  26630. setUpdateMatrix( /*value*/ ) { } // Ignore .updateMatrix for 3d TextureNode
  26631. /**
  26632. * Overwrites the default implementation to return the unmodified uv node.
  26633. *
  26634. * @param {NodeBuilder} builder - The current node builder.
  26635. * @param {Node} uvNode - The uv node to setup.
  26636. * @return {Node} The unmodified uv node.
  26637. */
  26638. setupUV( builder, uvNode ) {
  26639. const texture = this.value;
  26640. if ( builder.isFlipY() && ( texture.isRenderTargetTexture === true || texture.isFramebufferTexture === true ) ) {
  26641. if ( this.sampler ) {
  26642. uvNode = uvNode.flipY();
  26643. } else {
  26644. uvNode = uvNode.setY( int( textureSize( this, this.levelNode ).y ).sub( uvNode.y ).sub( 1 ) );
  26645. }
  26646. }
  26647. return uvNode;
  26648. }
  26649. /**
  26650. * Generates the uv code snippet.
  26651. *
  26652. * @param {NodeBuilder} builder - The current node builder.
  26653. * @param {Node} uvNode - The uv node to generate code for.
  26654. * @return {string} The generated code snippet.
  26655. */
  26656. generateUV( builder, uvNode ) {
  26657. return uvNode.build( builder, this.sampler === true ? 'vec3' : 'ivec3' );
  26658. }
  26659. /**
  26660. * Generates the offset code snippet.
  26661. *
  26662. * @param {NodeBuilder} builder - The current node builder.
  26663. * @param {Node} offsetNode - The offset node to generate code for.
  26664. * @return {string} The generated code snippet.
  26665. */
  26666. generateOffset( builder, offsetNode ) {
  26667. return offsetNode.build( builder, 'ivec3' );
  26668. }
  26669. /**
  26670. * TODO.
  26671. *
  26672. * @param {Node<vec3>} uvNode - The uv node .
  26673. * @return {Node<vec3>} TODO.
  26674. */
  26675. normal( uvNode ) {
  26676. return normal( { texture: this, uv: uvNode } );
  26677. }
  26678. }
  26679. /**
  26680. * TSL function for creating a 3D texture node.
  26681. *
  26682. * @tsl
  26683. * @function
  26684. * @param {Data3DTexture} value - The 3D texture.
  26685. * @param {?Node<vec3>} [uvNode=null] - The uv node.
  26686. * @param {?Node<int>} [levelNode=null] - The level node.
  26687. * @returns {Texture3DNode}
  26688. */
  26689. const texture3D = /*@__PURE__*/ nodeProxy( Texture3DNode ).setParameterLength( 1, 3 );
  26690. /**
  26691. * TSL function for creating a texture node that fetches/loads texels without interpolation.
  26692. *
  26693. * @tsl
  26694. * @function
  26695. * @param {?(Texture|TextureNode)} [value=EmptyTexture] - The texture.
  26696. * @param {?Node<vec3>} [uvNode=null] - The uv node.
  26697. * @param {?Node<int>} [levelNode=null] - The level node.
  26698. * @param {?Node<float>} [biasNode=null] - The bias node.
  26699. * @returns {TextureNode}
  26700. */
  26701. const texture3DLoad = ( ...params ) => texture3D( ...params ).setSampler( false );
  26702. /**
  26703. * TSL function for creating a texture node that fetches/loads texels without interpolation.
  26704. *
  26705. * @tsl
  26706. * @function
  26707. * @param {?(Texture|TextureNode)} [value=EmptyTexture] - The texture.
  26708. * @param {?Node<vec3>} [uvNode=null] - The uv node.
  26709. * @param {?Node<int>} [levelNode=null] - The level node.
  26710. * @returns {TextureNode}
  26711. */
  26712. const texture3DLevel = ( value, uvNode, levelNode ) => texture3D( value, uvNode ).level( levelNode );
  26713. /**
  26714. * A special type of reference node that allows to link values in
  26715. * `userData` fields to node objects.
  26716. * ```js
  26717. * sprite.userData.rotation = 1; // stores individual rotation per sprite
  26718. *
  26719. * const material = new THREE.SpriteNodeMaterial();
  26720. * material.rotationNode = userData( 'rotation', 'float' );
  26721. * ```
  26722. * Since `UserDataNode` is extended from {@link ReferenceNode}, the node value
  26723. * will automatically be updated when the `rotation` user data field changes.
  26724. *
  26725. * @augments ReferenceNode
  26726. */
  26727. class UserDataNode extends ReferenceNode {
  26728. static get type() {
  26729. return 'UserDataNode';
  26730. }
  26731. /**
  26732. * Constructs a new user data node.
  26733. *
  26734. * @param {string} property - The property name that should be referenced by the node.
  26735. * @param {string} inputType - The node data type of the reference.
  26736. * @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.
  26737. */
  26738. constructor( property, inputType, userData = null ) {
  26739. super( property, inputType, userData );
  26740. /**
  26741. * A reference to the `userData` object. If not provided, the `userData`
  26742. * property of the 3D object that uses the node material is evaluated.
  26743. *
  26744. * @type {?Object}
  26745. * @default null
  26746. */
  26747. this.userData = userData;
  26748. }
  26749. /**
  26750. * Overwritten to make sure {@link ReferenceNode#reference} points to the correct
  26751. * `userData` field.
  26752. *
  26753. * @param {(NodeFrame|NodeBuilder)} state - The current state to evaluate.
  26754. * @return {Object} A reference to the `userData` field.
  26755. */
  26756. updateReference( state ) {
  26757. this.reference = this.userData !== null ? this.userData : state.object.userData;
  26758. return this.reference;
  26759. }
  26760. }
  26761. /**
  26762. * TSL function for creating a user data node.
  26763. *
  26764. * @tsl
  26765. * @function
  26766. * @param {string} name - The property name that should be referenced by the node.
  26767. * @param {string} inputType - The node data type of the reference.
  26768. * @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.
  26769. * @returns {UserDataNode}
  26770. */
  26771. const userData = ( name, inputType, userData ) => nodeObject( new UserDataNode( name, inputType, userData ) );
  26772. const _objectData = new WeakMap();
  26773. /**
  26774. * A node for representing motion or velocity vectors. Foundation
  26775. * for advanced post processing effects like motion blur or TRAA.
  26776. *
  26777. * The node keeps track of the model, view and projection matrices
  26778. * of the previous frame and uses them to compute offsets in NDC space.
  26779. * These offsets represent the final velocity.
  26780. *
  26781. * @augments TempNode
  26782. */
  26783. class VelocityNode extends TempNode {
  26784. static get type() {
  26785. return 'VelocityNode';
  26786. }
  26787. /**
  26788. * Constructs a new vertex color node.
  26789. */
  26790. constructor() {
  26791. super( 'vec2' );
  26792. /**
  26793. * The current projection matrix.
  26794. *
  26795. * @type {?Matrix4}
  26796. * @default null
  26797. */
  26798. this.projectionMatrix = null;
  26799. /**
  26800. * Overwritten since velocity nodes are updated per object.
  26801. *
  26802. * @type {string}
  26803. * @default 'object'
  26804. */
  26805. this.updateType = NodeUpdateType.OBJECT;
  26806. /**
  26807. * Overwritten since velocity nodes save data after the update.
  26808. *
  26809. * @type {string}
  26810. * @default 'object'
  26811. */
  26812. this.updateAfterType = NodeUpdateType.OBJECT;
  26813. /**
  26814. * Uniform node representing the previous model matrix in world space.
  26815. *
  26816. * @type {UniformNode<mat4>}
  26817. * @default null
  26818. */
  26819. this.previousModelWorldMatrix = uniform( new Matrix4() );
  26820. /**
  26821. * Uniform node representing the previous projection matrix.
  26822. *
  26823. * @type {UniformNode<mat4>}
  26824. * @default null
  26825. */
  26826. this.previousProjectionMatrix = uniform( new Matrix4() ).setGroup( renderGroup );
  26827. /**
  26828. * Uniform node representing the previous view matrix.
  26829. *
  26830. * @type {UniformNode<mat4>}
  26831. * @default null
  26832. */
  26833. this.previousCameraViewMatrix = uniform( new Matrix4() );
  26834. }
  26835. /**
  26836. * Sets the given projection matrix.
  26837. *
  26838. * @param {Matrix4} projectionMatrix - The projection matrix to set.
  26839. */
  26840. setProjectionMatrix( projectionMatrix ) {
  26841. this.projectionMatrix = projectionMatrix;
  26842. }
  26843. /**
  26844. * Updates velocity specific uniforms.
  26845. *
  26846. * @param {NodeFrame} frame - A reference to the current node frame.
  26847. */
  26848. update( { frameId, camera, object } ) {
  26849. const previousModelMatrix = getPreviousMatrix( object );
  26850. this.previousModelWorldMatrix.value.copy( previousModelMatrix );
  26851. //
  26852. const cameraData = getData( camera );
  26853. if ( cameraData.frameId !== frameId ) {
  26854. cameraData.frameId = frameId;
  26855. if ( cameraData.previousProjectionMatrix === undefined ) {
  26856. cameraData.previousProjectionMatrix = new Matrix4();
  26857. cameraData.previousCameraViewMatrix = new Matrix4();
  26858. cameraData.currentProjectionMatrix = new Matrix4();
  26859. cameraData.currentCameraViewMatrix = new Matrix4();
  26860. cameraData.previousProjectionMatrix.copy( this.projectionMatrix || camera.projectionMatrix );
  26861. cameraData.previousCameraViewMatrix.copy( camera.matrixWorldInverse );
  26862. } else {
  26863. cameraData.previousProjectionMatrix.copy( cameraData.currentProjectionMatrix );
  26864. cameraData.previousCameraViewMatrix.copy( cameraData.currentCameraViewMatrix );
  26865. }
  26866. cameraData.currentProjectionMatrix.copy( this.projectionMatrix || camera.projectionMatrix );
  26867. cameraData.currentCameraViewMatrix.copy( camera.matrixWorldInverse );
  26868. this.previousProjectionMatrix.value.copy( cameraData.previousProjectionMatrix );
  26869. this.previousCameraViewMatrix.value.copy( cameraData.previousCameraViewMatrix );
  26870. }
  26871. }
  26872. /**
  26873. * Overwritten to updated velocity specific uniforms.
  26874. *
  26875. * @param {NodeFrame} frame - A reference to the current node frame.
  26876. */
  26877. updateAfter( { object } ) {
  26878. getPreviousMatrix( object ).copy( object.matrixWorld );
  26879. }
  26880. /**
  26881. * Implements the velocity computation based on the previous and current vertex data.
  26882. *
  26883. * @param {NodeBuilder} builder - A reference to the current node builder.
  26884. * @return {Node<vec2>} The motion vector.
  26885. */
  26886. setup( /*builder*/ ) {
  26887. const projectionMatrix = ( this.projectionMatrix === null ) ? cameraProjectionMatrix : uniform( this.projectionMatrix );
  26888. const previousModelViewMatrix = this.previousCameraViewMatrix.mul( this.previousModelWorldMatrix );
  26889. const clipPositionCurrent = projectionMatrix.mul( modelViewMatrix ).mul( positionLocal );
  26890. const clipPositionPrevious = this.previousProjectionMatrix.mul( previousModelViewMatrix ).mul( positionPrevious );
  26891. const ndcPositionCurrent = clipPositionCurrent.xy.div( clipPositionCurrent.w );
  26892. const ndcPositionPrevious = clipPositionPrevious.xy.div( clipPositionPrevious.w );
  26893. const velocity = sub( ndcPositionCurrent, ndcPositionPrevious );
  26894. return velocity;
  26895. }
  26896. }
  26897. function getData( object ) {
  26898. let objectData = _objectData.get( object );
  26899. if ( objectData === undefined ) {
  26900. objectData = {};
  26901. _objectData.set( object, objectData );
  26902. }
  26903. return objectData;
  26904. }
  26905. function getPreviousMatrix( object, index = 0 ) {
  26906. const objectData = getData( object );
  26907. let matrix = objectData[ index ];
  26908. if ( matrix === undefined ) {
  26909. objectData[ index ] = matrix = new Matrix4();
  26910. objectData[ index ].copy( object.matrixWorld );
  26911. }
  26912. return matrix;
  26913. }
  26914. /**
  26915. * TSL object that represents the velocity of a render pass.
  26916. *
  26917. * @tsl
  26918. * @type {VelocityNode}
  26919. */
  26920. const velocity = /*@__PURE__*/ nodeImmutable( VelocityNode );
  26921. /**
  26922. * Computes a grayscale value for the given RGB color value.
  26923. *
  26924. * @tsl
  26925. * @function
  26926. * @param {Node<vec3>} color - The color value to compute the grayscale for.
  26927. * @return {Node<vec3>} The grayscale color.
  26928. */
  26929. const grayscale = /*@__PURE__*/ Fn( ( [ color ] ) => {
  26930. return luminance( color.rgb );
  26931. } );
  26932. /**
  26933. * Super-saturates or desaturates the given RGB color.
  26934. *
  26935. * @tsl
  26936. * @function
  26937. * @param {Node<vec3>} color - The input color.
  26938. * @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.
  26939. * @return {Node<vec3>} The saturated color.
  26940. */
  26941. const saturation = /*@__PURE__*/ Fn( ( [ color, adjustment = float( 1 ) ] ) => {
  26942. return adjustment.mix( luminance( color.rgb ), color.rgb );
  26943. } );
  26944. /**
  26945. * Selectively enhance the intensity of less saturated RGB colors. Can result
  26946. * in a more natural and visually appealing image with enhanced color depth
  26947. * compared to {@link ColorAdjustment#saturation}.
  26948. *
  26949. * @tsl
  26950. * @function
  26951. * @param {Node<vec3>} color - The input color.
  26952. * @param {Node<float>} [adjustment=1] - Controls the intensity of the vibrance effect.
  26953. * @return {Node<vec3>} The updated color.
  26954. */
  26955. const vibrance = /*@__PURE__*/ Fn( ( [ color, adjustment = float( 1 ) ] ) => {
  26956. const average = add( color.r, color.g, color.b ).div( 3.0 );
  26957. const mx = color.r.max( color.g.max( color.b ) );
  26958. const amt = mx.sub( average ).mul( adjustment ).mul( -3 );
  26959. return mix( color.rgb, mx, amt );
  26960. } );
  26961. /**
  26962. * Updates the hue component of the given RGB color while preserving its luminance and saturation.
  26963. *
  26964. * @tsl
  26965. * @function
  26966. * @param {Node<vec3>} color - The input color.
  26967. * @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.
  26968. * @return {Node<vec3>} The updated color.
  26969. */
  26970. const hue = /*@__PURE__*/ Fn( ( [ color, adjustment = float( 1 ) ] ) => {
  26971. const k = vec3( 0.57735, 0.57735, 0.57735 );
  26972. const cosAngle = adjustment.cos();
  26973. return vec3( color.rgb.mul( cosAngle ).add( k.cross( color.rgb ).mul( adjustment.sin() ).add( k.mul( dot( k, color.rgb ).mul( cosAngle.oneMinus() ) ) ) ) );
  26974. } );
  26975. /**
  26976. * Computes the luminance for the given RGB color value.
  26977. *
  26978. * @tsl
  26979. * @function
  26980. * @param {Node<vec3>} color - The color value to compute the luminance for.
  26981. * @param {?Node<vec3>} luminanceCoefficients - The luminance coefficients. By default predefined values of the current working color space are used.
  26982. * @return {Node<float>} The luminance.
  26983. */
  26984. const luminance = (
  26985. color,
  26986. luminanceCoefficients = vec3( ColorManagement.getLuminanceCoefficients( new Vector3() ) )
  26987. ) => dot( color, luminanceCoefficients );
  26988. /**
  26989. * Color Decision List (CDL) v1.2
  26990. *
  26991. * Compact representation of color grading information, defined by slope, offset, power, and
  26992. * saturation. The CDL should be typically be given input in a log space (such as LogC, ACEScc,
  26993. * or AgX Log), and will return output in the same space. Output may require clamping >=0.
  26994. *
  26995. * @tsl
  26996. * @function
  26997. * @param {Node<vec4>} color Input (-Infinity < input < +Infinity)
  26998. * @param {Node<vec3>} slope Slope (0 ≤ slope < +Infinity)
  26999. * @param {Node<vec3>} offset Offset (-Infinity < offset < +Infinity; typically -1 < offset < 1)
  27000. * @param {Node<vec3>} power Power (0 < power < +Infinity)
  27001. * @param {Node<float>} saturation Saturation (0 ≤ saturation < +Infinity; typically 0 ≤ saturation < 4)
  27002. * @param {Node<vec3>} luminanceCoefficients Luminance coefficients for saturation term, typically Rec. 709
  27003. * @return {Node<vec4>} Output, -Infinity < output < +Infinity
  27004. *
  27005. * References:
  27006. * - ASC CDL v1.2
  27007. * - {@link https://blender.stackexchange.com/a/55239/43930}
  27008. * - {@link https://docs.acescentral.com/specifications/acescc/}
  27009. */
  27010. const cdl = /*@__PURE__*/ Fn( ( [
  27011. color,
  27012. slope = vec3( 1 ),
  27013. offset = vec3( 0 ),
  27014. power = vec3( 1 ),
  27015. saturation = float( 1 ),
  27016. // ASC CDL v1.2 explicitly requires Rec. 709 luminance coefficients.
  27017. luminanceCoefficients = vec3( ColorManagement.getLuminanceCoefficients( new Vector3(), LinearSRGBColorSpace ) )
  27018. ] ) => {
  27019. // NOTE: The ASC CDL v1.2 defines a [0, 1] clamp on the slope+offset term, and another on the
  27020. // saturation term. Per the ACEScc specification and Filament, limits may be omitted to support
  27021. // values outside [0, 1], requiring a workaround for negative values in the power expression.
  27022. const luma = color.rgb.dot( vec3( luminanceCoefficients ) );
  27023. const v = max$1( color.rgb.mul( slope ).add( offset ), 0.0 ).toVar();
  27024. const pv = v.pow( power ).toVar();
  27025. If( v.r.greaterThan( 0.0 ), () => { v.r.assign( pv.r ); } ); // eslint-disable-line
  27026. If( v.g.greaterThan( 0.0 ), () => { v.g.assign( pv.g ); } ); // eslint-disable-line
  27027. If( v.b.greaterThan( 0.0 ), () => { v.b.assign( pv.b ); } ); // eslint-disable-line
  27028. v.assign( luma.add( v.sub( luma ).mul( saturation ) ) );
  27029. return vec4( v.rgb, color.a );
  27030. } );
  27031. /**
  27032. * Represents a posterize effect which reduces the number of colors
  27033. * in an image, resulting in a more blocky and stylized appearance.
  27034. *
  27035. * @augments TempNode
  27036. */
  27037. class PosterizeNode extends TempNode {
  27038. static get type() {
  27039. return 'PosterizeNode';
  27040. }
  27041. /**
  27042. * Constructs a new posterize node.
  27043. *
  27044. * @param {Node} sourceNode - The input color.
  27045. * @param {Node} stepsNode - Controls the intensity of the posterization effect. A lower number results in a more blocky appearance.
  27046. */
  27047. constructor( sourceNode, stepsNode ) {
  27048. super();
  27049. /**
  27050. * The input color.
  27051. *
  27052. * @type {Node}
  27053. */
  27054. this.sourceNode = sourceNode;
  27055. /**
  27056. * Controls the intensity of the posterization effect. A lower number results in a more blocky appearance.
  27057. *
  27058. * @type {Node}
  27059. */
  27060. this.stepsNode = stepsNode;
  27061. }
  27062. setup() {
  27063. const { sourceNode, stepsNode } = this;
  27064. return sourceNode.mul( stepsNode ).floor().div( stepsNode );
  27065. }
  27066. }
  27067. /**
  27068. * TSL function for creating a posterize node.
  27069. *
  27070. * @tsl
  27071. * @function
  27072. * @param {Node} sourceNode - The input color.
  27073. * @param {Node} stepsNode - Controls the intensity of the posterization effect. A lower number results in a more blocky appearance.
  27074. * @returns {PosterizeNode}
  27075. */
  27076. const posterize = /*@__PURE__*/ nodeProxy( PosterizeNode ).setParameterLength( 2 );
  27077. const _size = /*@__PURE__*/ new Vector2();
  27078. /**
  27079. * Represents the texture of a pass node.
  27080. *
  27081. * @augments TextureNode
  27082. */
  27083. class PassTextureNode extends TextureNode {
  27084. static get type() {
  27085. return 'PassTextureNode';
  27086. }
  27087. /**
  27088. * Constructs a new pass texture node.
  27089. *
  27090. * @param {PassNode} passNode - The pass node.
  27091. * @param {Texture} texture - The output texture.
  27092. */
  27093. constructor( passNode, texture ) {
  27094. super( texture );
  27095. /**
  27096. * A reference to the pass node.
  27097. *
  27098. * @type {PassNode}
  27099. */
  27100. this.passNode = passNode;
  27101. this.setUpdateMatrix( false );
  27102. }
  27103. setup( builder ) {
  27104. this.passNode.build( builder );
  27105. return super.setup( builder );
  27106. }
  27107. clone() {
  27108. return new this.constructor( this.passNode, this.value );
  27109. }
  27110. }
  27111. /**
  27112. * An extension of `PassTextureNode` which allows to manage more than one
  27113. * internal texture. Relevant for the `getPreviousTexture()` related API.
  27114. *
  27115. * @augments PassTextureNode
  27116. */
  27117. class PassMultipleTextureNode extends PassTextureNode {
  27118. static get type() {
  27119. return 'PassMultipleTextureNode';
  27120. }
  27121. /**
  27122. * Constructs a new pass texture node.
  27123. *
  27124. * @param {PassNode} passNode - The pass node.
  27125. * @param {string} textureName - The output texture name.
  27126. * @param {boolean} [previousTexture=false] - Whether previous frame data should be used or not.
  27127. */
  27128. constructor( passNode, textureName, previousTexture = false ) {
  27129. // null is passed to the super call since this class does not
  27130. // use an external texture for rendering pass data into. Instead
  27131. // the texture is managed by the pass node itself
  27132. super( passNode, null );
  27133. /**
  27134. * The output texture name.
  27135. *
  27136. * @type {string}
  27137. */
  27138. this.textureName = textureName;
  27139. /**
  27140. * Whether previous frame data should be used or not.
  27141. *
  27142. * @type {boolean}
  27143. */
  27144. this.previousTexture = previousTexture;
  27145. }
  27146. /**
  27147. * Updates the texture reference of this node.
  27148. */
  27149. updateTexture() {
  27150. this.value = this.previousTexture ? this.passNode.getPreviousTexture( this.textureName ) : this.passNode.getTexture( this.textureName );
  27151. }
  27152. setup( builder ) {
  27153. this.updateTexture();
  27154. return super.setup( builder );
  27155. }
  27156. clone() {
  27157. const newNode = new this.constructor( this.passNode, this.textureName, this.previousTexture );
  27158. newNode.uvNode = this.uvNode;
  27159. newNode.levelNode = this.levelNode;
  27160. newNode.biasNode = this.biasNode;
  27161. newNode.sampler = this.sampler;
  27162. newNode.depthNode = this.depthNode;
  27163. newNode.compareNode = this.compareNode;
  27164. newNode.gradNode = this.gradNode;
  27165. newNode.offsetNode = this.offsetNode;
  27166. return newNode;
  27167. }
  27168. }
  27169. /**
  27170. * Represents a render pass (sometimes called beauty pass) in context of post processing.
  27171. * This pass produces a render for the given scene and camera and can provide multiple outputs
  27172. * via MRT for further processing.
  27173. *
  27174. * ```js
  27175. * const postProcessing = new PostProcessing( renderer );
  27176. *
  27177. * const scenePass = pass( scene, camera );
  27178. *
  27179. * postProcessing.outputNode = scenePass;
  27180. * ```
  27181. *
  27182. * @augments TempNode
  27183. */
  27184. class PassNode extends TempNode {
  27185. static get type() {
  27186. return 'PassNode';
  27187. }
  27188. /**
  27189. * Constructs a new pass node.
  27190. *
  27191. * @param {('color'|'depth')} scope - The scope of the pass. The scope determines whether the node outputs color or depth.
  27192. * @param {Scene} scene - A reference to the scene.
  27193. * @param {Camera} camera - A reference to the camera.
  27194. * @param {Object} options - Options for the internal render target.
  27195. */
  27196. constructor( scope, scene, camera, options = {} ) {
  27197. super( 'vec4' );
  27198. /**
  27199. * The scope of the pass. The scope determines whether the node outputs color or depth.
  27200. *
  27201. * @type {('color'|'depth')}
  27202. */
  27203. this.scope = scope;
  27204. /**
  27205. * A reference to the scene.
  27206. *
  27207. * @type {Scene}
  27208. */
  27209. this.scene = scene;
  27210. /**
  27211. * A reference to the camera.
  27212. *
  27213. * @type {Camera}
  27214. */
  27215. this.camera = camera;
  27216. /**
  27217. * Options for the internal render target.
  27218. *
  27219. * @type {Object}
  27220. */
  27221. this.options = options;
  27222. /**
  27223. * The pass's pixel ratio. Will be kept automatically kept in sync with the renderer's pixel ratio.
  27224. *
  27225. * @private
  27226. * @type {number}
  27227. * @default 1
  27228. */
  27229. this._pixelRatio = 1;
  27230. /**
  27231. * The pass's pixel width. Will be kept automatically kept in sync with the renderer's width.
  27232. * @private
  27233. * @type {number}
  27234. * @default 1
  27235. */
  27236. this._width = 1;
  27237. /**
  27238. * The pass's pixel height. Will be kept automatically kept in sync with the renderer's height.
  27239. * @private
  27240. * @type {number}
  27241. * @default 1
  27242. */
  27243. this._height = 1;
  27244. const depthTexture = new DepthTexture();
  27245. depthTexture.isRenderTargetTexture = true;
  27246. //depthTexture.type = FloatType;
  27247. depthTexture.name = 'depth';
  27248. const renderTarget = new RenderTarget( this._width * this._pixelRatio, this._height * this._pixelRatio, { type: HalfFloatType, ...options, } );
  27249. renderTarget.texture.name = 'output';
  27250. renderTarget.depthTexture = depthTexture;
  27251. /**
  27252. * The pass's render target.
  27253. *
  27254. * @type {RenderTarget}
  27255. */
  27256. this.renderTarget = renderTarget;
  27257. /**
  27258. * An optional override material for the pass.
  27259. *
  27260. * @type {Material|null}
  27261. */
  27262. this.overrideMaterial = null;
  27263. /**
  27264. * Whether the pass is transparent.
  27265. *
  27266. * @type {boolean}
  27267. * @default false
  27268. */
  27269. this.transparent = true;
  27270. /**
  27271. * Whether the pass is opaque.
  27272. *
  27273. * @type {boolean}
  27274. * @default true
  27275. */
  27276. this.opaque = true;
  27277. /**
  27278. * An optional global context for the pass.
  27279. *
  27280. * @type {ContextNode|null}
  27281. */
  27282. this.contextNode = null;
  27283. /**
  27284. * A cache for the context node.
  27285. *
  27286. * @private
  27287. * @type {?Object}
  27288. * @default null
  27289. */
  27290. this._contextNodeCache = null;
  27291. /**
  27292. * A dictionary holding the internal result textures.
  27293. *
  27294. * @private
  27295. * @type {Object<string, Texture>}
  27296. */
  27297. this._textures = {
  27298. output: renderTarget.texture,
  27299. depth: depthTexture
  27300. };
  27301. /**
  27302. * A dictionary holding the internal texture nodes.
  27303. *
  27304. * @private
  27305. * @type {Object<string, TextureNode>}
  27306. */
  27307. this._textureNodes = {};
  27308. /**
  27309. * A dictionary holding the internal depth nodes.
  27310. *
  27311. * @private
  27312. * @type {Object}
  27313. */
  27314. this._linearDepthNodes = {};
  27315. /**
  27316. * A dictionary holding the internal viewZ nodes.
  27317. *
  27318. * @private
  27319. * @type {Object}
  27320. */
  27321. this._viewZNodes = {};
  27322. /**
  27323. * A dictionary holding the texture data of the previous frame.
  27324. * Used for computing velocity/motion vectors.
  27325. *
  27326. * @private
  27327. * @type {Object<string, Texture>}
  27328. */
  27329. this._previousTextures = {};
  27330. /**
  27331. * A dictionary holding the texture nodes of the previous frame.
  27332. * Used for computing velocity/motion vectors.
  27333. *
  27334. * @private
  27335. * @type {Object<string, TextureNode>}
  27336. */
  27337. this._previousTextureNodes = {};
  27338. /**
  27339. * The `near` property of the camera as a uniform.
  27340. *
  27341. * @private
  27342. * @type {UniformNode}
  27343. */
  27344. this._cameraNear = uniform( 0 );
  27345. /**
  27346. * The `far` property of the camera as a uniform.
  27347. *
  27348. * @private
  27349. * @type {UniformNode}
  27350. */
  27351. this._cameraFar = uniform( 0 );
  27352. /**
  27353. * A MRT node configuring the MRT settings.
  27354. *
  27355. * @private
  27356. * @type {?MRTNode}
  27357. * @default null
  27358. */
  27359. this._mrt = null;
  27360. /**
  27361. * Layer object for configuring the camera that is used
  27362. * to produce the pass.
  27363. *
  27364. * @private
  27365. * @type {?Layers}
  27366. * @default null
  27367. */
  27368. this._layers = null;
  27369. /**
  27370. * Scales the resolution of the internal render target.
  27371. *
  27372. * @private
  27373. * @type {number}
  27374. * @default 1
  27375. */
  27376. this._resolutionScale = 1;
  27377. /**
  27378. * Custom viewport definition.
  27379. *
  27380. * @private
  27381. * @type {?Vector4}
  27382. * @default null
  27383. */
  27384. this._viewport = null;
  27385. /**
  27386. * Custom scissor definition.
  27387. *
  27388. * @private
  27389. * @type {?Vector4}
  27390. * @default null
  27391. */
  27392. this._scissor = null;
  27393. /**
  27394. * This flag can be used for type testing.
  27395. *
  27396. * @type {boolean}
  27397. * @readonly
  27398. * @default true
  27399. */
  27400. this.isPassNode = true;
  27401. /**
  27402. * The `updateBeforeType` is set to `NodeUpdateType.FRAME` since the node renders the
  27403. * scene once per frame in its {@link PassNode#updateBefore} method.
  27404. *
  27405. * @type {string}
  27406. * @default 'frame'
  27407. */
  27408. this.updateBeforeType = NodeUpdateType.FRAME;
  27409. /**
  27410. * This flag is used for global cache.
  27411. *
  27412. * @type {boolean}
  27413. * @default true
  27414. */
  27415. this.global = true;
  27416. }
  27417. /**
  27418. * Sets the resolution scale for the pass.
  27419. * The resolution scale is a factor that is multiplied with the renderer's width and height.
  27420. *
  27421. * @param {number} resolutionScale - The resolution scale to set. A value of `1` means full resolution.
  27422. * @return {PassNode} A reference to this pass.
  27423. */
  27424. setResolutionScale( resolutionScale ) {
  27425. this._resolutionScale = resolutionScale;
  27426. return this;
  27427. }
  27428. /**
  27429. * Gets the current resolution scale of the pass.
  27430. *
  27431. * @return {number} The current resolution scale. A value of `1` means full resolution.
  27432. */
  27433. getResolutionScale() {
  27434. return this._resolutionScale;
  27435. }
  27436. /**
  27437. * Sets the resolution for the pass.
  27438. * The resolution is a factor that is multiplied with the renderer's width and height.
  27439. *
  27440. * @param {number} resolution - The resolution to set. A value of `1` means full resolution.
  27441. * @return {PassNode} A reference to this pass.
  27442. * @deprecated since r181. Use {@link PassNode#setResolutionScale `setResolutionScale()`} instead.
  27443. */
  27444. setResolution( resolution ) { // @deprecated, r181
  27445. warn( 'PassNode: .setResolution() is deprecated. Use .setResolutionScale() instead.' );
  27446. return this.setResolutionScale( resolution );
  27447. }
  27448. /**
  27449. * Gets the current resolution of the pass.
  27450. *
  27451. * @return {number} The current resolution. A value of `1` means full resolution.
  27452. * @deprecated since r181. Use {@link PassNode#getResolutionScale `getResolutionScale()`} instead.
  27453. */
  27454. getResolution() { // @deprecated, r181
  27455. warn( 'PassNode: .getResolution() is deprecated. Use .getResolutionScale() instead.' );
  27456. return this.getResolutionScale();
  27457. }
  27458. /**
  27459. * Sets the layer configuration that should be used when rendering the pass.
  27460. *
  27461. * @param {Layers} layers - The layers object to set.
  27462. * @return {PassNode} A reference to this pass.
  27463. */
  27464. setLayers( layers ) {
  27465. this._layers = layers;
  27466. return this;
  27467. }
  27468. /**
  27469. * Gets the current layer configuration of the pass.
  27470. *
  27471. * @return {?Layers} .
  27472. */
  27473. getLayers() {
  27474. return this._layers;
  27475. }
  27476. /**
  27477. * Sets the given MRT node to setup MRT for this pass.
  27478. *
  27479. * @param {MRTNode} mrt - The MRT object.
  27480. * @return {PassNode} A reference to this pass.
  27481. */
  27482. setMRT( mrt ) {
  27483. this._mrt = mrt;
  27484. return this;
  27485. }
  27486. /**
  27487. * Returns the current MRT node.
  27488. *
  27489. * @return {MRTNode} The current MRT node.
  27490. */
  27491. getMRT() {
  27492. return this._mrt;
  27493. }
  27494. /**
  27495. * Returns the texture for the given output name.
  27496. *
  27497. * @param {string} name - The output name to get the texture for.
  27498. * @return {Texture} The texture.
  27499. */
  27500. getTexture( name ) {
  27501. let texture = this._textures[ name ];
  27502. if ( texture === undefined ) {
  27503. const refTexture = this.renderTarget.texture;
  27504. texture = refTexture.clone();
  27505. texture.name = name;
  27506. this._textures[ name ] = texture;
  27507. this.renderTarget.textures.push( texture );
  27508. }
  27509. return texture;
  27510. }
  27511. /**
  27512. * Returns the texture holding the data of the previous frame for the given output name.
  27513. *
  27514. * @param {string} name - The output name to get the texture for.
  27515. * @return {Texture} The texture holding the data of the previous frame.
  27516. */
  27517. getPreviousTexture( name ) {
  27518. let texture = this._previousTextures[ name ];
  27519. if ( texture === undefined ) {
  27520. texture = this.getTexture( name ).clone();
  27521. this._previousTextures[ name ] = texture;
  27522. }
  27523. return texture;
  27524. }
  27525. /**
  27526. * Switches current and previous textures for the given output name.
  27527. *
  27528. * @param {string} name - The output name.
  27529. */
  27530. toggleTexture( name ) {
  27531. const prevTexture = this._previousTextures[ name ];
  27532. if ( prevTexture !== undefined ) {
  27533. const texture = this._textures[ name ];
  27534. const index = this.renderTarget.textures.indexOf( texture );
  27535. this.renderTarget.textures[ index ] = prevTexture;
  27536. this._textures[ name ] = prevTexture;
  27537. this._previousTextures[ name ] = texture;
  27538. this._textureNodes[ name ].updateTexture();
  27539. this._previousTextureNodes[ name ].updateTexture();
  27540. }
  27541. }
  27542. /**
  27543. * Returns the texture node for the given output name.
  27544. *
  27545. * @param {string} [name='output'] - The output name to get the texture node for.
  27546. * @return {TextureNode} The texture node.
  27547. */
  27548. getTextureNode( name = 'output' ) {
  27549. let textureNode = this._textureNodes[ name ];
  27550. if ( textureNode === undefined ) {
  27551. textureNode = nodeObject( new PassMultipleTextureNode( this, name ) );
  27552. textureNode.updateTexture();
  27553. this._textureNodes[ name ] = textureNode;
  27554. }
  27555. return textureNode;
  27556. }
  27557. /**
  27558. * Returns the previous texture node for the given output name.
  27559. *
  27560. * @param {string} [name='output'] - The output name to get the previous texture node for.
  27561. * @return {TextureNode} The previous texture node.
  27562. */
  27563. getPreviousTextureNode( name = 'output' ) {
  27564. let textureNode = this._previousTextureNodes[ name ];
  27565. if ( textureNode === undefined ) {
  27566. if ( this._textureNodes[ name ] === undefined ) this.getTextureNode( name );
  27567. textureNode = nodeObject( new PassMultipleTextureNode( this, name, true ) );
  27568. textureNode.updateTexture();
  27569. this._previousTextureNodes[ name ] = textureNode;
  27570. }
  27571. return textureNode;
  27572. }
  27573. /**
  27574. * Returns a viewZ node of this pass.
  27575. *
  27576. * @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.
  27577. * @return {Node} The viewZ node.
  27578. */
  27579. getViewZNode( name = 'depth' ) {
  27580. let viewZNode = this._viewZNodes[ name ];
  27581. if ( viewZNode === undefined ) {
  27582. const cameraNear = this._cameraNear;
  27583. const cameraFar = this._cameraFar;
  27584. this._viewZNodes[ name ] = viewZNode = perspectiveDepthToViewZ( this.getTextureNode( name ), cameraNear, cameraFar );
  27585. }
  27586. return viewZNode;
  27587. }
  27588. /**
  27589. * Returns a linear depth node of this pass.
  27590. *
  27591. * @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.
  27592. * @return {Node} The linear depth node.
  27593. */
  27594. getLinearDepthNode( name = 'depth' ) {
  27595. let linearDepthNode = this._linearDepthNodes[ name ];
  27596. if ( linearDepthNode === undefined ) {
  27597. const cameraNear = this._cameraNear;
  27598. const cameraFar = this._cameraFar;
  27599. const viewZNode = this.getViewZNode( name );
  27600. // TODO: just if ( builder.camera.isPerspectiveCamera )
  27601. this._linearDepthNodes[ name ] = linearDepthNode = viewZToOrthographicDepth( viewZNode, cameraNear, cameraFar );
  27602. }
  27603. return linearDepthNode;
  27604. }
  27605. /**
  27606. * Precompiles the pass.
  27607. *
  27608. * Note that this method must be called after the pass configuration is complete.
  27609. * So calls like `setMRT()` and `getTextureNode()` must proceed the precompilation.
  27610. *
  27611. * @async
  27612. * @param {Renderer} renderer - The renderer.
  27613. * @return {Promise} A Promise that resolves when the compile has been finished.
  27614. * @see {@link Renderer#compileAsync}
  27615. */
  27616. async compileAsync( renderer ) {
  27617. const currentRenderTarget = renderer.getRenderTarget();
  27618. const currentMRT = renderer.getMRT();
  27619. renderer.setRenderTarget( this.renderTarget );
  27620. renderer.setMRT( this._mrt );
  27621. await renderer.compileAsync( this.scene, this.camera );
  27622. renderer.setRenderTarget( currentRenderTarget );
  27623. renderer.setMRT( currentMRT );
  27624. }
  27625. setup( { renderer } ) {
  27626. this.renderTarget.samples = this.options.samples === undefined ? renderer.samples : this.options.samples;
  27627. this.renderTarget.texture.type = renderer.getOutputBufferType();
  27628. return this.scope === PassNode.COLOR ? this.getTextureNode() : this.getLinearDepthNode();
  27629. }
  27630. updateBefore( frame ) {
  27631. const { renderer } = frame;
  27632. const { scene } = this;
  27633. let camera;
  27634. let pixelRatio;
  27635. const outputRenderTarget = renderer.getOutputRenderTarget();
  27636. if ( outputRenderTarget && outputRenderTarget.isXRRenderTarget === true ) {
  27637. pixelRatio = 1;
  27638. camera = renderer.xr.getCamera();
  27639. renderer.xr.updateCamera( camera );
  27640. _size.set( outputRenderTarget.width, outputRenderTarget.height );
  27641. } else {
  27642. camera = this.camera;
  27643. pixelRatio = renderer.getPixelRatio();
  27644. renderer.getSize( _size );
  27645. }
  27646. this._pixelRatio = pixelRatio;
  27647. this.setSize( _size.width, _size.height );
  27648. const currentRenderTarget = renderer.getRenderTarget();
  27649. const currentMRT = renderer.getMRT();
  27650. const currentAutoClear = renderer.autoClear;
  27651. const currentTransparent = renderer.transparent;
  27652. const currentOpaque = renderer.opaque;
  27653. const currentMask = camera.layers.mask;
  27654. const currentContextNode = renderer.contextNode;
  27655. const currentOverrideMaterial = scene.overrideMaterial;
  27656. this._cameraNear.value = camera.near;
  27657. this._cameraFar.value = camera.far;
  27658. if ( this._layers !== null ) {
  27659. camera.layers.mask = this._layers.mask;
  27660. }
  27661. for ( const name in this._previousTextures ) {
  27662. this.toggleTexture( name );
  27663. }
  27664. if ( this.overrideMaterial !== null ) {
  27665. scene.overrideMaterial = this.overrideMaterial;
  27666. }
  27667. renderer.setRenderTarget( this.renderTarget );
  27668. renderer.setMRT( this._mrt );
  27669. renderer.autoClear = true;
  27670. renderer.transparent = this.transparent;
  27671. renderer.opaque = this.opaque;
  27672. if ( this.contextNode !== null ) {
  27673. if ( this._contextNodeCache === null || this._contextNodeCache.version !== this.version ) {
  27674. this._contextNodeCache = {
  27675. version: this.version,
  27676. context: context( { ...renderer.contextNode.getFlowContextData(), ...this.contextNode.getFlowContextData() } )
  27677. };
  27678. }
  27679. renderer.contextNode = this._contextNodeCache.context;
  27680. }
  27681. const currentSceneName = scene.name;
  27682. scene.name = this.name ? this.name : scene.name;
  27683. renderer.render( scene, camera );
  27684. scene.name = currentSceneName;
  27685. scene.overrideMaterial = currentOverrideMaterial;
  27686. renderer.setRenderTarget( currentRenderTarget );
  27687. renderer.setMRT( currentMRT );
  27688. renderer.autoClear = currentAutoClear;
  27689. renderer.transparent = currentTransparent;
  27690. renderer.opaque = currentOpaque;
  27691. renderer.contextNode = currentContextNode;
  27692. camera.layers.mask = currentMask;
  27693. }
  27694. /**
  27695. * Sets the size of the pass's render target. Honors the pixel ratio.
  27696. *
  27697. * @param {number} width - The width to set.
  27698. * @param {number} height - The height to set.
  27699. */
  27700. setSize( width, height ) {
  27701. this._width = width;
  27702. this._height = height;
  27703. const effectiveWidth = Math.floor( this._width * this._pixelRatio * this._resolutionScale );
  27704. const effectiveHeight = Math.floor( this._height * this._pixelRatio * this._resolutionScale );
  27705. this.renderTarget.setSize( effectiveWidth, effectiveHeight );
  27706. if ( this._scissor !== null ) this.renderTarget.scissor.copy( this._scissor );
  27707. if ( this._viewport !== null ) this.renderTarget.viewport.copy( this._viewport );
  27708. }
  27709. /**
  27710. * This method allows to define the pass's scissor rectangle. By default, the scissor rectangle is kept
  27711. * in sync with the pass's dimensions. To reverse the process and use auto-sizing again, call the method
  27712. * with `null` as the single argument.
  27713. *
  27714. * @param {?(number | Vector4)} x - The horizontal coordinate for the lower left corner of the box in logical pixel unit.
  27715. * Instead of passing four arguments, the method also works with a single four-dimensional vector.
  27716. * @param {number} y - The vertical coordinate for the lower left corner of the box in logical pixel unit.
  27717. * @param {number} width - The width of the scissor box in logical pixel unit.
  27718. * @param {number} height - The height of the scissor box in logical pixel unit.
  27719. */
  27720. setScissor( x, y, width, height ) {
  27721. if ( x === null ) {
  27722. this._scissor = null;
  27723. } else {
  27724. if ( this._scissor === null ) this._scissor = new Vector4();
  27725. if ( x.isVector4 ) {
  27726. this._scissor.copy( x );
  27727. } else {
  27728. this._scissor.set( x, y, width, height );
  27729. }
  27730. this._scissor.multiplyScalar( this._pixelRatio * this._resolutionScale ).floor();
  27731. }
  27732. }
  27733. /**
  27734. * This method allows to define the pass's viewport. By default, the viewport is kept in sync
  27735. * with the pass's dimensions. To reverse the process and use auto-sizing again, call the method
  27736. * with `null` as the single argument.
  27737. *
  27738. * @param {number | Vector4} x - The horizontal coordinate for the lower left corner of the viewport origin in logical pixel unit.
  27739. * @param {number} y - The vertical coordinate for the lower left corner of the viewport origin in logical pixel unit.
  27740. * @param {number} width - The width of the viewport in logical pixel unit.
  27741. * @param {number} height - The height of the viewport in logical pixel unit.
  27742. */
  27743. setViewport( x, y, width, height ) {
  27744. if ( x === null ) {
  27745. this._viewport = null;
  27746. } else {
  27747. if ( this._viewport === null ) this._viewport = new Vector4();
  27748. if ( x.isVector4 ) {
  27749. this._viewport.copy( x );
  27750. } else {
  27751. this._viewport.set( x, y, width, height );
  27752. }
  27753. this._viewport.multiplyScalar( this._pixelRatio * this._resolutionScale ).floor();
  27754. }
  27755. }
  27756. /**
  27757. * Sets the pixel ratio the pass's render target and updates the size.
  27758. *
  27759. * @param {number} pixelRatio - The pixel ratio to set.
  27760. */
  27761. setPixelRatio( pixelRatio ) {
  27762. this._pixelRatio = pixelRatio;
  27763. this.setSize( this._width, this._height );
  27764. }
  27765. /**
  27766. * Frees internal resources. Should be called when the node is no longer in use.
  27767. */
  27768. dispose() {
  27769. this.renderTarget.dispose();
  27770. }
  27771. }
  27772. /**
  27773. * @static
  27774. * @type {'color'}
  27775. * @default 'color'
  27776. */
  27777. PassNode.COLOR = 'color';
  27778. /**
  27779. * @static
  27780. * @type {'depth'}
  27781. * @default 'depth'
  27782. */
  27783. PassNode.DEPTH = 'depth';
  27784. /**
  27785. * TSL function for creating a pass node.
  27786. *
  27787. * @tsl
  27788. * @function
  27789. * @param {Scene} scene - A reference to the scene.
  27790. * @param {Camera} camera - A reference to the camera.
  27791. * @param {Object} options - Options for the internal render target.
  27792. * @returns {PassNode}
  27793. */
  27794. const pass = ( scene, camera, options ) => nodeObject( new PassNode( PassNode.COLOR, scene, camera, options ) );
  27795. /**
  27796. * TSL function for creating a pass texture node.
  27797. *
  27798. * @tsl
  27799. * @function
  27800. * @param {PassNode} pass - The pass node.
  27801. * @param {Texture} texture - The output texture.
  27802. * @returns {PassTextureNode}
  27803. */
  27804. const passTexture = ( pass, texture ) => nodeObject( new PassTextureNode( pass, texture ) );
  27805. /**
  27806. * TSL function for creating a depth pass node.
  27807. *
  27808. * @tsl
  27809. * @function
  27810. * @param {Scene} scene - A reference to the scene.
  27811. * @param {Camera} camera - A reference to the camera.
  27812. * @param {Object} options - Options for the internal render target.
  27813. * @returns {PassNode}
  27814. */
  27815. const depthPass = ( scene, camera, options ) => nodeObject( new PassNode( PassNode.DEPTH, scene, camera, options ) );
  27816. /**
  27817. * Represents a render pass for producing a toon outline effect on compatible objects.
  27818. * Only 3D objects with materials of type `MeshToonMaterial` and `MeshToonNodeMaterial`
  27819. * will receive the outline.
  27820. *
  27821. * ```js
  27822. * const postProcessing = new PostProcessing( renderer );
  27823. *
  27824. * const scenePass = toonOutlinePass( scene, camera );
  27825. *
  27826. * postProcessing.outputNode = scenePass;
  27827. * ```
  27828. * @augments PassNode
  27829. */
  27830. class ToonOutlinePassNode extends PassNode {
  27831. static get type() {
  27832. return 'ToonOutlinePassNode';
  27833. }
  27834. /**
  27835. * Constructs a new outline pass node.
  27836. *
  27837. * @param {Scene} scene - A reference to the scene.
  27838. * @param {Camera} camera - A reference to the camera.
  27839. * @param {Node} colorNode - Defines the outline's color.
  27840. * @param {Node} thicknessNode - Defines the outline's thickness.
  27841. * @param {Node} alphaNode - Defines the outline's alpha.
  27842. */
  27843. constructor( scene, camera, colorNode, thicknessNode, alphaNode ) {
  27844. super( PassNode.COLOR, scene, camera );
  27845. /**
  27846. * Defines the outline's color.
  27847. *
  27848. * @type {Node}
  27849. */
  27850. this.colorNode = colorNode;
  27851. /**
  27852. * Defines the outline's thickness.
  27853. *
  27854. * @type {Node}
  27855. */
  27856. this.thicknessNode = thicknessNode;
  27857. /**
  27858. * Defines the outline's alpha.
  27859. *
  27860. * @type {Node}
  27861. */
  27862. this.alphaNode = alphaNode;
  27863. /**
  27864. * An internal material cache.
  27865. *
  27866. * @private
  27867. * @type {WeakMap<Material, NodeMaterial>}
  27868. */
  27869. this._materialCache = new WeakMap();
  27870. /**
  27871. * The name of this pass.
  27872. *
  27873. * @type {string}
  27874. * @default 'Outline Pass'
  27875. */
  27876. this.name = 'Outline Pass';
  27877. }
  27878. updateBefore( frame ) {
  27879. const { renderer } = frame;
  27880. const currentRenderObjectFunction = renderer.getRenderObjectFunction();
  27881. renderer.setRenderObjectFunction( ( object, scene, camera, geometry, material, group, lightsNode, clippingContext ) => {
  27882. // only render outline for supported materials
  27883. if ( material.isMeshToonMaterial || material.isMeshToonNodeMaterial ) {
  27884. if ( material.wireframe === false ) {
  27885. const outlineMaterial = this._getOutlineMaterial( material );
  27886. renderer.renderObject( object, scene, camera, geometry, outlineMaterial, group, lightsNode, clippingContext );
  27887. }
  27888. }
  27889. // default
  27890. renderer.renderObject( object, scene, camera, geometry, material, group, lightsNode, clippingContext );
  27891. } );
  27892. super.updateBefore( frame );
  27893. renderer.setRenderObjectFunction( currentRenderObjectFunction );
  27894. }
  27895. /**
  27896. * Creates the material used for outline rendering.
  27897. *
  27898. * @private
  27899. * @return {NodeMaterial} The outline material.
  27900. */
  27901. _createMaterial() {
  27902. const material = new NodeMaterial();
  27903. material.isMeshToonOutlineMaterial = true;
  27904. material.name = 'Toon_Outline';
  27905. material.side = BackSide;
  27906. // vertex node
  27907. const outlineNormal = normalLocal.negate();
  27908. const mvp = cameraProjectionMatrix.mul( modelViewMatrix );
  27909. const ratio = float( 1.0 ); // TODO: support outline thickness ratio for each vertex
  27910. const pos = mvp.mul( vec4( positionLocal, 1.0 ) );
  27911. const pos2 = mvp.mul( vec4( positionLocal.add( outlineNormal ), 1.0 ) );
  27912. const norm = normalize( pos.sub( pos2 ) ); // NOTE: subtract pos2 from pos because BackSide objectNormal is negative
  27913. material.vertexNode = pos.add( norm.mul( this.thicknessNode ).mul( pos.w ).mul( ratio ) );
  27914. // color node
  27915. material.colorNode = vec4( this.colorNode, this.alphaNode );
  27916. return material;
  27917. }
  27918. /**
  27919. * For the given toon material, this method returns a corresponding
  27920. * outline material.
  27921. *
  27922. * @private
  27923. * @param {(MeshToonMaterial|MeshToonNodeMaterial)} originalMaterial - The toon material.
  27924. * @return {NodeMaterial} The outline material.
  27925. */
  27926. _getOutlineMaterial( originalMaterial ) {
  27927. let outlineMaterial = this._materialCache.get( originalMaterial );
  27928. if ( outlineMaterial === undefined ) {
  27929. outlineMaterial = this._createMaterial();
  27930. this._materialCache.set( originalMaterial, outlineMaterial );
  27931. }
  27932. return outlineMaterial;
  27933. }
  27934. }
  27935. /**
  27936. * TSL function for creating a toon outline pass node.
  27937. *
  27938. * @tsl
  27939. * @function
  27940. * @param {Scene} scene - A reference to the scene.
  27941. * @param {Camera} camera - A reference to the camera.
  27942. * @param {Color} color - Defines the outline's color.
  27943. * @param {number} [thickness=0.003] - Defines the outline's thickness.
  27944. * @param {number} [alpha=1] - Defines the outline's alpha.
  27945. * @returns {ToonOutlinePassNode}
  27946. */
  27947. 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 ) ) );
  27948. /**
  27949. * Linear tone mapping, exposure only.
  27950. *
  27951. * @tsl
  27952. * @function
  27953. * @param {Node<vec3>} color - The color that should be tone mapped.
  27954. * @param {Node<float>} exposure - The exposure.
  27955. * @return {Node<vec3>} The tone mapped color.
  27956. */
  27957. const linearToneMapping = /*@__PURE__*/ Fn( ( [ color, exposure ] ) => {
  27958. return color.mul( exposure ).clamp();
  27959. } ).setLayout( {
  27960. name: 'linearToneMapping',
  27961. type: 'vec3',
  27962. inputs: [
  27963. { name: 'color', type: 'vec3' },
  27964. { name: 'exposure', type: 'float' }
  27965. ]
  27966. } );
  27967. /**
  27968. * Reinhard tone mapping.
  27969. *
  27970. * Reference: {@link https://www.cs.utah.edu/docs/techreports/2002/pdf/UUCS-02-001.pdf}
  27971. *
  27972. * @tsl
  27973. * @function
  27974. * @param {Node<vec3>} color - The color that should be tone mapped.
  27975. * @param {Node<float>} exposure - The exposure.
  27976. * @return {Node<vec3>} The tone mapped color.
  27977. */
  27978. const reinhardToneMapping = /*@__PURE__*/ Fn( ( [ color, exposure ] ) => {
  27979. color = color.mul( exposure );
  27980. return color.div( color.add( 1.0 ) ).clamp();
  27981. } ).setLayout( {
  27982. name: 'reinhardToneMapping',
  27983. type: 'vec3',
  27984. inputs: [
  27985. { name: 'color', type: 'vec3' },
  27986. { name: 'exposure', type: 'float' }
  27987. ]
  27988. } );
  27989. /**
  27990. * Cineon tone mapping.
  27991. *
  27992. * Reference: {@link http://filmicworlds.com/blog/filmic-tonemapping-operators/}
  27993. *
  27994. * @tsl
  27995. * @function
  27996. * @param {Node<vec3>} color - The color that should be tone mapped.
  27997. * @param {Node<float>} exposure - The exposure.
  27998. * @return {Node<vec3>} The tone mapped color.
  27999. */
  28000. const cineonToneMapping = /*@__PURE__*/ Fn( ( [ color, exposure ] ) => {
  28001. // filmic operator by Jim Hejl and Richard Burgess-Dawson
  28002. color = color.mul( exposure );
  28003. color = color.sub( 0.004 ).max( 0.0 );
  28004. const a = color.mul( color.mul( 6.2 ).add( 0.5 ) );
  28005. const b = color.mul( color.mul( 6.2 ).add( 1.7 ) ).add( 0.06 );
  28006. return a.div( b ).pow( 2.2 );
  28007. } ).setLayout( {
  28008. name: 'cineonToneMapping',
  28009. type: 'vec3',
  28010. inputs: [
  28011. { name: 'color', type: 'vec3' },
  28012. { name: 'exposure', type: 'float' }
  28013. ]
  28014. } );
  28015. // source: https://github.com/selfshadow/ltc_code/blob/master/webgl/shaders/ltc/ltc_blit.fs
  28016. const RRTAndODTFit = /*@__PURE__*/ Fn( ( [ color ] ) => {
  28017. const a = color.mul( color.add( 0.0245786 ) ).sub( 0.000090537 );
  28018. const b = color.mul( color.add( 0.4329510 ).mul( 0.983729 ) ).add( 0.238081 );
  28019. return a.div( b );
  28020. } );
  28021. /**
  28022. * ACESFilmic tone mapping.
  28023. *
  28024. * Reference: {@link https://github.com/selfshadow/ltc_code/blob/master/webgl/shaders/ltc/ltc_blit.fs}
  28025. *
  28026. * @tsl
  28027. * @function
  28028. * @param {Node<vec3>} color - The color that should be tone mapped.
  28029. * @param {Node<float>} exposure - The exposure.
  28030. * @return {Node<vec3>} The tone mapped color.
  28031. */
  28032. const acesFilmicToneMapping = /*@__PURE__*/ Fn( ( [ color, exposure ] ) => {
  28033. // sRGB => XYZ => D65_2_D60 => AP1 => RRT_SAT
  28034. const ACESInputMat = mat3(
  28035. 0.59719, 0.35458, 0.04823,
  28036. 0.07600, 0.90834, 0.01566,
  28037. 0.02840, 0.13383, 0.83777
  28038. );
  28039. // ODT_SAT => XYZ => D60_2_D65 => sRGB
  28040. const ACESOutputMat = mat3(
  28041. 1.60475, -0.53108, -0.07367,
  28042. -0.10208, 1.10813, -605e-5,
  28043. -327e-5, -0.07276, 1.07602
  28044. );
  28045. color = color.mul( exposure ).div( 0.6 );
  28046. color = ACESInputMat.mul( color );
  28047. // Apply RRT and ODT
  28048. color = RRTAndODTFit( color );
  28049. color = ACESOutputMat.mul( color );
  28050. // Clamp to [0, 1]
  28051. return color.clamp();
  28052. } ).setLayout( {
  28053. name: 'acesFilmicToneMapping',
  28054. type: 'vec3',
  28055. inputs: [
  28056. { name: 'color', type: 'vec3' },
  28057. { name: 'exposure', type: 'float' }
  28058. ]
  28059. } );
  28060. 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 ) );
  28061. 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 ) );
  28062. const agxDefaultContrastApprox = /*@__PURE__*/ Fn( ( [ x_immutable ] ) => {
  28063. const x = vec3( x_immutable ).toVar();
  28064. const x2 = vec3( x.mul( x ) ).toVar();
  28065. const x4 = vec3( x2.mul( x2 ) ).toVar();
  28066. 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 ) ) ) );
  28067. } );
  28068. /**
  28069. * AgX tone mapping.
  28070. *
  28071. * @tsl
  28072. * @function
  28073. * @param {Node<vec3>} color - The color that should be tone mapped.
  28074. * @param {Node<float>} exposure - The exposure.
  28075. * @return {Node<vec3>} The tone mapped color.
  28076. */
  28077. const agxToneMapping = /*@__PURE__*/ Fn( ( [ color, exposure ] ) => {
  28078. const colortone = vec3( color ).toVar();
  28079. const AgXInsetMatrix = mat3( vec3( 0.856627153315983, 0.137318972929847, 0.11189821299995 ), vec3( 0.0951212405381588, 0.761241990602591, 0.0767994186031903 ), vec3( 0.0482516061458583, 0.101439036467562, 0.811302368396859 ) );
  28080. const AgXOutsetMatrix = mat3( vec3( 1.1271005818144368, -0.1413297634984383, -0.14132976349843826 ), vec3( -0.11060664309660323, 1.157823702216272, -0.11060664309660294 ), vec3( -0.016493938717834573, -0.016493938717834257, 1.2519364065950405 ) );
  28081. const AgxMinEv = float( -12.47393 );
  28082. const AgxMaxEv = float( 4.026069 );
  28083. colortone.mulAssign( exposure );
  28084. colortone.assign( LINEAR_SRGB_TO_LINEAR_REC2020.mul( colortone ) );
  28085. colortone.assign( AgXInsetMatrix.mul( colortone ) );
  28086. colortone.assign( max$1( colortone, 1e-10 ) );
  28087. colortone.assign( log2( colortone ) );
  28088. colortone.assign( colortone.sub( AgxMinEv ).div( AgxMaxEv.sub( AgxMinEv ) ) );
  28089. colortone.assign( clamp( colortone, 0.0, 1.0 ) );
  28090. colortone.assign( agxDefaultContrastApprox( colortone ) );
  28091. colortone.assign( AgXOutsetMatrix.mul( colortone ) );
  28092. colortone.assign( pow( max$1( vec3( 0.0 ), colortone ), vec3( 2.2 ) ) );
  28093. colortone.assign( LINEAR_REC2020_TO_LINEAR_SRGB.mul( colortone ) );
  28094. colortone.assign( clamp( colortone, 0.0, 1.0 ) );
  28095. return colortone;
  28096. } ).setLayout( {
  28097. name: 'agxToneMapping',
  28098. type: 'vec3',
  28099. inputs: [
  28100. { name: 'color', type: 'vec3' },
  28101. { name: 'exposure', type: 'float' }
  28102. ]
  28103. } );
  28104. /**
  28105. * Neutral tone mapping.
  28106. *
  28107. * Reference: {@link https://modelviewer.dev/examples/tone-mapping}
  28108. *
  28109. * @tsl
  28110. * @function
  28111. * @param {Node<vec3>} color - The color that should be tone mapped.
  28112. * @param {Node<float>} exposure - The exposure.
  28113. * @return {Node<vec3>} The tone mapped color.
  28114. */
  28115. const neutralToneMapping = /*@__PURE__*/ Fn( ( [ color, exposure ] ) => {
  28116. const StartCompression = float( 0.8 - 0.04 );
  28117. const Desaturation = float( 0.15 );
  28118. color = color.mul( exposure );
  28119. const x = min$1( color.r, min$1( color.g, color.b ) );
  28120. const offset = select( x.lessThan( 0.08 ), x.sub( mul( 6.25, x.mul( x ) ) ), 0.04 );
  28121. color.subAssign( offset );
  28122. const peak = max$1( color.r, max$1( color.g, color.b ) );
  28123. If( peak.lessThan( StartCompression ), () => {
  28124. return color;
  28125. } );
  28126. const d = sub( 1, StartCompression );
  28127. const newPeak = sub( 1, d.mul( d ).div( peak.add( d.sub( StartCompression ) ) ) );
  28128. color.mulAssign( newPeak.div( peak ) );
  28129. const g = sub( 1, div( 1, Desaturation.mul( peak.sub( newPeak ) ).add( 1 ) ) );
  28130. return mix( color, vec3( newPeak ), g );
  28131. } ).setLayout( {
  28132. name: 'neutralToneMapping',
  28133. type: 'vec3',
  28134. inputs: [
  28135. { name: 'color', type: 'vec3' },
  28136. { name: 'exposure', type: 'float' }
  28137. ]
  28138. } );
  28139. /**
  28140. * This class represents native code sections. It is the base
  28141. * class for modules like {@link FunctionNode} which allows to implement
  28142. * functions with native shader languages.
  28143. *
  28144. * @augments Node
  28145. */
  28146. class CodeNode extends Node {
  28147. static get type() {
  28148. return 'CodeNode';
  28149. }
  28150. /**
  28151. * Constructs a new code node.
  28152. *
  28153. * @param {string} [code=''] - The native code.
  28154. * @param {Array<Node>} [includes=[]] - An array of includes.
  28155. * @param {('js'|'wgsl'|'glsl')} [language=''] - The used language.
  28156. */
  28157. constructor( code = '', includes = [], language = '' ) {
  28158. super( 'code' );
  28159. /**
  28160. * This flag can be used for type testing.
  28161. *
  28162. * @type {boolean}
  28163. * @readonly
  28164. * @default true
  28165. */
  28166. this.isCodeNode = true;
  28167. /**
  28168. * This flag is used for global cache.
  28169. *
  28170. * @type {boolean}
  28171. * @default true
  28172. */
  28173. this.global = true;
  28174. /**
  28175. * The native code.
  28176. *
  28177. * @type {string}
  28178. * @default ''
  28179. */
  28180. this.code = code;
  28181. /**
  28182. * An array of includes
  28183. *
  28184. * @type {Array<Node>}
  28185. * @default []
  28186. */
  28187. this.includes = includes;
  28188. /**
  28189. * The used language.
  28190. *
  28191. * @type {('js'|'wgsl'|'glsl')}
  28192. * @default ''
  28193. */
  28194. this.language = language;
  28195. }
  28196. /**
  28197. * Sets the includes of this code node.
  28198. *
  28199. * @param {Array<Node>} includes - The includes to set.
  28200. * @return {CodeNode} A reference to this node.
  28201. */
  28202. setIncludes( includes ) {
  28203. this.includes = includes;
  28204. return this;
  28205. }
  28206. /**
  28207. * Returns the includes of this code node.
  28208. *
  28209. * @param {NodeBuilder} builder - The current node builder.
  28210. * @return {Array<Node>} The includes.
  28211. */
  28212. getIncludes( /*builder*/ ) {
  28213. return this.includes;
  28214. }
  28215. generate( builder ) {
  28216. const includes = this.getIncludes( builder );
  28217. for ( const include of includes ) {
  28218. include.build( builder );
  28219. }
  28220. const nodeCode = builder.getCodeFromNode( this, this.getNodeType( builder ) );
  28221. nodeCode.code = this.code;
  28222. return nodeCode.code;
  28223. }
  28224. serialize( data ) {
  28225. super.serialize( data );
  28226. data.code = this.code;
  28227. data.language = this.language;
  28228. }
  28229. deserialize( data ) {
  28230. super.deserialize( data );
  28231. this.code = data.code;
  28232. this.language = data.language;
  28233. }
  28234. }
  28235. /**
  28236. * TSL function for creating a code node.
  28237. *
  28238. * @tsl
  28239. * @function
  28240. * @param {string} [code] - The native code.
  28241. * @param {?Array<Node>} [includes=[]] - An array of includes.
  28242. * @param {?('js'|'wgsl'|'glsl')} [language=''] - The used language.
  28243. * @returns {CodeNode}
  28244. */
  28245. const code = /*@__PURE__*/ nodeProxy( CodeNode ).setParameterLength( 1, 3 );
  28246. /**
  28247. * TSL function for creating a JS code node.
  28248. *
  28249. * @tsl
  28250. * @function
  28251. * @param {string} src - The native code.
  28252. * @param {Array<Node>} includes - An array of includes.
  28253. * @returns {CodeNode}
  28254. */
  28255. const js = ( src, includes ) => code( src, includes, 'js' );
  28256. /**
  28257. * TSL function for creating a WGSL code node.
  28258. *
  28259. * @tsl
  28260. * @function
  28261. * @param {string} src - The native code.
  28262. * @param {Array<Node>} includes - An array of includes.
  28263. * @returns {CodeNode}
  28264. */
  28265. const wgsl = ( src, includes ) => code( src, includes, 'wgsl' );
  28266. /**
  28267. * TSL function for creating a GLSL code node.
  28268. *
  28269. * @tsl
  28270. * @function
  28271. * @param {string} src - The native code.
  28272. * @param {Array<Node>} includes - An array of includes.
  28273. * @returns {CodeNode}
  28274. */
  28275. const glsl = ( src, includes ) => code( src, includes, 'glsl' );
  28276. /**
  28277. * This class represents a native shader function. It can be used to implement
  28278. * certain aspects of a node material with native shader code. There are two predefined
  28279. * TSL functions for easier usage.
  28280. *
  28281. * - `wgslFn`: Creates a WGSL function node.
  28282. * - `glslFn`: Creates a GLSL function node.
  28283. *
  28284. * A basic example with one include looks like so:
  28285. *
  28286. * ```js
  28287. * const desaturateWGSLFn = wgslFn( `
  28288. * fn desaturate( color:vec3<f32> ) -> vec3<f32> {
  28289. * let lum = vec3<f32>( 0.299, 0.587, 0.114 );
  28290. * return vec3<f32>( dot( lum, color ) );
  28291. * }`
  28292. *);
  28293. * const someWGSLFn = wgslFn( `
  28294. * fn someFn( color:vec3<f32> ) -> vec3<f32> {
  28295. * return desaturate( color );
  28296. * }
  28297. * `, [ desaturateWGSLFn ] );
  28298. * material.colorNode = someWGSLFn( { color: texture( map ) } );
  28299. *```
  28300. * @augments CodeNode
  28301. */
  28302. class FunctionNode extends CodeNode {
  28303. static get type() {
  28304. return 'FunctionNode';
  28305. }
  28306. /**
  28307. * Constructs a new function node.
  28308. *
  28309. * @param {string} [code=''] - The native code.
  28310. * @param {Array<Node>} [includes=[]] - An array of includes.
  28311. * @param {('js'|'wgsl'|'glsl')} [language=''] - The used language.
  28312. */
  28313. constructor( code = '', includes = [], language = '' ) {
  28314. super( code, includes, language );
  28315. }
  28316. /**
  28317. * Returns the type of this function node.
  28318. *
  28319. * @param {NodeBuilder} builder - The current node builder.
  28320. * @return {string} The type.
  28321. */
  28322. getNodeType( builder ) {
  28323. return this.getNodeFunction( builder ).type;
  28324. }
  28325. /**
  28326. * Returns the type of a member of this function node.
  28327. *
  28328. * @param {NodeBuilder} builder - The current node builder.
  28329. * @param {string} name - The name of the member.
  28330. * @return {string} The type of the member.
  28331. */
  28332. getMemberType( builder, name ) {
  28333. const type = this.getNodeType( builder );
  28334. const structType = builder.getStructTypeNode( type );
  28335. return structType.getMemberType( builder, name );
  28336. }
  28337. /**
  28338. * Returns the inputs of this function node.
  28339. *
  28340. * @param {NodeBuilder} builder - The current node builder.
  28341. * @return {Array<NodeFunctionInput>} The inputs.
  28342. */
  28343. getInputs( builder ) {
  28344. return this.getNodeFunction( builder ).inputs;
  28345. }
  28346. /**
  28347. * Returns the node function for this function node.
  28348. *
  28349. * @param {NodeBuilder} builder - The current node builder.
  28350. * @return {NodeFunction} The node function.
  28351. */
  28352. getNodeFunction( builder ) {
  28353. const nodeData = builder.getDataFromNode( this );
  28354. let nodeFunction = nodeData.nodeFunction;
  28355. if ( nodeFunction === undefined ) {
  28356. nodeFunction = builder.parser.parseFunction( this.code );
  28357. nodeData.nodeFunction = nodeFunction;
  28358. }
  28359. return nodeFunction;
  28360. }
  28361. generate( builder, output ) {
  28362. super.generate( builder );
  28363. const nodeFunction = this.getNodeFunction( builder );
  28364. const name = nodeFunction.name;
  28365. const type = nodeFunction.type;
  28366. const nodeCode = builder.getCodeFromNode( this, type );
  28367. if ( name !== '' ) {
  28368. // use a custom property name
  28369. nodeCode.name = name;
  28370. }
  28371. const propertyName = builder.getPropertyName( nodeCode );
  28372. const code = this.getNodeFunction( builder ).getCode( propertyName );
  28373. nodeCode.code = code + '\n';
  28374. if ( output === 'property' ) {
  28375. return propertyName;
  28376. } else {
  28377. return builder.format( `${ propertyName }()`, type, output );
  28378. }
  28379. }
  28380. }
  28381. const nativeFn = ( code, includes = [], language = '' ) => {
  28382. for ( let i = 0; i < includes.length; i ++ ) {
  28383. const include = includes[ i ];
  28384. // TSL Function: glslFn, wgslFn
  28385. if ( typeof include === 'function' ) {
  28386. includes[ i ] = include.functionNode;
  28387. }
  28388. }
  28389. const functionNode = nodeObject( new FunctionNode( code, includes, language ) );
  28390. const fn = ( ...params ) => functionNode.call( ...params );
  28391. fn.functionNode = functionNode;
  28392. return fn;
  28393. };
  28394. const glslFn = ( code, includes ) => nativeFn( code, includes, 'glsl' );
  28395. const wgslFn = ( code, includes ) => nativeFn( code, includes, 'wgsl' );
  28396. /**
  28397. * `ScriptableNode` uses this class to manage script inputs and outputs.
  28398. *
  28399. * @augments Node
  28400. */
  28401. class ScriptableValueNode extends Node {
  28402. static get type() {
  28403. return 'ScriptableValueNode';
  28404. }
  28405. /**
  28406. * Constructs a new scriptable node.
  28407. *
  28408. * @param {any} [value=null] - The value.
  28409. */
  28410. constructor( value = null ) {
  28411. super();
  28412. /**
  28413. * A reference to the value.
  28414. *
  28415. * @private
  28416. * @default null
  28417. */
  28418. this._value = value;
  28419. /**
  28420. * Depending on the type of `_value`, this property might cache parsed data.
  28421. *
  28422. * @private
  28423. * @default null
  28424. */
  28425. this._cache = null;
  28426. /**
  28427. * If this node represents an input, this property represents the input type.
  28428. *
  28429. * @type {?string}
  28430. * @default null
  28431. */
  28432. this.inputType = null;
  28433. /**
  28434. * If this node represents an output, this property represents the output type.
  28435. *
  28436. * @type {?string}
  28437. * @default null
  28438. */
  28439. this.outputType = null;
  28440. /**
  28441. * An event dispatcher for managing events.
  28442. *
  28443. * @type {EventDispatcher}
  28444. */
  28445. this.events = new EventDispatcher();
  28446. /**
  28447. * This flag can be used for type testing.
  28448. *
  28449. * @type {boolean}
  28450. * @readonly
  28451. * @default true
  28452. */
  28453. this.isScriptableValueNode = true;
  28454. }
  28455. /**
  28456. * Whether this node represents an output or not.
  28457. *
  28458. * @type {boolean}
  28459. * @readonly
  28460. * @default true
  28461. */
  28462. get isScriptableOutputNode() {
  28463. return this.outputType !== null;
  28464. }
  28465. set value( val ) {
  28466. if ( this._value === val ) return;
  28467. if ( this._cache && this.inputType === 'URL' && this.value.value instanceof ArrayBuffer ) {
  28468. URL.revokeObjectURL( this._cache );
  28469. this._cache = null;
  28470. }
  28471. this._value = val;
  28472. this.events.dispatchEvent( { type: 'change' } );
  28473. this.refresh();
  28474. }
  28475. /**
  28476. * The node's value.
  28477. *
  28478. * @type {any}
  28479. */
  28480. get value() {
  28481. return this._value;
  28482. }
  28483. /**
  28484. * Dispatches the `refresh` event.
  28485. */
  28486. refresh() {
  28487. this.events.dispatchEvent( { type: 'refresh' } );
  28488. }
  28489. /**
  28490. * The `value` property usually represents a node or even binary data in form of array buffers.
  28491. * In this case, this method tries to return the actual value behind the complex type.
  28492. *
  28493. * @return {any} The value.
  28494. */
  28495. getValue() {
  28496. const value = this.value;
  28497. if ( value && this._cache === null && this.inputType === 'URL' && value.value instanceof ArrayBuffer ) {
  28498. this._cache = URL.createObjectURL( new Blob( [ value.value ] ) );
  28499. } else if ( value && value.value !== null && value.value !== undefined && (
  28500. ( ( this.inputType === 'URL' || this.inputType === 'String' ) && typeof value.value === 'string' ) ||
  28501. ( this.inputType === 'Number' && typeof value.value === 'number' ) ||
  28502. ( this.inputType === 'Vector2' && value.value.isVector2 ) ||
  28503. ( this.inputType === 'Vector3' && value.value.isVector3 ) ||
  28504. ( this.inputType === 'Vector4' && value.value.isVector4 ) ||
  28505. ( this.inputType === 'Color' && value.value.isColor ) ||
  28506. ( this.inputType === 'Matrix3' && value.value.isMatrix3 ) ||
  28507. ( this.inputType === 'Matrix4' && value.value.isMatrix4 )
  28508. ) ) {
  28509. return value.value;
  28510. }
  28511. return this._cache || value;
  28512. }
  28513. /**
  28514. * Overwritten since the node type is inferred from the value.
  28515. *
  28516. * @param {NodeBuilder} builder - The current node builder.
  28517. * @return {string} The node type.
  28518. */
  28519. getNodeType( builder ) {
  28520. return this.value && this.value.isNode ? this.value.getNodeType( builder ) : 'float';
  28521. }
  28522. setup() {
  28523. return this.value && this.value.isNode ? this.value : float();
  28524. }
  28525. serialize( data ) {
  28526. super.serialize( data );
  28527. if ( this.value !== null ) {
  28528. if ( this.inputType === 'ArrayBuffer' ) {
  28529. data.value = arrayBufferToBase64( this.value );
  28530. } else {
  28531. data.value = this.value ? this.value.toJSON( data.meta ).uuid : null;
  28532. }
  28533. } else {
  28534. data.value = null;
  28535. }
  28536. data.inputType = this.inputType;
  28537. data.outputType = this.outputType;
  28538. }
  28539. deserialize( data ) {
  28540. super.deserialize( data );
  28541. let value = null;
  28542. if ( data.value !== null ) {
  28543. if ( data.inputType === 'ArrayBuffer' ) {
  28544. value = base64ToArrayBuffer( data.value );
  28545. } else if ( data.inputType === 'Texture' ) {
  28546. value = data.meta.textures[ data.value ];
  28547. } else {
  28548. value = data.meta.nodes[ data.value ] || null;
  28549. }
  28550. }
  28551. this.value = value;
  28552. this.inputType = data.inputType;
  28553. this.outputType = data.outputType;
  28554. }
  28555. }
  28556. /**
  28557. * TSL function for creating a scriptable value node.
  28558. *
  28559. * @tsl
  28560. * @function
  28561. * @param {any} [value] - The value.
  28562. * @returns {ScriptableValueNode}
  28563. */
  28564. const scriptableValue = /*@__PURE__*/ nodeProxy( ScriptableValueNode ).setParameterLength( 1 );
  28565. /**
  28566. * A Map-like data structure for managing resources of scriptable nodes.
  28567. *
  28568. * @augments Map
  28569. */
  28570. class Resources extends Map {
  28571. get( key, callback = null, ...params ) {
  28572. if ( this.has( key ) ) return super.get( key );
  28573. if ( callback !== null ) {
  28574. const value = callback( ...params );
  28575. this.set( key, value );
  28576. return value;
  28577. }
  28578. }
  28579. }
  28580. class Parameters {
  28581. constructor( scriptableNode ) {
  28582. this.scriptableNode = scriptableNode;
  28583. }
  28584. get parameters() {
  28585. return this.scriptableNode.parameters;
  28586. }
  28587. get layout() {
  28588. return this.scriptableNode.getLayout();
  28589. }
  28590. getInputLayout( id ) {
  28591. return this.scriptableNode.getInputLayout( id );
  28592. }
  28593. get( name ) {
  28594. const param = this.parameters[ name ];
  28595. const value = param ? param.getValue() : null;
  28596. return value;
  28597. }
  28598. }
  28599. /**
  28600. * Defines the resources (e.g. namespaces) of scriptable nodes.
  28601. *
  28602. * @type {Resources}
  28603. */
  28604. const ScriptableNodeResources = new Resources();
  28605. /**
  28606. * This type of node allows to implement nodes with custom scripts. The script
  28607. * section is represented as an instance of `CodeNode` written with JavaScript.
  28608. * The script itself must adhere to a specific structure.
  28609. *
  28610. * - main(): Executed once by default and every time `node.needsUpdate` is set.
  28611. * - layout: The layout object defines the script's interface (inputs and outputs).
  28612. *
  28613. * ```js
  28614. * ScriptableNodeResources.set( 'TSL', TSL );
  28615. *
  28616. * const scriptableNode = scriptable( js( `
  28617. * layout = {
  28618. * outputType: 'node',
  28619. * elements: [
  28620. * { name: 'source', inputType: 'node' },
  28621. * ]
  28622. * };
  28623. *
  28624. * const { mul, oscSine } = TSL;
  28625. *
  28626. * function main() {
  28627. * const source = parameters.get( 'source' ) || float();
  28628. * return mul( source, oscSine() ) );
  28629. * }
  28630. *
  28631. * ` ) );
  28632. *
  28633. * scriptableNode.setParameter( 'source', color( 1, 0, 0 ) );
  28634. *
  28635. * const material = new THREE.MeshBasicNodeMaterial();
  28636. * material.colorNode = scriptableNode;
  28637. * ```
  28638. *
  28639. * @augments Node
  28640. */
  28641. class ScriptableNode extends Node {
  28642. static get type() {
  28643. return 'ScriptableNode';
  28644. }
  28645. /**
  28646. * Constructs a new scriptable node.
  28647. *
  28648. * @param {?CodeNode} [codeNode=null] - The code node.
  28649. * @param {Object} [parameters={}] - The parameters definition.
  28650. */
  28651. constructor( codeNode = null, parameters = {} ) {
  28652. super();
  28653. /**
  28654. * The code node.
  28655. *
  28656. * @type {?CodeNode}
  28657. * @default null
  28658. */
  28659. this.codeNode = codeNode;
  28660. /**
  28661. * The parameters definition.
  28662. *
  28663. * @type {Object}
  28664. * @default {}
  28665. */
  28666. this.parameters = parameters;
  28667. this._local = new Resources();
  28668. this._output = scriptableValue( null );
  28669. this._outputs = {};
  28670. this._source = this.source;
  28671. this._method = null;
  28672. this._object = null;
  28673. this._value = null;
  28674. this._needsOutputUpdate = true;
  28675. this.onRefresh = this.onRefresh.bind( this );
  28676. /**
  28677. * This flag can be used for type testing.
  28678. *
  28679. * @type {boolean}
  28680. * @readonly
  28681. * @default true
  28682. */
  28683. this.isScriptableNode = true;
  28684. }
  28685. /**
  28686. * The source code of the scriptable node.
  28687. *
  28688. * @type {string}
  28689. */
  28690. get source() {
  28691. return this.codeNode ? this.codeNode.code : '';
  28692. }
  28693. /**
  28694. * Sets the reference of a local script variable.
  28695. *
  28696. * @param {string} name - The variable name.
  28697. * @param {Object} value - The reference to set.
  28698. * @return {Resources} The resource map
  28699. */
  28700. setLocal( name, value ) {
  28701. return this._local.set( name, value );
  28702. }
  28703. /**
  28704. * Gets the value of a local script variable.
  28705. *
  28706. * @param {string} name - The variable name.
  28707. * @return {Object} The value.
  28708. */
  28709. getLocal( name ) {
  28710. return this._local.get( name );
  28711. }
  28712. /**
  28713. * Event listener for the `refresh` event.
  28714. */
  28715. onRefresh() {
  28716. this._refresh();
  28717. }
  28718. /**
  28719. * Returns an input from the layout with the given id/name.
  28720. *
  28721. * @param {string} id - The id/name of the input.
  28722. * @return {Object} The element entry.
  28723. */
  28724. getInputLayout( id ) {
  28725. for ( const element of this.getLayout() ) {
  28726. if ( element.inputType && ( element.id === id || element.name === id ) ) {
  28727. return element;
  28728. }
  28729. }
  28730. }
  28731. /**
  28732. * Returns an output from the layout with the given id/name.
  28733. *
  28734. * @param {string} id - The id/name of the output.
  28735. * @return {Object} The element entry.
  28736. */
  28737. getOutputLayout( id ) {
  28738. for ( const element of this.getLayout() ) {
  28739. if ( element.outputType && ( element.id === id || element.name === id ) ) {
  28740. return element;
  28741. }
  28742. }
  28743. }
  28744. /**
  28745. * Defines a script output for the given name and value.
  28746. *
  28747. * @param {string} name - The name of the output.
  28748. * @param {Node} value - The node value.
  28749. * @return {ScriptableNode} A reference to this node.
  28750. */
  28751. setOutput( name, value ) {
  28752. const outputs = this._outputs;
  28753. if ( outputs[ name ] === undefined ) {
  28754. outputs[ name ] = scriptableValue( value );
  28755. } else {
  28756. outputs[ name ].value = value;
  28757. }
  28758. return this;
  28759. }
  28760. /**
  28761. * Returns a script output for the given name.
  28762. *
  28763. * @param {string} name - The name of the output.
  28764. * @return {ScriptableValueNode} The node value.
  28765. */
  28766. getOutput( name ) {
  28767. return this._outputs[ name ];
  28768. }
  28769. /**
  28770. * Returns a parameter for the given name
  28771. *
  28772. * @param {string} name - The name of the parameter.
  28773. * @return {ScriptableValueNode} The node value.
  28774. */
  28775. getParameter( name ) {
  28776. return this.parameters[ name ];
  28777. }
  28778. /**
  28779. * Sets a value for the given parameter name.
  28780. *
  28781. * @param {string} name - The parameter name.
  28782. * @param {any} value - The parameter value.
  28783. * @return {ScriptableNode} A reference to this node.
  28784. */
  28785. setParameter( name, value ) {
  28786. const parameters = this.parameters;
  28787. if ( value && value.isScriptableNode ) {
  28788. this.deleteParameter( name );
  28789. parameters[ name ] = value;
  28790. parameters[ name ].getDefaultOutput().events.addEventListener( 'refresh', this.onRefresh );
  28791. } else if ( value && value.isScriptableValueNode ) {
  28792. this.deleteParameter( name );
  28793. parameters[ name ] = value;
  28794. parameters[ name ].events.addEventListener( 'refresh', this.onRefresh );
  28795. } else if ( parameters[ name ] === undefined ) {
  28796. parameters[ name ] = scriptableValue( value );
  28797. parameters[ name ].events.addEventListener( 'refresh', this.onRefresh );
  28798. } else {
  28799. parameters[ name ].value = value;
  28800. }
  28801. return this;
  28802. }
  28803. /**
  28804. * Returns the value of this node which is the value of
  28805. * the default output.
  28806. *
  28807. * @return {Node} The value.
  28808. */
  28809. getValue() {
  28810. return this.getDefaultOutput().getValue();
  28811. }
  28812. /**
  28813. * Deletes a parameter from the script.
  28814. *
  28815. * @param {string} name - The parameter to remove.
  28816. * @return {ScriptableNode} A reference to this node.
  28817. */
  28818. deleteParameter( name ) {
  28819. let valueNode = this.parameters[ name ];
  28820. if ( valueNode ) {
  28821. if ( valueNode.isScriptableNode ) valueNode = valueNode.getDefaultOutput();
  28822. valueNode.events.removeEventListener( 'refresh', this.onRefresh );
  28823. }
  28824. return this;
  28825. }
  28826. /**
  28827. * Deletes all parameters from the script.
  28828. *
  28829. * @return {ScriptableNode} A reference to this node.
  28830. */
  28831. clearParameters() {
  28832. for ( const name of Object.keys( this.parameters ) ) {
  28833. this.deleteParameter( name );
  28834. }
  28835. this.needsUpdate = true;
  28836. return this;
  28837. }
  28838. /**
  28839. * Calls a function from the script.
  28840. *
  28841. * @param {string} name - The function name.
  28842. * @param {...any} params - A list of parameters.
  28843. * @return {any} The result of the function call.
  28844. */
  28845. call( name, ...params ) {
  28846. const object = this.getObject();
  28847. const method = object[ name ];
  28848. if ( typeof method === 'function' ) {
  28849. return method( ...params );
  28850. }
  28851. }
  28852. /**
  28853. * Asynchronously calls a function from the script.
  28854. *
  28855. * @param {string} name - The function name.
  28856. * @param {...any} params - A list of parameters.
  28857. * @return {Promise<any>} The result of the function call.
  28858. */
  28859. async callAsync( name, ...params ) {
  28860. const object = this.getObject();
  28861. const method = object[ name ];
  28862. if ( typeof method === 'function' ) {
  28863. return method.constructor.name === 'AsyncFunction' ? await method( ...params ) : method( ...params );
  28864. }
  28865. }
  28866. /**
  28867. * Overwritten since the node types is inferred from the script's output.
  28868. *
  28869. * @param {NodeBuilder} builder - The current node builder
  28870. * @return {string} The node type.
  28871. */
  28872. getNodeType( builder ) {
  28873. return this.getDefaultOutputNode().getNodeType( builder );
  28874. }
  28875. /**
  28876. * Refreshes the script node.
  28877. *
  28878. * @param {?string} [output=null] - An optional output.
  28879. */
  28880. refresh( output = null ) {
  28881. if ( output !== null ) {
  28882. this.getOutput( output ).refresh();
  28883. } else {
  28884. this._refresh();
  28885. }
  28886. }
  28887. /**
  28888. * Returns an object representation of the script.
  28889. *
  28890. * @return {Object} The result object.
  28891. */
  28892. getObject() {
  28893. if ( this.needsUpdate ) this.dispose();
  28894. if ( this._object !== null ) return this._object;
  28895. //
  28896. const refresh = () => this.refresh();
  28897. const setOutput = ( id, value ) => this.setOutput( id, value );
  28898. const parameters = new Parameters( this );
  28899. const THREE = ScriptableNodeResources.get( 'THREE' );
  28900. const TSL = ScriptableNodeResources.get( 'TSL' );
  28901. const method = this.getMethod();
  28902. const params = [ parameters, this._local, ScriptableNodeResources, refresh, setOutput, THREE, TSL ];
  28903. this._object = method( ...params );
  28904. const layout = this._object.layout;
  28905. if ( layout ) {
  28906. if ( layout.cache === false ) {
  28907. this._local.clear();
  28908. }
  28909. // default output
  28910. this._output.outputType = layout.outputType || null;
  28911. if ( Array.isArray( layout.elements ) ) {
  28912. for ( const element of layout.elements ) {
  28913. const id = element.id || element.name;
  28914. if ( element.inputType ) {
  28915. if ( this.getParameter( id ) === undefined ) this.setParameter( id, null );
  28916. this.getParameter( id ).inputType = element.inputType;
  28917. }
  28918. if ( element.outputType ) {
  28919. if ( this.getOutput( id ) === undefined ) this.setOutput( id, null );
  28920. this.getOutput( id ).outputType = element.outputType;
  28921. }
  28922. }
  28923. }
  28924. }
  28925. return this._object;
  28926. }
  28927. deserialize( data ) {
  28928. super.deserialize( data );
  28929. for ( const name in this.parameters ) {
  28930. let valueNode = this.parameters[ name ];
  28931. if ( valueNode.isScriptableNode ) valueNode = valueNode.getDefaultOutput();
  28932. valueNode.events.addEventListener( 'refresh', this.onRefresh );
  28933. }
  28934. }
  28935. /**
  28936. * Returns the layout of the script.
  28937. *
  28938. * @return {Object} The script's layout.
  28939. */
  28940. getLayout() {
  28941. return this.getObject().layout;
  28942. }
  28943. /**
  28944. * Returns default node output of the script.
  28945. *
  28946. * @return {Node} The default node output.
  28947. */
  28948. getDefaultOutputNode() {
  28949. const output = this.getDefaultOutput().value;
  28950. if ( output && output.isNode ) {
  28951. return output;
  28952. }
  28953. return float();
  28954. }
  28955. /**
  28956. * Returns default output of the script.
  28957. *
  28958. * @return {ScriptableValueNode} The default output.
  28959. */
  28960. getDefaultOutput() {
  28961. return this._exec()._output;
  28962. }
  28963. /**
  28964. * Returns a function created from the node's script.
  28965. *
  28966. * @return {Function} The function representing the node's code.
  28967. */
  28968. getMethod() {
  28969. if ( this.needsUpdate ) this.dispose();
  28970. if ( this._method !== null ) return this._method;
  28971. //
  28972. const parametersProps = [ 'parameters', 'local', 'global', 'refresh', 'setOutput', 'THREE', 'TSL' ];
  28973. const interfaceProps = [ 'layout', 'init', 'main', 'dispose' ];
  28974. const properties = interfaceProps.join( ', ' );
  28975. const declarations = 'var ' + properties + '; var output = {};\n';
  28976. const returns = '\nreturn { ...output, ' + properties + ' };';
  28977. const code = declarations + this.codeNode.code + returns;
  28978. //
  28979. this._method = new Function( ...parametersProps, code );
  28980. return this._method;
  28981. }
  28982. /**
  28983. * Frees all internal resources.
  28984. */
  28985. dispose() {
  28986. if ( this._method === null ) return;
  28987. if ( this._object && typeof this._object.dispose === 'function' ) {
  28988. this._object.dispose();
  28989. }
  28990. this._method = null;
  28991. this._object = null;
  28992. this._source = null;
  28993. this._value = null;
  28994. this._needsOutputUpdate = true;
  28995. this._output.value = null;
  28996. this._outputs = {};
  28997. }
  28998. setup() {
  28999. return this.getDefaultOutputNode();
  29000. }
  29001. getCacheKey( force ) {
  29002. const values = [ hashString( this.source ), this.getDefaultOutputNode().getCacheKey( force ) ];
  29003. for ( const param in this.parameters ) {
  29004. values.push( this.parameters[ param ].getCacheKey( force ) );
  29005. }
  29006. return hashArray( values );
  29007. }
  29008. set needsUpdate( value ) {
  29009. if ( value === true ) this.dispose();
  29010. }
  29011. get needsUpdate() {
  29012. return this.source !== this._source;
  29013. }
  29014. /**
  29015. * Executes the `main` function of the script.
  29016. *
  29017. * @private
  29018. * @return {ScriptableNode} A reference to this node.
  29019. */
  29020. _exec() {
  29021. if ( this.codeNode === null ) return this;
  29022. if ( this._needsOutputUpdate === true ) {
  29023. this._value = this.call( 'main' );
  29024. this._needsOutputUpdate = false;
  29025. }
  29026. this._output.value = this._value;
  29027. return this;
  29028. }
  29029. /**
  29030. * Executes the refresh.
  29031. *
  29032. * @private
  29033. */
  29034. _refresh() {
  29035. this.needsUpdate = true;
  29036. this._exec();
  29037. this._output.refresh();
  29038. }
  29039. }
  29040. /**
  29041. * TSL function for creating a scriptable node.
  29042. *
  29043. * @tsl
  29044. * @function
  29045. * @param {CodeNode} [codeNode] - The code node.
  29046. * @param {?Object} [parameters={}] - The parameters definition.
  29047. * @returns {ScriptableNode}
  29048. */
  29049. const scriptable = /*@__PURE__*/ nodeProxy( ScriptableNode ).setParameterLength( 1, 2 );
  29050. /**
  29051. * Returns a node that represents the `z` coordinate in view space
  29052. * for the current fragment. It's a different representation of the
  29053. * default depth value.
  29054. *
  29055. * This value can be part of a computation that defines how the fog
  29056. * density increases when moving away from the camera.
  29057. *
  29058. * @param {NodeBuilder} builder - The current node builder.
  29059. * @return {Node} The viewZ node.
  29060. */
  29061. function getViewZNode( builder ) {
  29062. let viewZ;
  29063. const getViewZ = builder.context.getViewZ;
  29064. if ( getViewZ !== undefined ) {
  29065. viewZ = getViewZ( this );
  29066. }
  29067. return ( viewZ || positionView.z ).negate();
  29068. }
  29069. /**
  29070. * Constructs a new range factor node.
  29071. *
  29072. * @tsl
  29073. * @function
  29074. * @param {Node} near - Defines the near value.
  29075. * @param {Node} far - Defines the far value.
  29076. */
  29077. const rangeFogFactor = Fn( ( [ near, far ], builder ) => {
  29078. const viewZ = getViewZNode( builder );
  29079. return smoothstep( near, far, viewZ );
  29080. } );
  29081. /**
  29082. * Represents an exponential squared fog. This type of fog gives
  29083. * a clear view near the camera and a faster than exponentially
  29084. * densening fog farther from the camera.
  29085. *
  29086. * @tsl
  29087. * @function
  29088. * @param {Node} density - Defines the fog density.
  29089. */
  29090. const densityFogFactor = Fn( ( [ density ], builder ) => {
  29091. const viewZ = getViewZNode( builder );
  29092. return density.mul( density, viewZ, viewZ ).negate().exp().oneMinus();
  29093. } );
  29094. /**
  29095. * This class can be used to configure a fog for the scene.
  29096. * Nodes of this type are assigned to `Scene.fogNode`.
  29097. *
  29098. * @tsl
  29099. * @function
  29100. * @param {Node} color - Defines the color of the fog.
  29101. * @param {Node} factor - Defines how the fog is factored in the scene.
  29102. */
  29103. const fog = Fn( ( [ color, factor ] ) => {
  29104. return vec4( factor.toFloat().mix( output.rgb, color.toVec3() ), output.a );
  29105. } );
  29106. // Deprecated
  29107. /**
  29108. * @tsl
  29109. * @function
  29110. * @deprecated since r171. Use `fog( color, rangeFogFactor( near, far ) )` instead.
  29111. *
  29112. * @param {Node} color
  29113. * @param {Node} near
  29114. * @param {Node} far
  29115. * @returns {Function}
  29116. */
  29117. function rangeFog( color, near, far ) { // @deprecated, r171
  29118. warn( 'TSL: "rangeFog( color, near, far )" is deprecated. Use "fog( color, rangeFogFactor( near, far ) )" instead.' );
  29119. return fog( color, rangeFogFactor( near, far ) );
  29120. }
  29121. /**
  29122. * @tsl
  29123. * @function
  29124. * @deprecated since r171. Use `fog( color, densityFogFactor( density ) )` instead.
  29125. *
  29126. * @param {Node} color
  29127. * @param {Node} density
  29128. * @returns {Function}
  29129. */
  29130. function densityFog( color, density ) { // @deprecated, r171
  29131. warn( 'TSL: "densityFog( color, density )" is deprecated. Use "fog( color, densityFogFactor( density ) )" instead.' );
  29132. return fog( color, densityFogFactor( density ) );
  29133. }
  29134. let min = null;
  29135. let max = null;
  29136. /**
  29137. * `RangeNode` generates random instanced attribute data in a defined range.
  29138. * An exemplary use case for this utility node is to generate random per-instance
  29139. * colors:
  29140. * ```js
  29141. * const material = new MeshBasicNodeMaterial();
  29142. * material.colorNode = range( new Color( 0x000000 ), new Color( 0xFFFFFF ) );
  29143. * const mesh = new InstancedMesh( geometry, material, count );
  29144. * ```
  29145. * @augments Node
  29146. */
  29147. class RangeNode extends Node {
  29148. static get type() {
  29149. return 'RangeNode';
  29150. }
  29151. /**
  29152. * Constructs a new range node.
  29153. *
  29154. * @param {Node<any>} [minNode=float()] - A node defining the lower bound of the range.
  29155. * @param {Node<any>} [maxNode=float()] - A node defining the upper bound of the range.
  29156. */
  29157. constructor( minNode = float(), maxNode = float() ) {
  29158. super();
  29159. /**
  29160. * A node defining the lower bound of the range.
  29161. *
  29162. * @type {Node<any>}
  29163. * @default float()
  29164. */
  29165. this.minNode = minNode;
  29166. /**
  29167. * A node defining the upper bound of the range.
  29168. *
  29169. * @type {Node<any>}
  29170. * @default float()
  29171. */
  29172. this.maxNode = maxNode;
  29173. }
  29174. /**
  29175. * Returns the vector length which is computed based on the range definition.
  29176. *
  29177. * @param {NodeBuilder} builder - The current node builder.
  29178. * @return {number} The vector length.
  29179. */
  29180. getVectorLength( builder ) {
  29181. const minNode = this.getConstNode( this.minNode );
  29182. const maxNode = this.getConstNode( this.maxNode );
  29183. const minLength = builder.getTypeLength( getValueType( minNode.value ) );
  29184. const maxLength = builder.getTypeLength( getValueType( maxNode.value ) );
  29185. return minLength > maxLength ? minLength : maxLength;
  29186. }
  29187. /**
  29188. * This method is overwritten since the node type is inferred from range definition.
  29189. *
  29190. * @param {NodeBuilder} builder - The current node builder.
  29191. * @return {string} The node type.
  29192. */
  29193. getNodeType( builder ) {
  29194. return builder.object.count > 1 ? builder.getTypeFromLength( this.getVectorLength( builder ) ) : 'float';
  29195. }
  29196. /**
  29197. * Returns a constant node from the given node by traversing it.
  29198. *
  29199. * @param {Node} node - The node to traverse.
  29200. * @returns {Node} The constant node, if found.
  29201. */
  29202. getConstNode( node ) {
  29203. let output = null;
  29204. node.traverse( n => {
  29205. if ( n.isConstNode === true ) {
  29206. output = n;
  29207. }
  29208. } );
  29209. if ( output === null ) {
  29210. throw new Error( 'THREE.TSL: No "ConstNode" found in node graph.' );
  29211. }
  29212. return output;
  29213. }
  29214. setup( builder ) {
  29215. const object = builder.object;
  29216. let output = null;
  29217. if ( object.count > 1 ) {
  29218. const minNode = this.getConstNode( this.minNode );
  29219. const maxNode = this.getConstNode( this.maxNode );
  29220. const minValue = minNode.value;
  29221. const maxValue = maxNode.value;
  29222. const minLength = builder.getTypeLength( getValueType( minValue ) );
  29223. const maxLength = builder.getTypeLength( getValueType( maxValue ) );
  29224. min = min || new Vector4();
  29225. max = max || new Vector4();
  29226. min.setScalar( 0 );
  29227. max.setScalar( 0 );
  29228. if ( minLength === 1 ) min.setScalar( minValue );
  29229. else if ( minValue.isColor ) min.set( minValue.r, minValue.g, minValue.b, 1 );
  29230. else min.set( minValue.x, minValue.y, minValue.z || 0, minValue.w || 0 );
  29231. if ( maxLength === 1 ) max.setScalar( maxValue );
  29232. else if ( maxValue.isColor ) max.set( maxValue.r, maxValue.g, maxValue.b, 1 );
  29233. else max.set( maxValue.x, maxValue.y, maxValue.z || 0, maxValue.w || 0 );
  29234. const stride = 4;
  29235. const length = stride * object.count;
  29236. const array = new Float32Array( length );
  29237. for ( let i = 0; i < length; i ++ ) {
  29238. const index = i % stride;
  29239. const minElementValue = min.getComponent( index );
  29240. const maxElementValue = max.getComponent( index );
  29241. array[ i ] = MathUtils.lerp( minElementValue, maxElementValue, Math.random() );
  29242. }
  29243. const nodeType = this.getNodeType( builder );
  29244. if ( object.count <= 4096 ) {
  29245. output = buffer( array, 'vec4', object.count ).element( instanceIndex ).convert( nodeType );
  29246. } else {
  29247. // TODO: Improve anonymous buffer attribute creation removing this part
  29248. const bufferAttribute = new InstancedBufferAttribute( array, 4 );
  29249. builder.geometry.setAttribute( '__range' + this.id, bufferAttribute );
  29250. output = instancedBufferAttribute( bufferAttribute ).convert( nodeType );
  29251. }
  29252. } else {
  29253. output = float( 0 );
  29254. }
  29255. return output;
  29256. }
  29257. }
  29258. /**
  29259. * TSL function for creating a range node.
  29260. *
  29261. * @tsl
  29262. * @function
  29263. * @param {Node<any>} [minNode=float()] - A node defining the lower bound of the range.
  29264. * @param {Node<any>} [maxNode=float()] - A node defining the upper bound of the range.
  29265. * @returns {RangeNode}
  29266. */
  29267. const range = /*@__PURE__*/ nodeProxy( RangeNode ).setParameterLength( 2 );
  29268. /**
  29269. * `ComputeBuiltinNode` represents a compute-scope builtin value that expose information
  29270. * about the currently running dispatch and/or the device it is running on.
  29271. *
  29272. * This node can only be used with a WebGPU backend.
  29273. *
  29274. * @augments Node
  29275. */
  29276. class ComputeBuiltinNode extends Node {
  29277. static get type() {
  29278. return 'ComputeBuiltinNode';
  29279. }
  29280. /**
  29281. * Constructs a new compute builtin node.
  29282. *
  29283. * @param {string} builtinName - The built-in name.
  29284. * @param {string} nodeType - The node type.
  29285. */
  29286. constructor( builtinName, nodeType ) {
  29287. super( nodeType );
  29288. /**
  29289. * The built-in name.
  29290. *
  29291. * @private
  29292. * @type {string}
  29293. */
  29294. this._builtinName = builtinName;
  29295. }
  29296. /**
  29297. * This method is overwritten since hash is derived from the built-in name.
  29298. *
  29299. * @param {NodeBuilder} builder - The current node builder.
  29300. * @return {string} The hash.
  29301. */
  29302. getHash( builder ) {
  29303. return this.getBuiltinName( builder );
  29304. }
  29305. /**
  29306. * This method is overwritten since the node type is simply derived from `nodeType`..
  29307. *
  29308. * @param {NodeBuilder} builder - The current node builder.
  29309. * @return {string} The node type.
  29310. */
  29311. getNodeType( /*builder*/ ) {
  29312. return this.nodeType;
  29313. }
  29314. /**
  29315. * Sets the builtin name.
  29316. *
  29317. * @param {string} builtinName - The built-in name.
  29318. * @return {ComputeBuiltinNode} A reference to this node.
  29319. */
  29320. setBuiltinName( builtinName ) {
  29321. this._builtinName = builtinName;
  29322. return this;
  29323. }
  29324. /**
  29325. * Returns the builtin name.
  29326. *
  29327. * @param {NodeBuilder} builder - The current node builder.
  29328. * @return {string} The builtin name.
  29329. */
  29330. getBuiltinName( /*builder*/ ) {
  29331. return this._builtinName;
  29332. }
  29333. /**
  29334. * Whether the current node builder has the builtin or not.
  29335. *
  29336. * @param {NodeBuilder} builder - The current node builder.
  29337. * @return {boolean} Whether the builder has the builtin or not.
  29338. */
  29339. hasBuiltin( builder ) {
  29340. return builder.hasBuiltin( this._builtinName );
  29341. }
  29342. generate( builder, output ) {
  29343. const builtinName = this.getBuiltinName( builder );
  29344. const nodeType = this.getNodeType( builder );
  29345. if ( builder.shaderStage === 'compute' ) {
  29346. return builder.format( builtinName, nodeType, output );
  29347. } else {
  29348. warn( `ComputeBuiltinNode: Compute built-in value ${builtinName} can not be accessed in the ${builder.shaderStage} stage` );
  29349. return builder.generateConst( nodeType );
  29350. }
  29351. }
  29352. serialize( data ) {
  29353. super.serialize( data );
  29354. data.global = this.global;
  29355. data._builtinName = this._builtinName;
  29356. }
  29357. deserialize( data ) {
  29358. super.deserialize( data );
  29359. this.global = data.global;
  29360. this._builtinName = data._builtinName;
  29361. }
  29362. }
  29363. /**
  29364. * TSL function for creating a compute builtin node.
  29365. *
  29366. * @tsl
  29367. * @function
  29368. * @param {string} name - The built-in name.
  29369. * @param {string} nodeType - The node type.
  29370. * @returns {ComputeBuiltinNode}
  29371. */
  29372. const computeBuiltin = ( name, nodeType ) => nodeObject( new ComputeBuiltinNode( name, nodeType ) );
  29373. /**
  29374. * Represents the number of workgroups dispatched by the compute shader.
  29375. * ```js
  29376. * // Run 512 invocations/threads with a workgroup size of 128.
  29377. * const computeFn = Fn(() => {
  29378. *
  29379. * // numWorkgroups.x = 4
  29380. * storageBuffer.element(0).assign(numWorkgroups.x)
  29381. *
  29382. * })().compute(512, [128]);
  29383. *
  29384. * // Run 512 invocations/threads with the default workgroup size of 64.
  29385. * const computeFn = Fn(() => {
  29386. *
  29387. * // numWorkgroups.x = 8
  29388. * storageBuffer.element(0).assign(numWorkgroups.x)
  29389. *
  29390. * })().compute(512);
  29391. * ```
  29392. *
  29393. * @tsl
  29394. * @type {ComputeBuiltinNode<uvec3>}
  29395. */
  29396. const numWorkgroups = /*@__PURE__*/ computeBuiltin( 'numWorkgroups', 'uvec3' );
  29397. /**
  29398. * Represents the 3-dimensional index of the workgroup the current compute invocation belongs to.
  29399. * ```js
  29400. * // Execute 12 compute threads with a workgroup size of 3.
  29401. * const computeFn = Fn( () => {
  29402. *
  29403. * If( workgroupId.x.mod( 2 ).equal( 0 ), () => {
  29404. *
  29405. * storageBuffer.element( instanceIndex ).assign( instanceIndex );
  29406. *
  29407. * } ).Else( () => {
  29408. *
  29409. * storageBuffer.element( instanceIndex ).assign( 0 );
  29410. *
  29411. * } );
  29412. *
  29413. * } )().compute( 12, [ 3 ] );
  29414. *
  29415. * // workgroupId.x = [0, 0, 0, 1, 1, 1, 2, 2, 2, 3, 3, 3];
  29416. * // Buffer Output = [0, 1, 2, 0, 0, 0, 6, 7, 8, 0, 0, 0];
  29417. * ```
  29418. *
  29419. * @tsl
  29420. * @type {ComputeBuiltinNode<uvec3>}
  29421. */
  29422. const workgroupId = /*@__PURE__*/ computeBuiltin( 'workgroupId', 'uvec3' );
  29423. /**
  29424. * A non-linearized 3-dimensional representation of the current invocation's position within a 3D global grid.
  29425. *
  29426. * @tsl
  29427. * @type {ComputeBuiltinNode<uvec3>}
  29428. */
  29429. const globalId = /*@__PURE__*/ computeBuiltin( 'globalId', 'uvec3' );
  29430. /**
  29431. * A non-linearized 3-dimensional representation of the current invocation's position within a 3D workgroup grid.
  29432. *
  29433. * @tsl
  29434. * @type {ComputeBuiltinNode<uvec3>}
  29435. */
  29436. const localId = /*@__PURE__*/ computeBuiltin( 'localId', 'uvec3' );
  29437. /**
  29438. * A device dependent variable that exposes the size of the current invocation's subgroup.
  29439. *
  29440. * @tsl
  29441. * @type {ComputeBuiltinNode<uint>}
  29442. */
  29443. const subgroupSize = /*@__PURE__*/ computeBuiltin( 'subgroupSize', 'uint' );
  29444. /**
  29445. * Represents a GPU control barrier that synchronizes compute operations within a given scope.
  29446. *
  29447. * This node can only be used with a WebGPU backend.
  29448. *
  29449. * @augments Node
  29450. */
  29451. class BarrierNode extends Node {
  29452. /**
  29453. * Constructs a new barrier node.
  29454. *
  29455. * @param {string} scope - The scope defines the behavior of the node.
  29456. */
  29457. constructor( scope ) {
  29458. super();
  29459. this.scope = scope;
  29460. }
  29461. generate( builder ) {
  29462. const { scope } = this;
  29463. const { renderer } = builder;
  29464. if ( renderer.backend.isWebGLBackend === true ) {
  29465. builder.addFlowCode( `\t// ${scope}Barrier \n` );
  29466. } else {
  29467. builder.addLineFlowCode( `${scope}Barrier()`, this );
  29468. }
  29469. }
  29470. }
  29471. /**
  29472. * TSL function for creating a barrier node.
  29473. *
  29474. * @tsl
  29475. * @function
  29476. * @param {string} scope - The scope defines the behavior of the node..
  29477. * @returns {BarrierNode}
  29478. */
  29479. const barrier = nodeProxy( BarrierNode );
  29480. /**
  29481. * TSL function for creating a workgroup barrier. All compute shader
  29482. * invocations must wait for each invocation within a workgroup to
  29483. * complete before the barrier can be surpassed.
  29484. *
  29485. * @tsl
  29486. * @function
  29487. * @returns {BarrierNode}
  29488. */
  29489. const workgroupBarrier = () => barrier( 'workgroup' ).toStack();
  29490. /**
  29491. * TSL function for creating a storage barrier. All invocations must
  29492. * wait for each access to variables within the 'storage' address space
  29493. * to complete before the barrier can be passed.
  29494. *
  29495. * @tsl
  29496. * @function
  29497. * @returns {BarrierNode}
  29498. */
  29499. const storageBarrier = () => barrier( 'storage' ).toStack();
  29500. /**
  29501. * TSL function for creating a texture barrier. All invocations must
  29502. * wait for each access to variables within the 'texture' address space
  29503. * to complete before the barrier can be passed.
  29504. *
  29505. * @tsl
  29506. * @function
  29507. * @returns {BarrierNode}
  29508. */
  29509. const textureBarrier = () => barrier( 'texture' ).toStack();
  29510. /**
  29511. * Represents an element of a 'workgroup' scoped buffer.
  29512. *
  29513. * @augments ArrayElementNode
  29514. */
  29515. class WorkgroupInfoElementNode extends ArrayElementNode {
  29516. /**
  29517. * Constructs a new workgroup info element node.
  29518. *
  29519. * @param {Node} workgroupInfoNode - The workgroup info node.
  29520. * @param {Node} indexNode - The index node that defines the element access.
  29521. */
  29522. constructor( workgroupInfoNode, indexNode ) {
  29523. super( workgroupInfoNode, indexNode );
  29524. /**
  29525. * This flag can be used for type testing.
  29526. *
  29527. * @type {boolean}
  29528. * @readonly
  29529. * @default true
  29530. */
  29531. this.isWorkgroupInfoElementNode = true;
  29532. }
  29533. generate( builder, output ) {
  29534. let snippet;
  29535. const isAssignContext = builder.context.assign;
  29536. snippet = super.generate( builder );
  29537. if ( isAssignContext !== true ) {
  29538. const type = this.getNodeType( builder );
  29539. snippet = builder.format( snippet, type, output );
  29540. }
  29541. // TODO: Possibly activate clip distance index on index access rather than from clipping context
  29542. return snippet;
  29543. }
  29544. }
  29545. /**
  29546. * A node allowing the user to create a 'workgroup' scoped buffer within the
  29547. * context of a compute shader. Typically, workgroup scoped buffers are
  29548. * created to hold data that is transferred from a global storage scope into
  29549. * a local workgroup scope. For invocations within a workgroup, data
  29550. * access speeds on 'workgroup' scoped buffers can be significantly faster
  29551. * than similar access operations on globally accessible storage buffers.
  29552. *
  29553. * This node can only be used with a WebGPU backend.
  29554. *
  29555. * @augments Node
  29556. */
  29557. class WorkgroupInfoNode extends Node {
  29558. /**
  29559. * Constructs a new buffer scoped to type scope.
  29560. *
  29561. * @param {string} scope - TODO.
  29562. * @param {string} bufferType - The data type of a 'workgroup' scoped buffer element.
  29563. * @param {number} [bufferCount=0] - The number of elements in the buffer.
  29564. */
  29565. constructor( scope, bufferType, bufferCount = 0 ) {
  29566. super( bufferType );
  29567. /**
  29568. * The buffer type.
  29569. *
  29570. * @type {string}
  29571. */
  29572. this.bufferType = bufferType;
  29573. /**
  29574. * The buffer count.
  29575. *
  29576. * @type {number}
  29577. * @default 0
  29578. */
  29579. this.bufferCount = bufferCount;
  29580. /**
  29581. * This flag can be used for type testing.
  29582. *
  29583. * @type {boolean}
  29584. * @readonly
  29585. * @default true
  29586. */
  29587. this.isWorkgroupInfoNode = true;
  29588. /**
  29589. * The data type of the array buffer.
  29590. *
  29591. * @type {string}
  29592. */
  29593. this.elementType = bufferType;
  29594. /**
  29595. * TODO.
  29596. *
  29597. * @type {string}
  29598. */
  29599. this.scope = scope;
  29600. /**
  29601. * The name of the workgroup scoped buffer.
  29602. *
  29603. * @type {string}
  29604. * @default ''
  29605. */
  29606. this.name = '';
  29607. }
  29608. /**
  29609. * Sets the name of this node.
  29610. *
  29611. * @param {string} name - The name to set.
  29612. * @return {WorkgroupInfoNode} A reference to this node.
  29613. */
  29614. setName( name ) {
  29615. this.name = name;
  29616. return this;
  29617. }
  29618. /**
  29619. * Sets the name/label of this node.
  29620. *
  29621. * @deprecated
  29622. * @param {string} name - The name to set.
  29623. * @return {WorkgroupInfoNode} A reference to this node.
  29624. */
  29625. label( name ) {
  29626. warn( 'TSL: "label()" has been deprecated. Use "setName()" instead.' ); // @deprecated r179
  29627. return this.setName( name );
  29628. }
  29629. /**
  29630. * Sets the scope of this node.
  29631. *
  29632. * @param {string} scope - The scope to set.
  29633. * @return {WorkgroupInfoNode} A reference to this node.
  29634. */
  29635. setScope( scope ) {
  29636. this.scope = scope;
  29637. return this;
  29638. }
  29639. /**
  29640. * The data type of the array buffer.
  29641. *
  29642. * @return {string} The element type.
  29643. */
  29644. getElementType() {
  29645. return this.elementType;
  29646. }
  29647. /**
  29648. * Overwrites the default implementation since the input type
  29649. * is inferred from the scope.
  29650. *
  29651. * @param {NodeBuilder} builder - The current node builder.
  29652. * @return {string} The input type.
  29653. */
  29654. getInputType( /*builder*/ ) {
  29655. return `${this.scope}Array`;
  29656. }
  29657. /**
  29658. * This method can be used to access elements via an index node.
  29659. *
  29660. * @param {IndexNode} indexNode - indexNode.
  29661. * @return {WorkgroupInfoElementNode} A reference to an element.
  29662. */
  29663. element( indexNode ) {
  29664. return nodeObject( new WorkgroupInfoElementNode( this, indexNode ) );
  29665. }
  29666. generate( builder ) {
  29667. const name = ( this.name !== '' ) ? this.name : `${this.scope}Array_${this.id}`;
  29668. return builder.getScopedArray( name, this.scope.toLowerCase(), this.bufferType, this.bufferCount );
  29669. }
  29670. }
  29671. /**
  29672. * TSL function for creating a workgroup info node.
  29673. * Creates a new 'workgroup' scoped array buffer.
  29674. *
  29675. * @tsl
  29676. * @function
  29677. * @param {string} type - The data type of a 'workgroup' scoped buffer element.
  29678. * @param {number} [count=0] - The number of elements in the buffer.
  29679. * @returns {WorkgroupInfoNode}
  29680. */
  29681. const workgroupArray = ( type, count ) => nodeObject( new WorkgroupInfoNode( 'Workgroup', type, count ) );
  29682. /**
  29683. * `AtomicFunctionNode` represents any function that can operate on atomic variable types
  29684. * within a shader. In an atomic function, any modification to an atomic variable will
  29685. * occur as an indivisible step with a defined order relative to other modifications.
  29686. * Accordingly, even if multiple atomic functions are modifying an atomic variable at once
  29687. * atomic operations will not interfere with each other.
  29688. *
  29689. * This node can only be used with a WebGPU backend.
  29690. *
  29691. * @augments Node
  29692. */
  29693. class AtomicFunctionNode extends Node {
  29694. static get type() {
  29695. return 'AtomicFunctionNode';
  29696. }
  29697. /**
  29698. * Constructs a new atomic function node.
  29699. *
  29700. * @param {string} method - The signature of the atomic function to construct.
  29701. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  29702. * @param {Node} valueNode - The value that mutates the atomic variable.
  29703. */
  29704. constructor( method, pointerNode, valueNode ) {
  29705. super( 'uint' );
  29706. /**
  29707. * The signature of the atomic function to construct.
  29708. *
  29709. * @type {string}
  29710. */
  29711. this.method = method;
  29712. /**
  29713. * An atomic variable or element of an atomic buffer.
  29714. *
  29715. * @type {Node}
  29716. */
  29717. this.pointerNode = pointerNode;
  29718. /**
  29719. * A value that modifies the atomic variable.
  29720. *
  29721. * @type {Node}
  29722. */
  29723. this.valueNode = valueNode;
  29724. /**
  29725. * Creates a list of the parents for this node for detecting if the node needs to return a value.
  29726. *
  29727. * @type {boolean}
  29728. * @default true
  29729. */
  29730. this.parents = true;
  29731. }
  29732. /**
  29733. * Overwrites the default implementation to return the type of
  29734. * the pointer node.
  29735. *
  29736. * @param {NodeBuilder} builder - The current node builder.
  29737. * @return {string} The input type.
  29738. */
  29739. getInputType( builder ) {
  29740. return this.pointerNode.getNodeType( builder );
  29741. }
  29742. /**
  29743. * Overwritten since the node type is inferred from the input type.
  29744. *
  29745. * @param {NodeBuilder} builder - The current node builder.
  29746. * @return {string} The node type.
  29747. */
  29748. getNodeType( builder ) {
  29749. return this.getInputType( builder );
  29750. }
  29751. generate( builder ) {
  29752. const properties = builder.getNodeProperties( this );
  29753. const parents = properties.parents;
  29754. const method = this.method;
  29755. const type = this.getNodeType( builder );
  29756. const inputType = this.getInputType( builder );
  29757. const a = this.pointerNode;
  29758. const b = this.valueNode;
  29759. const params = [];
  29760. params.push( `&${ a.build( builder, inputType ) }` );
  29761. if ( b !== null ) {
  29762. params.push( b.build( builder, inputType ) );
  29763. }
  29764. const methodSnippet = `${ builder.getMethod( method, type ) }( ${ params.join( ', ' ) } )`;
  29765. const isVoid = parents ? ( parents.length === 1 && parents[ 0 ].isStackNode === true ) : false;
  29766. if ( isVoid ) {
  29767. builder.addLineFlowCode( methodSnippet, this );
  29768. } else {
  29769. if ( properties.constNode === undefined ) {
  29770. properties.constNode = expression( methodSnippet, type ).toConst();
  29771. }
  29772. return properties.constNode.build( builder );
  29773. }
  29774. }
  29775. }
  29776. AtomicFunctionNode.ATOMIC_LOAD = 'atomicLoad';
  29777. AtomicFunctionNode.ATOMIC_STORE = 'atomicStore';
  29778. AtomicFunctionNode.ATOMIC_ADD = 'atomicAdd';
  29779. AtomicFunctionNode.ATOMIC_SUB = 'atomicSub';
  29780. AtomicFunctionNode.ATOMIC_MAX = 'atomicMax';
  29781. AtomicFunctionNode.ATOMIC_MIN = 'atomicMin';
  29782. AtomicFunctionNode.ATOMIC_AND = 'atomicAnd';
  29783. AtomicFunctionNode.ATOMIC_OR = 'atomicOr';
  29784. AtomicFunctionNode.ATOMIC_XOR = 'atomicXor';
  29785. /**
  29786. * TSL function for creating an atomic function node.
  29787. *
  29788. * @tsl
  29789. * @function
  29790. * @param {string} method - The signature of the atomic function to construct.
  29791. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  29792. * @param {Node} valueNode - The value that mutates the atomic variable.
  29793. * @returns {AtomicFunctionNode}
  29794. */
  29795. const atomicNode = nodeProxy( AtomicFunctionNode );
  29796. /**
  29797. * TSL function for appending an atomic function call into the programmatic flow of a compute shader.
  29798. *
  29799. * @tsl
  29800. * @function
  29801. * @param {string} method - The signature of the atomic function to construct.
  29802. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  29803. * @param {Node} valueNode - The value that mutates the atomic variable.
  29804. * @returns {AtomicFunctionNode}
  29805. */
  29806. const atomicFunc = ( method, pointerNode, valueNode ) => {
  29807. return atomicNode( method, pointerNode, valueNode ).toStack();
  29808. };
  29809. /**
  29810. * Loads the value stored in the atomic variable.
  29811. *
  29812. * @tsl
  29813. * @function
  29814. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  29815. * @returns {AtomicFunctionNode}
  29816. */
  29817. const atomicLoad = ( pointerNode ) => atomicFunc( AtomicFunctionNode.ATOMIC_LOAD, pointerNode, null );
  29818. /**
  29819. * Stores a value in the atomic variable.
  29820. *
  29821. * @tsl
  29822. * @function
  29823. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  29824. * @param {Node} valueNode - The value that mutates the atomic variable.
  29825. * @returns {AtomicFunctionNode}
  29826. */
  29827. const atomicStore = ( pointerNode, valueNode ) => atomicFunc( AtomicFunctionNode.ATOMIC_STORE, pointerNode, valueNode );
  29828. /**
  29829. * Increments the value stored in the atomic variable.
  29830. *
  29831. * @tsl
  29832. * @function
  29833. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  29834. * @param {Node} valueNode - The value that mutates the atomic variable.
  29835. * @returns {AtomicFunctionNode}
  29836. */
  29837. const atomicAdd = ( pointerNode, valueNode ) => atomicFunc( AtomicFunctionNode.ATOMIC_ADD, pointerNode, valueNode );
  29838. /**
  29839. * Decrements the value stored in the atomic variable.
  29840. *
  29841. * @tsl
  29842. * @function
  29843. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  29844. * @param {Node} valueNode - The value that mutates the atomic variable.
  29845. * @returns {AtomicFunctionNode}
  29846. */
  29847. const atomicSub = ( pointerNode, valueNode ) => atomicFunc( AtomicFunctionNode.ATOMIC_SUB, pointerNode, valueNode );
  29848. /**
  29849. * Stores in an atomic variable the maximum between its current value and a parameter.
  29850. *
  29851. * @tsl
  29852. * @function
  29853. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  29854. * @param {Node} valueNode - The value that mutates the atomic variable.
  29855. * @returns {AtomicFunctionNode}
  29856. */
  29857. const atomicMax = ( pointerNode, valueNode ) => atomicFunc( AtomicFunctionNode.ATOMIC_MAX, pointerNode, valueNode );
  29858. /**
  29859. * Stores in an atomic variable the minimum between its current value and a parameter.
  29860. *
  29861. * @tsl
  29862. * @function
  29863. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  29864. * @param {Node} valueNode - The value that mutates the atomic variable.
  29865. * @returns {AtomicFunctionNode}
  29866. */
  29867. const atomicMin = ( pointerNode, valueNode ) => atomicFunc( AtomicFunctionNode.ATOMIC_MIN, pointerNode, valueNode );
  29868. /**
  29869. * Stores in an atomic variable the bitwise AND of its value with a parameter.
  29870. *
  29871. * @tsl
  29872. * @function
  29873. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  29874. * @param {Node} valueNode - The value that mutates the atomic variable.
  29875. * @returns {AtomicFunctionNode}
  29876. */
  29877. const atomicAnd = ( pointerNode, valueNode ) => atomicFunc( AtomicFunctionNode.ATOMIC_AND, pointerNode, valueNode );
  29878. /**
  29879. * Stores in an atomic variable the bitwise OR of its value with a parameter.
  29880. *
  29881. * @tsl
  29882. * @function
  29883. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  29884. * @param {Node} valueNode - The value that mutates the atomic variable.
  29885. * @returns {AtomicFunctionNode}
  29886. */
  29887. const atomicOr = ( pointerNode, valueNode ) => atomicFunc( AtomicFunctionNode.ATOMIC_OR, pointerNode, valueNode );
  29888. /**
  29889. * Stores in an atomic variable the bitwise XOR of its value with a parameter.
  29890. *
  29891. * @tsl
  29892. * @function
  29893. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  29894. * @param {Node} valueNode - The value that mutates the atomic variable.
  29895. * @returns {AtomicFunctionNode}
  29896. */
  29897. const atomicXor = ( pointerNode, valueNode ) => atomicFunc( AtomicFunctionNode.ATOMIC_XOR, pointerNode, valueNode );
  29898. /**
  29899. * This class represents a set of built in WGSL shader functions that sync
  29900. * synchronously execute an operation across a subgroup, or 'warp', of compute
  29901. * or fragment shader invocations within a workgroup. Typically, these functions
  29902. * will synchronously execute an operation using data from all active invocations
  29903. * within the subgroup, then broadcast that result to all active invocations. In
  29904. * other graphics APIs, subgroup functions are also referred to as wave intrinsics
  29905. * (DirectX/HLSL) or warp intrinsics (CUDA).
  29906. *
  29907. * @augments TempNode
  29908. */
  29909. class SubgroupFunctionNode extends TempNode {
  29910. static get type() {
  29911. return 'SubgroupFunctionNode';
  29912. }
  29913. /**
  29914. * Constructs a new function node.
  29915. *
  29916. * @param {string} method - The subgroup/wave intrinsic method to construct.
  29917. * @param {Node} [aNode=null] - The method's first argument.
  29918. * @param {Node} [bNode=null] - The method's second argument.
  29919. */
  29920. constructor( method, aNode = null, bNode = null ) {
  29921. super();
  29922. /**
  29923. * The subgroup/wave intrinsic method to construct.
  29924. *
  29925. * @type {String}
  29926. */
  29927. this.method = method;
  29928. /**
  29929. * The method's first argument.
  29930. *
  29931. * @type {Node}
  29932. */
  29933. this.aNode = aNode;
  29934. /**
  29935. * The method's second argument.
  29936. *
  29937. * @type {Node}
  29938. */
  29939. this.bNode = bNode;
  29940. }
  29941. getInputType( builder ) {
  29942. const aType = this.aNode ? this.aNode.getNodeType( builder ) : null;
  29943. const bType = this.bNode ? this.bNode.getNodeType( builder ) : null;
  29944. const aLen = builder.isMatrix( aType ) ? 0 : builder.getTypeLength( aType );
  29945. const bLen = builder.isMatrix( bType ) ? 0 : builder.getTypeLength( bType );
  29946. if ( aLen > bLen ) {
  29947. return aType;
  29948. } else {
  29949. return bType;
  29950. }
  29951. }
  29952. getNodeType( builder ) {
  29953. const method = this.method;
  29954. if ( method === SubgroupFunctionNode.SUBGROUP_ELECT ) {
  29955. return 'bool';
  29956. } else if ( method === SubgroupFunctionNode.SUBGROUP_BALLOT ) {
  29957. return 'uvec4';
  29958. } else {
  29959. return this.getInputType( builder );
  29960. }
  29961. }
  29962. generate( builder, output ) {
  29963. const method = this.method;
  29964. const type = this.getNodeType( builder );
  29965. const inputType = this.getInputType( builder );
  29966. const a = this.aNode;
  29967. const b = this.bNode;
  29968. const params = [];
  29969. if (
  29970. method === SubgroupFunctionNode.SUBGROUP_BROADCAST ||
  29971. method === SubgroupFunctionNode.SUBGROUP_SHUFFLE ||
  29972. method === SubgroupFunctionNode.QUAD_BROADCAST
  29973. ) {
  29974. const bType = b.getNodeType( builder );
  29975. params.push(
  29976. a.build( builder, type ),
  29977. b.build( builder, bType === 'float' ? 'int' : type )
  29978. );
  29979. } else if (
  29980. method === SubgroupFunctionNode.SUBGROUP_SHUFFLE_XOR ||
  29981. method === SubgroupFunctionNode.SUBGROUP_SHUFFLE_DOWN ||
  29982. method === SubgroupFunctionNode.SUBGROUP_SHUFFLE_UP
  29983. ) {
  29984. params.push(
  29985. a.build( builder, type ),
  29986. b.build( builder, 'uint' )
  29987. );
  29988. } else {
  29989. if ( a !== null ) params.push( a.build( builder, inputType ) );
  29990. if ( b !== null ) params.push( b.build( builder, inputType ) );
  29991. }
  29992. const paramsString = params.length === 0 ? '()' : `( ${params.join( ', ' )} )`;
  29993. return builder.format( `${ builder.getMethod( method, type ) }${paramsString}`, type, output );
  29994. }
  29995. serialize( data ) {
  29996. super.serialize( data );
  29997. data.method = this.method;
  29998. }
  29999. deserialize( data ) {
  30000. super.deserialize( data );
  30001. this.method = data.method;
  30002. }
  30003. }
  30004. // 0 inputs
  30005. SubgroupFunctionNode.SUBGROUP_ELECT = 'subgroupElect';
  30006. // 1 input
  30007. SubgroupFunctionNode.SUBGROUP_BALLOT = 'subgroupBallot';
  30008. SubgroupFunctionNode.SUBGROUP_ADD = 'subgroupAdd';
  30009. SubgroupFunctionNode.SUBGROUP_INCLUSIVE_ADD = 'subgroupInclusiveAdd';
  30010. SubgroupFunctionNode.SUBGROUP_EXCLUSIVE_AND = 'subgroupExclusiveAdd';
  30011. SubgroupFunctionNode.SUBGROUP_MUL = 'subgroupMul';
  30012. SubgroupFunctionNode.SUBGROUP_INCLUSIVE_MUL = 'subgroupInclusiveMul';
  30013. SubgroupFunctionNode.SUBGROUP_EXCLUSIVE_MUL = 'subgroupExclusiveMul';
  30014. SubgroupFunctionNode.SUBGROUP_AND = 'subgroupAnd';
  30015. SubgroupFunctionNode.SUBGROUP_OR = 'subgroupOr';
  30016. SubgroupFunctionNode.SUBGROUP_XOR = 'subgroupXor';
  30017. SubgroupFunctionNode.SUBGROUP_MIN = 'subgroupMin';
  30018. SubgroupFunctionNode.SUBGROUP_MAX = 'subgroupMax';
  30019. SubgroupFunctionNode.SUBGROUP_ALL = 'subgroupAll';
  30020. SubgroupFunctionNode.SUBGROUP_ANY = 'subgroupAny';
  30021. SubgroupFunctionNode.SUBGROUP_BROADCAST_FIRST = 'subgroupBroadcastFirst';
  30022. SubgroupFunctionNode.QUAD_SWAP_X = 'quadSwapX';
  30023. SubgroupFunctionNode.QUAD_SWAP_Y = 'quadSwapY';
  30024. SubgroupFunctionNode.QUAD_SWAP_DIAGONAL = 'quadSwapDiagonal';
  30025. // 2 inputs
  30026. SubgroupFunctionNode.SUBGROUP_BROADCAST = 'subgroupBroadcast';
  30027. SubgroupFunctionNode.SUBGROUP_SHUFFLE = 'subgroupShuffle';
  30028. SubgroupFunctionNode.SUBGROUP_SHUFFLE_XOR = 'subgroupShuffleXor';
  30029. SubgroupFunctionNode.SUBGROUP_SHUFFLE_UP = 'subgroupShuffleUp';
  30030. SubgroupFunctionNode.SUBGROUP_SHUFFLE_DOWN = 'subgroupShuffleDown';
  30031. SubgroupFunctionNode.QUAD_BROADCAST = 'quadBroadcast';
  30032. /**
  30033. * Returns true if this invocation has the lowest subgroup_invocation_id
  30034. * among active invocations in the subgroup.
  30035. *
  30036. * @tsl
  30037. * @method
  30038. * @return {bool} The result of the computation.
  30039. */
  30040. const subgroupElect = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_ELECT ).setParameterLength( 0 );
  30041. /**
  30042. * Returns a set of bitfields where the bit corresponding to subgroup_invocation_id
  30043. * is 1 if pred is true for that active invocation and 0 otherwise.
  30044. *
  30045. * @tsl
  30046. * @method
  30047. * @param {bool} pred - A boolean that sets the bit corresponding to the invocations subgroup invocation id.
  30048. * @return {vec4<u32>}- A bitfield corresponding to the pred value of each subgroup invocation.
  30049. */
  30050. const subgroupBallot = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_BALLOT ).setParameterLength( 1 );
  30051. /**
  30052. * A reduction that adds e among all active invocations and returns that result.
  30053. *
  30054. * @tsl
  30055. * @method
  30056. * @param {number} e - The value provided to the reduction by the current invocation.
  30057. * @return {number} The accumulated result of the reduction operation.
  30058. */
  30059. const subgroupAdd = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_ADD ).setParameterLength( 1 );
  30060. /**
  30061. * An inclusive scan returning the sum of e for all active invocations with subgroup_invocation_id less than or equal to this invocation.
  30062. *
  30063. * @tsl
  30064. * @method
  30065. * @param {number} e - The value provided to the inclusive scan by the current invocation.
  30066. * @return {number} The accumulated result of the inclusive scan operation.
  30067. */
  30068. const subgroupInclusiveAdd = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_INCLUSIVE_ADD ).setParameterLength( 1 );
  30069. /**
  30070. * An exclusive scan that returns the sum of e for all active invocations with subgroup_invocation_id less than this invocation.
  30071. *
  30072. * @tsl
  30073. * @method
  30074. * @param {number} e - The value provided to the exclusive scan by the current invocation.
  30075. * @return {number} The accumulated result of the exclusive scan operation.
  30076. */
  30077. const subgroupExclusiveAdd = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_EXCLUSIVE_AND ).setParameterLength( 1 );
  30078. /**
  30079. * A reduction that multiplies e among all active invocations and returns that result.
  30080. *
  30081. * @tsl
  30082. * @method
  30083. * @param {number} e - The value provided to the reduction by the current invocation.
  30084. * @return {number} The accumulated result of the reduction operation.
  30085. */
  30086. const subgroupMul = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_MUL ).setParameterLength( 1 );
  30087. /**
  30088. * An inclusive scan returning the product of e for all active invocations with subgroup_invocation_id less than or equal to this invocation.
  30089. *
  30090. * @tsl
  30091. * @method
  30092. * @param {number} e - The value provided to the inclusive scan by the current invocation.
  30093. * @return {number} The accumulated result of the inclusive scan operation.
  30094. */
  30095. const subgroupInclusiveMul = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_INCLUSIVE_MUL ).setParameterLength( 1 );
  30096. /**
  30097. * An exclusive scan that returns the product of e for all active invocations with subgroup_invocation_id less than this invocation.
  30098. *
  30099. * @tsl
  30100. * @method
  30101. * @param {number} e - The value provided to the exclusive scan by the current invocation.
  30102. * @return {number} The accumulated result of the exclusive scan operation.
  30103. */
  30104. const subgroupExclusiveMul = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_EXCLUSIVE_MUL ).setParameterLength( 1 );
  30105. /**
  30106. * A reduction that performs a bitwise and of e among all active invocations and returns that result.
  30107. *
  30108. * @tsl
  30109. * @method
  30110. * @param {number} e - The value provided to the reduction by the current invocation.
  30111. * @return {number} The result of the reduction operation.
  30112. */
  30113. const subgroupAnd = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_AND ).setParameterLength( 1 );
  30114. /**
  30115. * A reduction that performs a bitwise or of e among all active invocations and returns that result.
  30116. *
  30117. * @tsl
  30118. * @method
  30119. * @param {number} e - The value provided to the reduction by the current invocation.
  30120. * @return {number} The result of the reduction operation.
  30121. */
  30122. const subgroupOr = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_OR ).setParameterLength( 1 );
  30123. /**
  30124. * A reduction that performs a bitwise xor of e among all active invocations and returns that result.
  30125. *
  30126. * @tsl
  30127. * @method
  30128. * @param {number} e - The value provided to the reduction by the current invocation.
  30129. * @return {number} The result of the reduction operation.
  30130. */
  30131. const subgroupXor = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_XOR ).setParameterLength( 1 );
  30132. /**
  30133. * A reduction that performs a min of e among all active invocations and returns that result.
  30134. *
  30135. * @tsl
  30136. * @method
  30137. * @param {number} e - The value provided to the reduction by the current invocation.
  30138. * @return {number} The result of the reduction operation.
  30139. */
  30140. const subgroupMin = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_MIN ).setParameterLength( 1 );
  30141. /**
  30142. * A reduction that performs a max of e among all active invocations and returns that result.
  30143. *
  30144. * @tsl
  30145. * @method
  30146. * @param {number} e - The value provided to the reduction by the current invocation.
  30147. * @return {number} The result of the reduction operation.
  30148. */
  30149. const subgroupMax = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_MAX ).setParameterLength( 1 );
  30150. /**
  30151. * Returns true if e is true for all active invocations in the subgroup.
  30152. *
  30153. * @tsl
  30154. * @method
  30155. * @return {bool} The result of the computation.
  30156. */
  30157. const subgroupAll = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_ALL ).setParameterLength( 0 );
  30158. /**
  30159. * Returns true if e is true for any active invocation in the subgroup
  30160. *
  30161. * @tsl
  30162. * @method
  30163. * @return {bool} The result of the computation.
  30164. */
  30165. const subgroupAny = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_ANY ).setParameterLength( 0 );
  30166. /**
  30167. * Broadcasts e from the active invocation with the lowest subgroup_invocation_id in the subgroup to all other active invocations.
  30168. *
  30169. * @tsl
  30170. * @method
  30171. * @param {number} e - The value to broadcast from the lowest subgroup invocation.
  30172. * @param {number} id - The subgroup invocation to broadcast from.
  30173. * @return {number} The broadcast value.
  30174. */
  30175. const subgroupBroadcastFirst = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_BROADCAST_FIRST ).setParameterLength( 2 );
  30176. /**
  30177. * Swaps e between invocations in the quad in the X direction.
  30178. *
  30179. * @tsl
  30180. * @method
  30181. * @param {number} e - The value to swap from the current invocation.
  30182. * @return {number} The value received from the swap operation.
  30183. */
  30184. const quadSwapX = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.QUAD_SWAP_X ).setParameterLength( 1 );
  30185. /**
  30186. * Swaps e between invocations in the quad in the Y direction.
  30187. *
  30188. * @tsl
  30189. * @method
  30190. * @param {number} e - The value to swap from the current invocation.
  30191. * @return {number} The value received from the swap operation.
  30192. */
  30193. const quadSwapY = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.QUAD_SWAP_Y ).setParameterLength( 1 );
  30194. /**
  30195. * Swaps e between invocations in the quad diagonally.
  30196. *
  30197. * @tsl
  30198. * @method
  30199. * @param {number} e - The value to swap from the current invocation.
  30200. * @return {number} The value received from the swap operation.
  30201. */
  30202. const quadSwapDiagonal = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.QUAD_SWAP_DIAGONAL ).setParameterLength( 1 );
  30203. /**
  30204. * Broadcasts e from the invocation whose subgroup_invocation_id matches id, to all active invocations.
  30205. *
  30206. * @tsl
  30207. * @method
  30208. * @param {number} e - The value to broadcast from subgroup invocation 'id'.
  30209. * @param {number} id - The subgroup invocation to broadcast from.
  30210. * @return {number} The broadcast value.
  30211. */
  30212. const subgroupBroadcast = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_BROADCAST ).setParameterLength( 2 );
  30213. /**
  30214. * Returns v from the active invocation whose subgroup_invocation_id matches id
  30215. *
  30216. * @tsl
  30217. * @method
  30218. * @param {number} v - The value to return from subgroup invocation id^mask.
  30219. * @param {number} id - The subgroup invocation which returns the value v.
  30220. * @return {number} The broadcast value.
  30221. */
  30222. const subgroupShuffle = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_SHUFFLE ).setParameterLength( 2 );
  30223. /**
  30224. * Returns v from the active invocation whose subgroup_invocation_id matches subgroup_invocation_id ^ mask.
  30225. *
  30226. * @tsl
  30227. * @method
  30228. * @param {number} v - The value to return from subgroup invocation id^mask.
  30229. * @param {number} mask - A bitmask that determines the target invocation via a XOR operation.
  30230. * @return {number} The broadcast value.
  30231. */
  30232. const subgroupShuffleXor = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_SHUFFLE_XOR ).setParameterLength( 2 );
  30233. /**
  30234. * Returns v from the active invocation whose subgroup_invocation_id matches subgroup_invocation_id - delta
  30235. *
  30236. * @tsl
  30237. * @method
  30238. * @param {number} v - The value to return from subgroup invocation id^mask.
  30239. * @param {number} delta - A value that offsets the current in.
  30240. * @return {number} The broadcast value.
  30241. */
  30242. const subgroupShuffleUp = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_SHUFFLE_UP ).setParameterLength( 2 );
  30243. /**
  30244. * Returns v from the active invocation whose subgroup_invocation_id matches subgroup_invocation_id + delta
  30245. *
  30246. * @tsl
  30247. * @method
  30248. * @param {number} v - The value to return from subgroup invocation id^mask.
  30249. * @param {number} delta - A value that offsets the current subgroup invocation.
  30250. * @return {number} The broadcast value.
  30251. */
  30252. const subgroupShuffleDown = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_SHUFFLE_DOWN ).setParameterLength( 2 );
  30253. /**
  30254. * Broadcasts e from the quad invocation with id equal to id.
  30255. *
  30256. * @tsl
  30257. * @method
  30258. * @param {number} e - The value to broadcast.
  30259. * @return {number} The broadcast value.
  30260. */
  30261. const quadBroadcast = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.QUAD_BROADCAST ).setParameterLength( 1 );
  30262. let uniformsLib;
  30263. function getLightData( light ) {
  30264. uniformsLib = uniformsLib || new WeakMap();
  30265. let uniforms = uniformsLib.get( light );
  30266. if ( uniforms === undefined ) uniformsLib.set( light, uniforms = {} );
  30267. return uniforms;
  30268. }
  30269. /**
  30270. * TSL function for getting a shadow matrix uniform node for the given light.
  30271. *
  30272. * @tsl
  30273. * @function
  30274. * @param {Light} light -The light source.
  30275. * @returns {UniformNode<mat4>} The shadow matrix uniform node.
  30276. */
  30277. function lightShadowMatrix( light ) {
  30278. const data = getLightData( light );
  30279. return data.shadowMatrix || ( data.shadowMatrix = uniform( 'mat4' ).setGroup( renderGroup ).onRenderUpdate( ( frame ) => {
  30280. // normally, shadow matrices are updated in ShadowNode. However, if the shadow matrix is used outside
  30281. // of shadow rendering (like in ProjectorLightNode), the shadow matrix still requires an update
  30282. if ( light.castShadow !== true || frame.renderer.shadowMap.enabled === false ) {
  30283. if ( light.shadow.camera.coordinateSystem !== frame.camera.coordinateSystem ) {
  30284. light.shadow.camera.coordinateSystem = frame.camera.coordinateSystem;
  30285. light.shadow.camera.updateProjectionMatrix();
  30286. }
  30287. light.shadow.updateMatrices( light );
  30288. }
  30289. return light.shadow.matrix;
  30290. } ) );
  30291. }
  30292. /**
  30293. * TSL function for getting projected uv coordinates for the given light.
  30294. * Relevant when using maps with spot lights.
  30295. *
  30296. * @tsl
  30297. * @function
  30298. * @param {Light} light -The light source.
  30299. * @param {Node<vec3>} [position=positionWorld] -The position to project.
  30300. * @returns {Node<vec3>} The projected uvs.
  30301. */
  30302. function lightProjectionUV( light, position = positionWorld ) {
  30303. const spotLightCoord = lightShadowMatrix( light ).mul( position );
  30304. const projectionUV = spotLightCoord.xyz.div( spotLightCoord.w );
  30305. return projectionUV;
  30306. }
  30307. /**
  30308. * TSL function for getting the position in world space for the given light.
  30309. *
  30310. * @tsl
  30311. * @function
  30312. * @param {Light} light -The light source.
  30313. * @returns {UniformNode<vec3>} The light's position in world space.
  30314. */
  30315. function lightPosition( light ) {
  30316. const data = getLightData( light );
  30317. return data.position || ( data.position = uniform( new Vector3() ).setGroup( renderGroup ).onRenderUpdate( ( _, self ) => self.value.setFromMatrixPosition( light.matrixWorld ) ) );
  30318. }
  30319. /**
  30320. * TSL function for getting the light target position in world space for the given light.
  30321. *
  30322. * @tsl
  30323. * @function
  30324. * @param {Light} light -The light source.
  30325. * @returns {UniformNode<vec3>} The light target position in world space.
  30326. */
  30327. function lightTargetPosition( light ) {
  30328. const data = getLightData( light );
  30329. return data.targetPosition || ( data.targetPosition = uniform( new Vector3() ).setGroup( renderGroup ).onRenderUpdate( ( _, self ) => self.value.setFromMatrixPosition( light.target.matrixWorld ) ) );
  30330. }
  30331. /**
  30332. * TSL function for getting the position in view space for the given light.
  30333. *
  30334. * @tsl
  30335. * @function
  30336. * @param {Light} light - The light source.
  30337. * @returns {UniformNode<vec3>} The light's position in view space.
  30338. */
  30339. function lightViewPosition( light ) {
  30340. const data = getLightData( light );
  30341. return data.viewPosition || ( data.viewPosition = uniform( new Vector3() ).setGroup( renderGroup ).onRenderUpdate( ( { camera }, self ) => {
  30342. self.value = self.value || new Vector3();
  30343. self.value.setFromMatrixPosition( light.matrixWorld );
  30344. self.value.applyMatrix4( camera.matrixWorldInverse );
  30345. } ) );
  30346. }
  30347. /**
  30348. * TSL function for getting the light target direction for the given light.
  30349. *
  30350. * @tsl
  30351. * @function
  30352. * @param {Light} light -The light source.
  30353. * @returns {Node<vec3>} The light's target direction.
  30354. */
  30355. const lightTargetDirection = ( light ) => cameraViewMatrix.transformDirection( lightPosition( light ).sub( lightTargetPosition( light ) ) );
  30356. const sortLights = ( lights ) => {
  30357. return lights.sort( ( a, b ) => a.id - b.id );
  30358. };
  30359. const getLightNodeById = ( id, lightNodes ) => {
  30360. for ( const lightNode of lightNodes ) {
  30361. if ( lightNode.isAnalyticLightNode && lightNode.light.id === id ) {
  30362. return lightNode;
  30363. }
  30364. }
  30365. return null;
  30366. };
  30367. const _lightsNodeRef = /*@__PURE__*/ new WeakMap();
  30368. const _hashData = [];
  30369. /**
  30370. * This node represents the scene's lighting and manages the lighting model's life cycle
  30371. * for the current build 3D object. It is responsible for computing the total outgoing
  30372. * light in a given lighting context.
  30373. *
  30374. * @augments Node
  30375. */
  30376. class LightsNode extends Node {
  30377. static get type() {
  30378. return 'LightsNode';
  30379. }
  30380. /**
  30381. * Constructs a new lights node.
  30382. */
  30383. constructor() {
  30384. super( 'vec3' );
  30385. /**
  30386. * A node representing the total diffuse light.
  30387. *
  30388. * @type {Node<vec3>}
  30389. */
  30390. this.totalDiffuseNode = property( 'vec3', 'totalDiffuse' );
  30391. /**
  30392. * A node representing the total specular light.
  30393. *
  30394. * @type {Node<vec3>}
  30395. */
  30396. this.totalSpecularNode = property( 'vec3', 'totalSpecular' );
  30397. /**
  30398. * A node representing the outgoing light.
  30399. *
  30400. * @type {Node<vec3>}
  30401. */
  30402. this.outgoingLightNode = property( 'vec3', 'outgoingLight' );
  30403. /**
  30404. * An array representing the lights in the scene.
  30405. *
  30406. * @private
  30407. * @type {Array<Light>}
  30408. */
  30409. this._lights = [];
  30410. /**
  30411. * For each light in the scene, this node will create a
  30412. * corresponding light node.
  30413. *
  30414. * @private
  30415. * @type {?Array<LightingNode>}
  30416. * @default null
  30417. */
  30418. this._lightNodes = null;
  30419. /**
  30420. * A hash for identifying the current light nodes setup.
  30421. *
  30422. * @private
  30423. * @type {?string}
  30424. * @default null
  30425. */
  30426. this._lightNodesHash = null;
  30427. /**
  30428. * `LightsNode` sets this property to `true` by default.
  30429. *
  30430. * @type {boolean}
  30431. * @default true
  30432. */
  30433. this.global = true;
  30434. }
  30435. /**
  30436. * Overwrites the default {@link Node#customCacheKey} implementation by including
  30437. * light data into the cache key.
  30438. *
  30439. * @return {number} The custom cache key.
  30440. */
  30441. customCacheKey() {
  30442. const lights = this._lights;
  30443. for ( let i = 0; i < lights.length; i ++ ) {
  30444. const light = lights[ i ];
  30445. _hashData.push( light.id );
  30446. _hashData.push( light.castShadow ? 1 : 0 );
  30447. if ( light.isSpotLight === true ) {
  30448. const hashMap = ( light.map !== null ) ? light.map.id : -1;
  30449. const hashColorNode = ( light.colorNode ) ? light.colorNode.getCacheKey() : -1;
  30450. _hashData.push( hashMap, hashColorNode );
  30451. }
  30452. }
  30453. const cacheKey = hashArray( _hashData );
  30454. _hashData.length = 0;
  30455. return cacheKey;
  30456. }
  30457. /**
  30458. * Computes a hash value for identifying the current light nodes setup.
  30459. *
  30460. * @param {NodeBuilder} builder - A reference to the current node builder.
  30461. * @return {string} The computed hash.
  30462. */
  30463. getHash( builder ) {
  30464. if ( this._lightNodesHash === null ) {
  30465. if ( this._lightNodes === null ) this.setupLightsNode( builder );
  30466. const hash = [];
  30467. for ( const lightNode of this._lightNodes ) {
  30468. hash.push( lightNode.getHash() );
  30469. }
  30470. this._lightNodesHash = 'lights-' + hash.join( ',' );
  30471. }
  30472. return this._lightNodesHash;
  30473. }
  30474. analyze( builder ) {
  30475. const properties = builder.getNodeProperties( this );
  30476. for ( const node of properties.nodes ) {
  30477. node.build( builder );
  30478. }
  30479. properties.outputNode.build( builder );
  30480. }
  30481. /**
  30482. * Creates lighting nodes for each scene light. This makes it possible to further
  30483. * process lights in the node system.
  30484. *
  30485. * @param {NodeBuilder} builder - A reference to the current node builder.
  30486. */
  30487. setupLightsNode( builder ) {
  30488. const lightNodes = [];
  30489. const previousLightNodes = this._lightNodes;
  30490. const lights = sortLights( this._lights );
  30491. const nodeLibrary = builder.renderer.library;
  30492. for ( const light of lights ) {
  30493. if ( light.isNode ) {
  30494. lightNodes.push( nodeObject( light ) );
  30495. } else {
  30496. let lightNode = null;
  30497. if ( previousLightNodes !== null ) {
  30498. lightNode = getLightNodeById( light.id, previousLightNodes ); // reuse existing light node
  30499. }
  30500. if ( lightNode === null ) {
  30501. // find the corresponding node type for a given light
  30502. const lightNodeClass = nodeLibrary.getLightNodeClass( light.constructor );
  30503. if ( lightNodeClass === null ) {
  30504. warn( `LightsNode.setupNodeLights: Light node not found for ${ light.constructor.name }` );
  30505. continue;
  30506. }
  30507. let lightNode = null;
  30508. if ( ! _lightsNodeRef.has( light ) ) {
  30509. lightNode = nodeObject( new lightNodeClass( light ) );
  30510. _lightsNodeRef.set( light, lightNode );
  30511. } else {
  30512. lightNode = _lightsNodeRef.get( light );
  30513. }
  30514. lightNodes.push( lightNode );
  30515. }
  30516. }
  30517. }
  30518. this._lightNodes = lightNodes;
  30519. }
  30520. /**
  30521. * Sets up a direct light in the lighting model.
  30522. *
  30523. * @param {Object} builder - The builder object containing the context and stack.
  30524. * @param {Object} lightNode - The light node.
  30525. * @param {Object} lightData - The light object containing color and direction properties.
  30526. */
  30527. setupDirectLight( builder, lightNode, lightData ) {
  30528. const { lightingModel, reflectedLight } = builder.context;
  30529. lightingModel.direct( {
  30530. ...lightData,
  30531. lightNode,
  30532. reflectedLight
  30533. }, builder );
  30534. }
  30535. setupDirectRectAreaLight( builder, lightNode, lightData ) {
  30536. const { lightingModel, reflectedLight } = builder.context;
  30537. lightingModel.directRectArea( {
  30538. ...lightData,
  30539. lightNode,
  30540. reflectedLight
  30541. }, builder );
  30542. }
  30543. /**
  30544. * Setups the internal lights by building all respective
  30545. * light nodes.
  30546. *
  30547. * @param {NodeBuilder} builder - A reference to the current node builder.
  30548. * @param {Array<LightingNode>} lightNodes - An array of lighting nodes.
  30549. */
  30550. setupLights( builder, lightNodes ) {
  30551. for ( const lightNode of lightNodes ) {
  30552. lightNode.build( builder );
  30553. }
  30554. }
  30555. getLightNodes( builder ) {
  30556. if ( this._lightNodes === null ) this.setupLightsNode( builder );
  30557. return this._lightNodes;
  30558. }
  30559. /**
  30560. * The implementation makes sure that for each light in the scene
  30561. * there is a corresponding light node. By building the light nodes
  30562. * and evaluating the lighting model the outgoing light is computed.
  30563. *
  30564. * @param {NodeBuilder} builder - A reference to the current node builder.
  30565. * @return {Node<vec3>} A node representing the outgoing light.
  30566. */
  30567. setup( builder ) {
  30568. const currentLightsNode = builder.lightsNode;
  30569. builder.lightsNode = this;
  30570. //
  30571. let outgoingLightNode = this.outgoingLightNode;
  30572. const context = builder.context;
  30573. const lightingModel = context.lightingModel;
  30574. const properties = builder.getNodeProperties( this );
  30575. if ( lightingModel ) {
  30576. const { totalDiffuseNode, totalSpecularNode } = this;
  30577. context.outgoingLight = outgoingLightNode;
  30578. const stack = builder.addStack();
  30579. //
  30580. properties.nodes = stack.nodes;
  30581. //
  30582. lightingModel.start( builder );
  30583. //
  30584. const { backdrop, backdropAlpha } = context;
  30585. const { directDiffuse, directSpecular, indirectDiffuse, indirectSpecular } = context.reflectedLight;
  30586. let totalDiffuse = directDiffuse.add( indirectDiffuse );
  30587. if ( backdrop !== null ) {
  30588. if ( backdropAlpha !== null ) {
  30589. totalDiffuse = vec3( backdropAlpha.mix( totalDiffuse, backdrop ) );
  30590. } else {
  30591. totalDiffuse = vec3( backdrop );
  30592. }
  30593. }
  30594. totalDiffuseNode.assign( totalDiffuse );
  30595. totalSpecularNode.assign( directSpecular.add( indirectSpecular ) );
  30596. outgoingLightNode.assign( totalDiffuseNode.add( totalSpecularNode ) );
  30597. //
  30598. lightingModel.finish( builder );
  30599. //
  30600. outgoingLightNode = outgoingLightNode.bypass( builder.removeStack() );
  30601. } else {
  30602. properties.nodes = [];
  30603. }
  30604. //
  30605. builder.lightsNode = currentLightsNode;
  30606. return outgoingLightNode;
  30607. }
  30608. /**
  30609. * Configures this node with an array of lights.
  30610. *
  30611. * @param {Array<Light>} lights - An array of lights.
  30612. * @return {LightsNode} A reference to this node.
  30613. */
  30614. setLights( lights ) {
  30615. this._lights = lights;
  30616. this._lightNodes = null;
  30617. this._lightNodesHash = null;
  30618. return this;
  30619. }
  30620. /**
  30621. * Returns an array of the scene's lights.
  30622. *
  30623. * @return {Array<Light>} The scene's lights.
  30624. */
  30625. getLights() {
  30626. return this._lights;
  30627. }
  30628. /**
  30629. * Whether the scene has lights or not.
  30630. *
  30631. * @type {boolean}
  30632. */
  30633. get hasLights() {
  30634. return this._lights.length > 0;
  30635. }
  30636. }
  30637. /**
  30638. * TSL function for creating an instance of `LightsNode` and configuring
  30639. * it with the given array of lights.
  30640. *
  30641. * @tsl
  30642. * @function
  30643. * @param {Array<Light>} lights - An array of lights.
  30644. * @return {LightsNode} The created lights node.
  30645. */
  30646. const lights = ( lights = [] ) => nodeObject( new LightsNode() ).setLights( lights );
  30647. /**
  30648. * Base class for all shadow nodes.
  30649. *
  30650. * Shadow nodes encapsulate shadow related logic and are always coupled to lighting nodes.
  30651. * Lighting nodes might share the same shadow node type or use specific ones depending on
  30652. * their requirements.
  30653. *
  30654. * @augments Node
  30655. */
  30656. class ShadowBaseNode extends Node {
  30657. static get type() {
  30658. return 'ShadowBaseNode';
  30659. }
  30660. /**
  30661. * Constructs a new shadow base node.
  30662. *
  30663. * @param {Light} light - The shadow casting light.
  30664. */
  30665. constructor( light ) {
  30666. super();
  30667. /**
  30668. * The shadow casting light.
  30669. *
  30670. * @type {Light}
  30671. */
  30672. this.light = light;
  30673. /**
  30674. * Overwritten since shadows are updated by default per render.
  30675. *
  30676. * @type {string}
  30677. * @default 'render'
  30678. */
  30679. this.updateBeforeType = NodeUpdateType.RENDER;
  30680. /**
  30681. * This flag can be used for type testing.
  30682. *
  30683. * @type {boolean}
  30684. * @readonly
  30685. * @default true
  30686. */
  30687. this.isShadowBaseNode = true;
  30688. }
  30689. /**
  30690. * Setups the shadow position node which is by default the predefined TSL node object `shadowPositionWorld`.
  30691. *
  30692. * @param {NodeBuilder} object - A configuration object that must at least hold a material reference.
  30693. */
  30694. setupShadowPosition( { context, material } ) {
  30695. // Use assign inside an Fn()
  30696. shadowPositionWorld.assign( material.receivedShadowPositionNode || context.shadowPositionWorld || positionWorld );
  30697. }
  30698. }
  30699. /**
  30700. * TSL object that represents the vertex position in world space during the shadow pass.
  30701. *
  30702. * @tsl
  30703. * @type {Node<vec3>}
  30704. */
  30705. const shadowPositionWorld = /*@__PURE__*/ property( 'vec3', 'shadowPositionWorld' );
  30706. /**
  30707. * Saves the state of the given renderer and stores it into the given state object.
  30708. *
  30709. * If not state object is provided, the function creates one.
  30710. *
  30711. * @private
  30712. * @function
  30713. * @param {Renderer} renderer - The renderer.
  30714. * @param {Object} [state={}] - The state.
  30715. * @return {Object} The state.
  30716. */
  30717. function saveRendererState( renderer, state = {} ) {
  30718. state.toneMapping = renderer.toneMapping;
  30719. state.toneMappingExposure = renderer.toneMappingExposure;
  30720. state.outputColorSpace = renderer.outputColorSpace;
  30721. state.renderTarget = renderer.getRenderTarget();
  30722. state.activeCubeFace = renderer.getActiveCubeFace();
  30723. state.activeMipmapLevel = renderer.getActiveMipmapLevel();
  30724. state.renderObjectFunction = renderer.getRenderObjectFunction();
  30725. state.pixelRatio = renderer.getPixelRatio();
  30726. state.mrt = renderer.getMRT();
  30727. state.clearColor = renderer.getClearColor( state.clearColor || new Color() );
  30728. state.clearAlpha = renderer.getClearAlpha();
  30729. state.autoClear = renderer.autoClear;
  30730. state.scissorTest = renderer.getScissorTest();
  30731. return state;
  30732. }
  30733. /**
  30734. * Saves the state of the given renderer and stores it into the given state object.
  30735. * Besides, the function also resets the state of the renderer to its default values.
  30736. *
  30737. * If not state object is provided, the function creates one.
  30738. *
  30739. * @private
  30740. * @function
  30741. * @param {Renderer} renderer - The renderer.
  30742. * @param {Object} [state={}] - The state.
  30743. * @return {Object} The state.
  30744. */
  30745. function resetRendererState( renderer, state ) {
  30746. state = saveRendererState( renderer, state );
  30747. renderer.setMRT( null );
  30748. renderer.setRenderObjectFunction( null );
  30749. renderer.setClearColor( 0x000000, 1 );
  30750. renderer.autoClear = true;
  30751. return state;
  30752. }
  30753. /**
  30754. * Restores the state of the given renderer from the given state object.
  30755. *
  30756. * @private
  30757. * @function
  30758. * @param {Renderer} renderer - The renderer.
  30759. * @param {Object} state - The state to restore.
  30760. */
  30761. function restoreRendererState( renderer, state ) {
  30762. renderer.toneMapping = state.toneMapping;
  30763. renderer.toneMappingExposure = state.toneMappingExposure;
  30764. renderer.outputColorSpace = state.outputColorSpace;
  30765. renderer.setRenderTarget( state.renderTarget, state.activeCubeFace, state.activeMipmapLevel );
  30766. renderer.setRenderObjectFunction( state.renderObjectFunction );
  30767. renderer.setPixelRatio( state.pixelRatio );
  30768. renderer.setMRT( state.mrt );
  30769. renderer.setClearColor( state.clearColor, state.clearAlpha );
  30770. renderer.autoClear = state.autoClear;
  30771. renderer.setScissorTest( state.scissorTest );
  30772. }
  30773. /**
  30774. * Saves the state of the given scene and stores it into the given state object.
  30775. *
  30776. * If not state object is provided, the function creates one.
  30777. *
  30778. * @private
  30779. * @function
  30780. * @param {Scene} scene - The scene.
  30781. * @param {Object} [state={}] - The state.
  30782. * @return {Object} The state.
  30783. */
  30784. function saveSceneState( scene, state = {} ) {
  30785. state.background = scene.background;
  30786. state.backgroundNode = scene.backgroundNode;
  30787. state.overrideMaterial = scene.overrideMaterial;
  30788. return state;
  30789. }
  30790. /**
  30791. * Saves the state of the given scene and stores it into the given state object.
  30792. * Besides, the function also resets the state of the scene to its default values.
  30793. *
  30794. * If not state object is provided, the function creates one.
  30795. *
  30796. * @private
  30797. * @function
  30798. * @param {Scene} scene - The scene.
  30799. * @param {Object} [state={}] - The state.
  30800. * @return {Object} The state.
  30801. */
  30802. function resetSceneState( scene, state ) {
  30803. state = saveSceneState( scene, state );
  30804. scene.background = null;
  30805. scene.backgroundNode = null;
  30806. scene.overrideMaterial = null;
  30807. return state;
  30808. }
  30809. /**
  30810. * Restores the state of the given scene from the given state object.
  30811. *
  30812. * @private
  30813. * @function
  30814. * @param {Scene} scene - The scene.
  30815. * @param {Object} state - The state to restore.
  30816. */
  30817. function restoreSceneState( scene, state ) {
  30818. scene.background = state.background;
  30819. scene.backgroundNode = state.backgroundNode;
  30820. scene.overrideMaterial = state.overrideMaterial;
  30821. }
  30822. /**
  30823. * Saves the state of the given renderer and scene and stores it into the given state object.
  30824. *
  30825. * If not state object is provided, the function creates one.
  30826. *
  30827. * @private
  30828. * @function
  30829. * @param {Renderer} renderer - The renderer.
  30830. * @param {Scene} scene - The scene.
  30831. * @param {Object} [state={}] - The state.
  30832. * @return {Object} The state.
  30833. */
  30834. function saveRendererAndSceneState( renderer, scene, state = {} ) {
  30835. state = saveRendererState( renderer, state );
  30836. state = saveSceneState( scene, state );
  30837. return state;
  30838. }
  30839. /**
  30840. * Saves the state of the given renderer and scene and stores it into the given state object.
  30841. * Besides, the function also resets the state of the renderer and scene to its default values.
  30842. *
  30843. * If not state object is provided, the function creates one.
  30844. *
  30845. * @private
  30846. * @function
  30847. * @param {Renderer} renderer - The renderer.
  30848. * @param {Scene} scene - The scene.
  30849. * @param {Object} [state={}] - The state.
  30850. * @return {Object} The state.
  30851. */
  30852. function resetRendererAndSceneState( renderer, scene, state ) {
  30853. state = resetRendererState( renderer, state );
  30854. state = resetSceneState( scene, state );
  30855. return state;
  30856. }
  30857. /**
  30858. * Restores the state of the given renderer and scene from the given state object.
  30859. *
  30860. * @private
  30861. * @function
  30862. * @param {Renderer} renderer - The renderer.
  30863. * @param {Scene} scene - The scene.
  30864. * @param {Object} state - The state to restore.
  30865. */
  30866. function restoreRendererAndSceneState( renderer, scene, state ) {
  30867. restoreRendererState( renderer, state );
  30868. restoreSceneState( scene, state );
  30869. }
  30870. var RendererUtils = /*#__PURE__*/Object.freeze({
  30871. __proto__: null,
  30872. resetRendererAndSceneState: resetRendererAndSceneState,
  30873. resetRendererState: resetRendererState,
  30874. resetSceneState: resetSceneState,
  30875. restoreRendererAndSceneState: restoreRendererAndSceneState,
  30876. restoreRendererState: restoreRendererState,
  30877. restoreSceneState: restoreSceneState,
  30878. saveRendererAndSceneState: saveRendererAndSceneState,
  30879. saveRendererState: saveRendererState,
  30880. saveSceneState: saveSceneState
  30881. });
  30882. const shadowMaterialLib = /*@__PURE__*/ new WeakMap();
  30883. /**
  30884. * A shadow filtering function performing basic filtering. This is in fact an unfiltered version of the shadow map
  30885. * with a binary `[0,1]` result.
  30886. *
  30887. * @method
  30888. * @param {Object} inputs - The input parameter object.
  30889. * @param {DepthTexture} inputs.depthTexture - A reference to the shadow map's texture data.
  30890. * @param {Node<vec3>} inputs.shadowCoord - The shadow coordinates.
  30891. * @return {Node<float>} The filtering result.
  30892. */
  30893. const BasicShadowFilter = /*@__PURE__*/ Fn( ( { depthTexture, shadowCoord, depthLayer } ) => {
  30894. let basic = texture( depthTexture, shadowCoord.xy ).setName( 't_basic' );
  30895. if ( depthTexture.isArrayTexture ) {
  30896. basic = basic.depth( depthLayer );
  30897. }
  30898. return basic.compare( shadowCoord.z );
  30899. } );
  30900. /**
  30901. * A shadow filtering function performing PCF filtering with Vogel disk sampling and IGN.
  30902. *
  30903. * Uses 5 samples distributed via Vogel disk pattern, rotated per-pixel using Interleaved
  30904. * Gradient Noise (IGN) to break up banding artifacts. Combined with hardware PCF (4-tap
  30905. * filtering per sample), this effectively provides 20 filtered taps with better distribution.
  30906. *
  30907. * @method
  30908. * @param {Object} inputs - The input parameter object.
  30909. * @param {DepthTexture} inputs.depthTexture - A reference to the shadow map's texture data.
  30910. * @param {Node<vec3>} inputs.shadowCoord - The shadow coordinates.
  30911. * @param {LightShadow} inputs.shadow - The light shadow.
  30912. * @return {Node<float>} The filtering result.
  30913. */
  30914. const PCFShadowFilter = /*@__PURE__*/ Fn( ( { depthTexture, shadowCoord, shadow, depthLayer } ) => {
  30915. const depthCompare = ( uv, compare ) => {
  30916. let depth = texture( depthTexture, uv );
  30917. if ( depthTexture.isArrayTexture ) {
  30918. depth = depth.depth( depthLayer );
  30919. }
  30920. return depth.compare( compare );
  30921. };
  30922. const mapSize = reference( 'mapSize', 'vec2', shadow ).setGroup( renderGroup );
  30923. const radius = reference( 'radius', 'float', shadow ).setGroup( renderGroup );
  30924. const texelSize = vec2( 1 ).div( mapSize );
  30925. const radiusScaled = radius.mul( texelSize.x );
  30926. // Use IGN to rotate sampling pattern per pixel (phi = IGN * 2π)
  30927. const phi = interleavedGradientNoise( screenCoordinate.xy ).mul( 6.28318530718 );
  30928. // 5 samples using Vogel disk distribution
  30929. return add(
  30930. depthCompare( shadowCoord.xy.add( vogelDiskSample( 0, 5, phi ).mul( radiusScaled ) ), shadowCoord.z ),
  30931. depthCompare( shadowCoord.xy.add( vogelDiskSample( 1, 5, phi ).mul( radiusScaled ) ), shadowCoord.z ),
  30932. depthCompare( shadowCoord.xy.add( vogelDiskSample( 2, 5, phi ).mul( radiusScaled ) ), shadowCoord.z ),
  30933. depthCompare( shadowCoord.xy.add( vogelDiskSample( 3, 5, phi ).mul( radiusScaled ) ), shadowCoord.z ),
  30934. depthCompare( shadowCoord.xy.add( vogelDiskSample( 4, 5, phi ).mul( radiusScaled ) ), shadowCoord.z )
  30935. ).mul( 1 / 5 );
  30936. } );
  30937. /**
  30938. * A shadow filtering function performing PCF soft filtering.
  30939. *
  30940. * @method
  30941. * @param {Object} inputs - The input parameter object.
  30942. * @param {DepthTexture} inputs.depthTexture - A reference to the shadow map's texture data.
  30943. * @param {Node<vec3>} inputs.shadowCoord - The shadow coordinates.
  30944. * @param {LightShadow} inputs.shadow - The light shadow.
  30945. * @return {Node<float>} The filtering result.
  30946. */
  30947. const PCFSoftShadowFilter = /*@__PURE__*/ Fn( ( { depthTexture, shadowCoord, shadow, depthLayer } ) => {
  30948. const depthCompare = ( uv, compare ) => {
  30949. let depth = texture( depthTexture, uv );
  30950. if ( depthTexture.isArrayTexture ) {
  30951. depth = depth.depth( depthLayer );
  30952. }
  30953. return depth.compare( compare );
  30954. };
  30955. const mapSize = reference( 'mapSize', 'vec2', shadow ).setGroup( renderGroup );
  30956. const texelSize = vec2( 1 ).div( mapSize );
  30957. const dx = texelSize.x;
  30958. const dy = texelSize.y;
  30959. const uv = shadowCoord.xy;
  30960. const f = fract( uv.mul( mapSize ).add( 0.5 ) );
  30961. uv.subAssign( f.mul( texelSize ) );
  30962. return add(
  30963. depthCompare( uv, shadowCoord.z ),
  30964. depthCompare( uv.add( vec2( dx, 0 ) ), shadowCoord.z ),
  30965. depthCompare( uv.add( vec2( 0, dy ) ), shadowCoord.z ),
  30966. depthCompare( uv.add( texelSize ), shadowCoord.z ),
  30967. mix(
  30968. depthCompare( uv.add( vec2( dx.negate(), 0 ) ), shadowCoord.z ),
  30969. depthCompare( uv.add( vec2( dx.mul( 2 ), 0 ) ), shadowCoord.z ),
  30970. f.x
  30971. ),
  30972. mix(
  30973. depthCompare( uv.add( vec2( dx.negate(), dy ) ), shadowCoord.z ),
  30974. depthCompare( uv.add( vec2( dx.mul( 2 ), dy ) ), shadowCoord.z ),
  30975. f.x
  30976. ),
  30977. mix(
  30978. depthCompare( uv.add( vec2( 0, dy.negate() ) ), shadowCoord.z ),
  30979. depthCompare( uv.add( vec2( 0, dy.mul( 2 ) ) ), shadowCoord.z ),
  30980. f.y
  30981. ),
  30982. mix(
  30983. depthCompare( uv.add( vec2( dx, dy.negate() ) ), shadowCoord.z ),
  30984. depthCompare( uv.add( vec2( dx, dy.mul( 2 ) ) ), shadowCoord.z ),
  30985. f.y
  30986. ),
  30987. mix(
  30988. mix(
  30989. depthCompare( uv.add( vec2( dx.negate(), dy.negate() ) ), shadowCoord.z ),
  30990. depthCompare( uv.add( vec2( dx.mul( 2 ), dy.negate() ) ), shadowCoord.z ),
  30991. f.x
  30992. ),
  30993. mix(
  30994. depthCompare( uv.add( vec2( dx.negate(), dy.mul( 2 ) ) ), shadowCoord.z ),
  30995. depthCompare( uv.add( vec2( dx.mul( 2 ), dy.mul( 2 ) ) ), shadowCoord.z ),
  30996. f.x
  30997. ),
  30998. f.y
  30999. )
  31000. ).mul( 1 / 9 );
  31001. } );
  31002. /**
  31003. * A shadow filtering function performing VSM filtering.
  31004. *
  31005. * @method
  31006. * @param {Object} inputs - The input parameter object.
  31007. * @param {DepthTexture} inputs.depthTexture - A reference to the shadow map's texture data.
  31008. * @param {Node<vec3>} inputs.shadowCoord - The shadow coordinates.
  31009. * @return {Node<float>} The filtering result.
  31010. */
  31011. const VSMShadowFilter = /*@__PURE__*/ Fn( ( { depthTexture, shadowCoord, depthLayer } ) => {
  31012. let distribution = texture( depthTexture ).sample( shadowCoord.xy );
  31013. if ( depthTexture.isArrayTexture ) {
  31014. distribution = distribution.depth( depthLayer );
  31015. }
  31016. distribution = distribution.rg;
  31017. const mean = distribution.x;
  31018. const variance = max$1( 0.0000001, distribution.y.mul( distribution.y ) );
  31019. const hardShadow = step( shadowCoord.z, mean );
  31020. // Early return if fully lit
  31021. If( hardShadow.equal( 1.0 ), () => {
  31022. return float( 1.0 );
  31023. } );
  31024. // Distance from mean
  31025. const d = shadowCoord.z.sub( mean );
  31026. // Chebyshev's inequality for upper bound on probability
  31027. let p_max = variance.div( variance.add( d.mul( d ) ) );
  31028. // Reduce light bleeding by remapping [amount, 1] to [0, 1]
  31029. p_max = clamp( sub( p_max, 0.3 ).div( 0.65 ) );
  31030. return max$1( hardShadow, p_max );
  31031. } );
  31032. //
  31033. const linearDistance = /*@__PURE__*/ Fn( ( [ position, cameraNear, cameraFar ] ) => {
  31034. let dist = positionWorld.sub( position ).length();
  31035. dist = dist.sub( cameraNear ).div( cameraFar.sub( cameraNear ) );
  31036. dist = dist.saturate(); // clamp to [ 0, 1 ]
  31037. return dist;
  31038. } );
  31039. const linearShadowDistance = ( light ) => {
  31040. const camera = light.shadow.camera;
  31041. const nearDistance = reference( 'near', 'float', camera ).setGroup( renderGroup );
  31042. const farDistance = reference( 'far', 'float', camera ).setGroup( renderGroup );
  31043. const referencePosition = objectPosition( light );
  31044. return linearDistance( referencePosition, nearDistance, farDistance );
  31045. };
  31046. /**
  31047. * Retrieves or creates a shadow material for the given light source.
  31048. *
  31049. * This function checks if a shadow material already exists for the provided light.
  31050. * If not, it creates a new `NodeMaterial` configured for shadow rendering and stores it
  31051. * in the `shadowMaterialLib` for future use.
  31052. *
  31053. * @tsl
  31054. * @function
  31055. * @param {Light} light - The light source for which the shadow material is needed.
  31056. * If the light is a point light, a depth node is calculated
  31057. * using the linear shadow distance.
  31058. * @returns {NodeMaterial} The shadow material associated with the given light.
  31059. */
  31060. const getShadowMaterial = ( light ) => {
  31061. let material = shadowMaterialLib.get( light );
  31062. if ( material === undefined ) {
  31063. const depthNode = light.isPointLight ? linearShadowDistance( light ) : null;
  31064. material = new NodeMaterial();
  31065. material.colorNode = vec4( 0, 0, 0, 1 );
  31066. material.depthNode = depthNode;
  31067. material.isShadowPassMaterial = true; // Use to avoid other overrideMaterial override material.colorNode unintentionally when using material.shadowNode
  31068. material.name = 'ShadowMaterial';
  31069. material.fog = false;
  31070. shadowMaterialLib.set( light, material );
  31071. }
  31072. return material;
  31073. };
  31074. /**
  31075. * Disposes the shadow material for the given light source.
  31076. *
  31077. * @param {Light} light - The light source.
  31078. */
  31079. const disposeShadowMaterial = ( light ) => {
  31080. const material = shadowMaterialLib.get( light );
  31081. if ( material !== undefined ) {
  31082. material.dispose();
  31083. shadowMaterialLib.delete( light );
  31084. }
  31085. };
  31086. //
  31087. const _shadowRenderObjectLibrary = /*@__PURE__*/ new ChainMap();
  31088. const _shadowRenderObjectKeys = [];
  31089. /**
  31090. * Creates a function to render shadow objects in a scene.
  31091. *
  31092. * @tsl
  31093. * @function
  31094. * @param {Renderer} renderer - The renderer.
  31095. * @param {LightShadow} shadow - The light shadow object containing shadow properties.
  31096. * @param {number} shadowType - The type of shadow map (e.g., BasicShadowMap).
  31097. * @param {boolean} useVelocity - Whether to use velocity data for rendering.
  31098. * @return {shadowRenderObjectFunction} A function that renders shadow objects.
  31099. */
  31100. const getShadowRenderObjectFunction = ( renderer, shadow, shadowType, useVelocity ) => {
  31101. _shadowRenderObjectKeys[ 0 ] = renderer;
  31102. _shadowRenderObjectKeys[ 1 ] = shadow;
  31103. let renderObjectFunction = _shadowRenderObjectLibrary.get( _shadowRenderObjectKeys );
  31104. if ( renderObjectFunction === undefined || ( renderObjectFunction.shadowType !== shadowType || renderObjectFunction.useVelocity !== useVelocity ) ) {
  31105. renderObjectFunction = ( object, scene, _camera, geometry, material, group, ...params ) => {
  31106. if ( object.castShadow === true || ( object.receiveShadow && shadowType === VSMShadowMap ) ) {
  31107. if ( useVelocity ) {
  31108. getDataFromObject( object ).useVelocity = true;
  31109. }
  31110. object.onBeforeShadow( renderer, object, _camera, shadow.camera, geometry, scene.overrideMaterial, group );
  31111. renderer.renderObject( object, scene, _camera, geometry, material, group, ...params );
  31112. object.onAfterShadow( renderer, object, _camera, shadow.camera, geometry, scene.overrideMaterial, group );
  31113. }
  31114. };
  31115. renderObjectFunction.shadowType = shadowType;
  31116. renderObjectFunction.useVelocity = useVelocity;
  31117. _shadowRenderObjectLibrary.set( _shadowRenderObjectKeys, renderObjectFunction );
  31118. }
  31119. _shadowRenderObjectKeys[ 0 ] = null;
  31120. _shadowRenderObjectKeys[ 1 ] = null;
  31121. return renderObjectFunction;
  31122. };
  31123. /**
  31124. * Represents the shader code for the first VSM render pass.
  31125. *
  31126. * @private
  31127. * @method
  31128. * @param {Object} inputs - The input parameter object.
  31129. * @param {Node<float>} inputs.samples - The number of samples
  31130. * @param {Node<float>} inputs.radius - The radius.
  31131. * @param {Node<float>} inputs.size - The size.
  31132. * @param {TextureNode} inputs.shadowPass - A reference to the render target's depth data.
  31133. * @return {Node<vec2>} The VSM output.
  31134. */
  31135. const VSMPassVertical = /*@__PURE__*/ Fn( ( { samples, radius, size, shadowPass, depthLayer } ) => {
  31136. const mean = float( 0 ).toVar( 'meanVertical' );
  31137. const squaredMean = float( 0 ).toVar( 'squareMeanVertical' );
  31138. const uvStride = samples.lessThanEqual( float( 1 ) ).select( float( 0 ), float( 2 ).div( samples.sub( 1 ) ) );
  31139. const uvStart = samples.lessThanEqual( float( 1 ) ).select( float( 0 ), float( -1 ) );
  31140. Loop( { start: int( 0 ), end: int( samples ), type: 'int', condition: '<' }, ( { i } ) => {
  31141. const uvOffset = uvStart.add( float( i ).mul( uvStride ) );
  31142. let depth = shadowPass.sample( add( screenCoordinate.xy, vec2( 0, uvOffset ).mul( radius ) ).div( size ) );
  31143. if ( shadowPass.value.isArrayTexture ) {
  31144. depth = depth.depth( depthLayer );
  31145. }
  31146. depth = depth.x;
  31147. mean.addAssign( depth );
  31148. squaredMean.addAssign( depth.mul( depth ) );
  31149. } );
  31150. mean.divAssign( samples );
  31151. squaredMean.divAssign( samples );
  31152. const std_dev = sqrt( squaredMean.sub( mean.mul( mean ) ).max( 0 ) );
  31153. return vec2( mean, std_dev );
  31154. } );
  31155. /**
  31156. * Represents the shader code for the second VSM render pass.
  31157. *
  31158. * @private
  31159. * @method
  31160. * @param {Object} inputs - The input parameter object.
  31161. * @param {Node<float>} inputs.samples - The number of samples
  31162. * @param {Node<float>} inputs.radius - The radius.
  31163. * @param {Node<float>} inputs.size - The size.
  31164. * @param {TextureNode} inputs.shadowPass - The result of the first VSM render pass.
  31165. * @return {Node<vec2>} The VSM output.
  31166. */
  31167. const VSMPassHorizontal = /*@__PURE__*/ Fn( ( { samples, radius, size, shadowPass, depthLayer } ) => {
  31168. const mean = float( 0 ).toVar( 'meanHorizontal' );
  31169. const squaredMean = float( 0 ).toVar( 'squareMeanHorizontal' );
  31170. const uvStride = samples.lessThanEqual( float( 1 ) ).select( float( 0 ), float( 2 ).div( samples.sub( 1 ) ) );
  31171. const uvStart = samples.lessThanEqual( float( 1 ) ).select( float( 0 ), float( -1 ) );
  31172. Loop( { start: int( 0 ), end: int( samples ), type: 'int', condition: '<' }, ( { i } ) => {
  31173. const uvOffset = uvStart.add( float( i ).mul( uvStride ) );
  31174. let distribution = shadowPass.sample( add( screenCoordinate.xy, vec2( uvOffset, 0 ).mul( radius ) ).div( size ) );
  31175. if ( shadowPass.value.isArrayTexture ) {
  31176. distribution = distribution.depth( depthLayer );
  31177. }
  31178. mean.addAssign( distribution.x );
  31179. squaredMean.addAssign( add( distribution.y.mul( distribution.y ), distribution.x.mul( distribution.x ) ) );
  31180. } );
  31181. mean.divAssign( samples );
  31182. squaredMean.divAssign( samples );
  31183. const std_dev = sqrt( squaredMean.sub( mean.mul( mean ) ).max( 0 ) );
  31184. return vec2( mean, std_dev );
  31185. } );
  31186. const _shadowFilterLib = [ BasicShadowFilter, PCFShadowFilter, PCFSoftShadowFilter, VSMShadowFilter ];
  31187. //
  31188. let _rendererState;
  31189. const _quadMesh = /*@__PURE__*/ new QuadMesh();
  31190. /**
  31191. * Represents the default shadow implementation for lighting nodes.
  31192. *
  31193. * @augments ShadowBaseNode
  31194. */
  31195. class ShadowNode extends ShadowBaseNode {
  31196. static get type() {
  31197. return 'ShadowNode';
  31198. }
  31199. /**
  31200. * Constructs a new shadow node.
  31201. *
  31202. * @param {Light} light - The shadow casting light.
  31203. * @param {?LightShadow} [shadow=null] - An optional light shadow.
  31204. */
  31205. constructor( light, shadow = null ) {
  31206. super( light );
  31207. /**
  31208. * The light shadow which defines the properties light's
  31209. * shadow.
  31210. *
  31211. * @type {?LightShadow}
  31212. * @default null
  31213. */
  31214. this.shadow = shadow || light.shadow;
  31215. /**
  31216. * A reference to the shadow map which is a render target.
  31217. *
  31218. * @type {?RenderTarget}
  31219. * @default null
  31220. */
  31221. this.shadowMap = null;
  31222. /**
  31223. * Only relevant for VSM shadows. Render target for the
  31224. * first VSM render pass.
  31225. *
  31226. * @type {?RenderTarget}
  31227. * @default null
  31228. */
  31229. this.vsmShadowMapVertical = null;
  31230. /**
  31231. * Only relevant for VSM shadows. Render target for the
  31232. * second VSM render pass.
  31233. *
  31234. * @type {?RenderTarget}
  31235. * @default null
  31236. */
  31237. this.vsmShadowMapHorizontal = null;
  31238. /**
  31239. * Only relevant for VSM shadows. Node material which
  31240. * is used to render the first VSM pass.
  31241. *
  31242. * @type {?NodeMaterial}
  31243. * @default null
  31244. */
  31245. this.vsmMaterialVertical = null;
  31246. /**
  31247. * Only relevant for VSM shadows. Node material which
  31248. * is used to render the second VSM pass.
  31249. *
  31250. * @type {?NodeMaterial}
  31251. * @default null
  31252. */
  31253. this.vsmMaterialHorizontal = null;
  31254. /**
  31255. * A reference to the output node which defines the
  31256. * final result of this shadow node.
  31257. *
  31258. * @type {?Node}
  31259. * @private
  31260. * @default null
  31261. */
  31262. this._node = null;
  31263. /**
  31264. * The current shadow map type of this shadow node.
  31265. *
  31266. * @type {?number}
  31267. * @private
  31268. * @default null
  31269. */
  31270. this._currentShadowType = null;
  31271. /**
  31272. * A Weak Map holding the current frame ID per camera. Used
  31273. * to control the update of shadow maps.
  31274. *
  31275. * @type {WeakMap<Camera,number>}
  31276. * @private
  31277. */
  31278. this._cameraFrameId = new WeakMap();
  31279. /**
  31280. * This flag can be used for type testing.
  31281. *
  31282. * @type {boolean}
  31283. * @readonly
  31284. * @default true
  31285. */
  31286. this.isShadowNode = true;
  31287. /**
  31288. * This index can be used when overriding setupRenderTarget with a RenderTarget Array to specify the depth layer.
  31289. *
  31290. * @type {number}
  31291. * @readonly
  31292. * @default true
  31293. */
  31294. this.depthLayer = 0;
  31295. }
  31296. /**
  31297. * Setups the shadow filtering.
  31298. *
  31299. * @param {NodeBuilder} builder - A reference to the current node builder.
  31300. * @param {Object} inputs - A configuration object that defines the shadow filtering.
  31301. * @param {Function} inputs.filterFn - This function defines the filtering type of the shadow map e.g. PCF.
  31302. * @param {DepthTexture} inputs.depthTexture - A reference to the shadow map's texture data.
  31303. * @param {Node<vec3>} inputs.shadowCoord - Shadow coordinates which are used to sample from the shadow map.
  31304. * @param {LightShadow} inputs.shadow - The light shadow.
  31305. * @return {Node<float>} The result node of the shadow filtering.
  31306. */
  31307. setupShadowFilter( builder, { filterFn, depthTexture, shadowCoord, shadow, depthLayer } ) {
  31308. const frustumTest = shadowCoord.x.greaterThanEqual( 0 )
  31309. .and( shadowCoord.x.lessThanEqual( 1 ) )
  31310. .and( shadowCoord.y.greaterThanEqual( 0 ) )
  31311. .and( shadowCoord.y.lessThanEqual( 1 ) )
  31312. .and( shadowCoord.z.lessThanEqual( 1 ) );
  31313. const shadowNode = filterFn( { depthTexture, shadowCoord, shadow, depthLayer } );
  31314. return frustumTest.select( shadowNode, float( 1 ) );
  31315. }
  31316. /**
  31317. * Setups the shadow coordinates.
  31318. *
  31319. * @param {NodeBuilder} builder - A reference to the current node builder.
  31320. * @param {Node<vec3>} shadowPosition - A node representing the shadow position.
  31321. * @return {Node<vec3>} The shadow coordinates.
  31322. */
  31323. setupShadowCoord( builder, shadowPosition ) {
  31324. const { shadow } = this;
  31325. const { renderer } = builder;
  31326. const bias = reference( 'bias', 'float', shadow ).setGroup( renderGroup );
  31327. let shadowCoord = shadowPosition;
  31328. let coordZ;
  31329. if ( shadow.camera.isOrthographicCamera || renderer.logarithmicDepthBuffer !== true ) {
  31330. shadowCoord = shadowCoord.xyz.div( shadowCoord.w );
  31331. coordZ = shadowCoord.z;
  31332. if ( renderer.coordinateSystem === WebGPUCoordinateSystem ) {
  31333. coordZ = coordZ.mul( 2 ).sub( 1 ); // WebGPU: Conversion [ 0, 1 ] to [ - 1, 1 ]
  31334. }
  31335. } else {
  31336. const w = shadowCoord.w;
  31337. shadowCoord = shadowCoord.xy.div( w ); // <-- Only divide X/Y coords since we don't need Z
  31338. // The normally available "cameraNear" and "cameraFar" nodes cannot be used here because they do not get
  31339. // updated to use the shadow camera. So, we have to declare our own "local" ones here.
  31340. // TODO: How do we get the cameraNear/cameraFar nodes to use the shadow camera so we don't have to declare local ones here?
  31341. const cameraNearLocal = reference( 'near', 'float', shadow.camera ).setGroup( renderGroup );
  31342. const cameraFarLocal = reference( 'far', 'float', shadow.camera ).setGroup( renderGroup );
  31343. coordZ = viewZToLogarithmicDepth( w.negate(), cameraNearLocal, cameraFarLocal );
  31344. }
  31345. shadowCoord = vec3(
  31346. shadowCoord.x,
  31347. shadowCoord.y.oneMinus(), // follow webgpu standards
  31348. coordZ.add( bias )
  31349. );
  31350. return shadowCoord;
  31351. }
  31352. /**
  31353. * Returns the shadow filtering function for the given shadow type.
  31354. *
  31355. * @param {number} type - The shadow type.
  31356. * @return {Function} The filtering function.
  31357. */
  31358. getShadowFilterFn( type ) {
  31359. return _shadowFilterLib[ type ];
  31360. }
  31361. setupRenderTarget( shadow, builder ) {
  31362. const depthTexture = new DepthTexture( shadow.mapSize.width, shadow.mapSize.height );
  31363. depthTexture.name = 'ShadowDepthTexture';
  31364. depthTexture.compareFunction = LessCompare;
  31365. const shadowMap = builder.createRenderTarget( shadow.mapSize.width, shadow.mapSize.height );
  31366. shadowMap.texture.name = 'ShadowMap';
  31367. shadowMap.texture.type = shadow.mapType;
  31368. shadowMap.depthTexture = depthTexture;
  31369. return { shadowMap, depthTexture };
  31370. }
  31371. /**
  31372. * Setups the shadow output node.
  31373. *
  31374. * @param {NodeBuilder} builder - A reference to the current node builder.
  31375. * @return {Node<vec3>} The shadow output node.
  31376. */
  31377. setupShadow( builder ) {
  31378. const { renderer, camera } = builder;
  31379. const { light, shadow } = this;
  31380. const shadowMapType = renderer.shadowMap.type;
  31381. const { depthTexture, shadowMap } = this.setupRenderTarget( shadow, builder );
  31382. shadow.camera.coordinateSystem = camera.coordinateSystem;
  31383. shadow.camera.updateProjectionMatrix();
  31384. // VSM
  31385. if ( shadowMapType === VSMShadowMap && shadow.isPointLightShadow !== true ) {
  31386. depthTexture.compareFunction = null; // VSM does not use textureSampleCompare()/texture2DCompare()
  31387. if ( shadowMap.depth > 1 ) {
  31388. if ( ! shadowMap._vsmShadowMapVertical ) {
  31389. shadowMap._vsmShadowMapVertical = builder.createRenderTarget( shadow.mapSize.width, shadow.mapSize.height, { format: RGFormat, type: HalfFloatType, depth: shadowMap.depth, depthBuffer: false } );
  31390. shadowMap._vsmShadowMapVertical.texture.name = 'VSMVertical';
  31391. }
  31392. this.vsmShadowMapVertical = shadowMap._vsmShadowMapVertical;
  31393. if ( ! shadowMap._vsmShadowMapHorizontal ) {
  31394. shadowMap._vsmShadowMapHorizontal = builder.createRenderTarget( shadow.mapSize.width, shadow.mapSize.height, { format: RGFormat, type: HalfFloatType, depth: shadowMap.depth, depthBuffer: false } );
  31395. shadowMap._vsmShadowMapHorizontal.texture.name = 'VSMHorizontal';
  31396. }
  31397. this.vsmShadowMapHorizontal = shadowMap._vsmShadowMapHorizontal;
  31398. } else {
  31399. this.vsmShadowMapVertical = builder.createRenderTarget( shadow.mapSize.width, shadow.mapSize.height, { format: RGFormat, type: HalfFloatType, depthBuffer: false } );
  31400. this.vsmShadowMapHorizontal = builder.createRenderTarget( shadow.mapSize.width, shadow.mapSize.height, { format: RGFormat, type: HalfFloatType, depthBuffer: false } );
  31401. }
  31402. let shadowPassVertical = texture( depthTexture );
  31403. if ( depthTexture.isArrayTexture ) {
  31404. shadowPassVertical = shadowPassVertical.depth( this.depthLayer );
  31405. }
  31406. let shadowPassHorizontal = texture( this.vsmShadowMapVertical.texture );
  31407. if ( depthTexture.isArrayTexture ) {
  31408. shadowPassHorizontal = shadowPassHorizontal.depth( this.depthLayer );
  31409. }
  31410. const samples = reference( 'blurSamples', 'float', shadow ).setGroup( renderGroup );
  31411. const radius = reference( 'radius', 'float', shadow ).setGroup( renderGroup );
  31412. const size = reference( 'mapSize', 'vec2', shadow ).setGroup( renderGroup );
  31413. let material = this.vsmMaterialVertical || ( this.vsmMaterialVertical = new NodeMaterial() );
  31414. material.fragmentNode = VSMPassVertical( { samples, radius, size, shadowPass: shadowPassVertical, depthLayer: this.depthLayer } ).context( builder.getSharedContext() );
  31415. material.name = 'VSMVertical';
  31416. material = this.vsmMaterialHorizontal || ( this.vsmMaterialHorizontal = new NodeMaterial() );
  31417. material.fragmentNode = VSMPassHorizontal( { samples, radius, size, shadowPass: shadowPassHorizontal, depthLayer: this.depthLayer } ).context( builder.getSharedContext() );
  31418. material.name = 'VSMHorizontal';
  31419. }
  31420. //
  31421. const shadowIntensity = reference( 'intensity', 'float', shadow ).setGroup( renderGroup );
  31422. const normalBias = reference( 'normalBias', 'float', shadow ).setGroup( renderGroup );
  31423. const shadowPosition = lightShadowMatrix( light ).mul( shadowPositionWorld.add( normalWorld.mul( normalBias ) ) );
  31424. const shadowCoord = this.setupShadowCoord( builder, shadowPosition );
  31425. //
  31426. const filterFn = shadow.filterNode || this.getShadowFilterFn( renderer.shadowMap.type ) || null;
  31427. if ( filterFn === null ) {
  31428. throw new Error( 'THREE.WebGPURenderer: Shadow map type not supported yet.' );
  31429. }
  31430. const shadowDepthTexture = ( shadowMapType === VSMShadowMap && shadow.isPointLightShadow !== true ) ? this.vsmShadowMapHorizontal.texture : depthTexture;
  31431. const shadowNode = this.setupShadowFilter( builder, { filterFn, shadowTexture: shadowMap.texture, depthTexture: shadowDepthTexture, shadowCoord, shadow, depthLayer: this.depthLayer } );
  31432. let shadowColor;
  31433. if ( shadowMap.texture.isCubeTexture ) {
  31434. // For cube shadow maps (point lights), use cubeTexture with vec3 coordinates
  31435. shadowColor = cubeTexture( shadowMap.texture, shadowCoord.xyz );
  31436. } else {
  31437. shadowColor = texture( shadowMap.texture, shadowCoord );
  31438. if ( depthTexture.isArrayTexture ) {
  31439. shadowColor = shadowColor.depth( this.depthLayer );
  31440. }
  31441. }
  31442. const shadowOutput = mix( 1, shadowNode.rgb.mix( shadowColor, 1 ), shadowIntensity.mul( shadowColor.a ) ).toVar();
  31443. this.shadowMap = shadowMap;
  31444. this.shadow.map = shadowMap;
  31445. // Shadow Output + Inspector
  31446. const inspectName = `${ this.light.type } Shadow [ ${ this.light.name || 'ID: ' + this.light.id } ]`;
  31447. return shadowOutput.toInspector( `${ inspectName } / Color`, () => {
  31448. if ( this.shadowMap.texture.isCubeTexture ) {
  31449. return cubeTexture( this.shadowMap.texture );
  31450. }
  31451. return texture( this.shadowMap.texture );
  31452. } ).toInspector( `${ inspectName } / Depth`, () => {
  31453. // TODO: Use linear depth
  31454. if ( this.shadowMap.texture.isCubeTexture ) {
  31455. return cubeTexture( this.shadowMap.texture ).r.oneMinus();
  31456. }
  31457. return textureLoad( this.shadowMap.depthTexture, uv$1().mul( textureSize( texture( this.shadowMap.depthTexture ) ) ) ).r.oneMinus();
  31458. } );
  31459. }
  31460. /**
  31461. * The implementation performs the setup of the output node. An output is only
  31462. * produces if shadow mapping is globally enabled in the renderer.
  31463. *
  31464. * @param {NodeBuilder} builder - A reference to the current node builder.
  31465. * @return {ShaderCallNodeInternal} The output node.
  31466. */
  31467. setup( builder ) {
  31468. if ( builder.renderer.shadowMap.enabled === false ) return;
  31469. return Fn( () => {
  31470. const currentShadowType = builder.renderer.shadowMap.type;
  31471. if ( this._currentShadowType !== currentShadowType ) {
  31472. this._reset();
  31473. this._node = null;
  31474. }
  31475. let node = this._node;
  31476. this.setupShadowPosition( builder );
  31477. if ( node === null ) {
  31478. this._node = node = this.setupShadow( builder );
  31479. this._currentShadowType = currentShadowType;
  31480. }
  31481. if ( builder.material.shadowNode ) { // @deprecated, r171
  31482. warn( 'NodeMaterial: ".shadowNode" is deprecated. Use ".castShadowNode" instead.' );
  31483. }
  31484. if ( builder.material.receivedShadowNode ) {
  31485. node = builder.material.receivedShadowNode( node );
  31486. }
  31487. return node;
  31488. } )();
  31489. }
  31490. /**
  31491. * Renders the shadow. The logic of this function could be included
  31492. * into {@link ShadowNode#updateShadow} however more specialized shadow
  31493. * nodes might require a custom shadow map rendering. By having a
  31494. * dedicated method, it's easier to overwrite the default behavior.
  31495. *
  31496. * @param {NodeFrame} frame - A reference to the current node frame.
  31497. */
  31498. renderShadow( frame ) {
  31499. const { shadow, shadowMap, light } = this;
  31500. const { renderer, scene } = frame;
  31501. shadow.updateMatrices( light );
  31502. shadowMap.setSize( shadow.mapSize.width, shadow.mapSize.height, shadowMap.depth );
  31503. const currentSceneName = scene.name;
  31504. scene.name = `Shadow Map [ ${ light.name || 'ID: ' + light.id } ]`;
  31505. renderer.render( scene, shadow.camera );
  31506. scene.name = currentSceneName;
  31507. }
  31508. /**
  31509. * Updates the shadow.
  31510. *
  31511. * @param {NodeFrame} frame - A reference to the current node frame.
  31512. */
  31513. updateShadow( frame ) {
  31514. const { shadowMap, light, shadow } = this;
  31515. const { renderer, scene, camera } = frame;
  31516. const shadowType = renderer.shadowMap.type;
  31517. const depthVersion = shadowMap.depthTexture.version;
  31518. this._depthVersionCached = depthVersion;
  31519. const _shadowCameraLayer = shadow.camera.layers.mask;
  31520. if ( ( shadow.camera.layers.mask & 0xFFFFFFFE ) === 0 ) {
  31521. shadow.camera.layers.mask = camera.layers.mask;
  31522. }
  31523. const currentRenderObjectFunction = renderer.getRenderObjectFunction();
  31524. const currentMRT = renderer.getMRT();
  31525. const useVelocity = currentMRT ? currentMRT.has( 'velocity' ) : false;
  31526. _rendererState = resetRendererAndSceneState( renderer, scene, _rendererState );
  31527. scene.overrideMaterial = getShadowMaterial( light );
  31528. renderer.setRenderObjectFunction( getShadowRenderObjectFunction( renderer, shadow, shadowType, useVelocity ) );
  31529. renderer.setClearColor( 0x000000, 0 );
  31530. renderer.setRenderTarget( shadowMap );
  31531. this.renderShadow( frame );
  31532. renderer.setRenderObjectFunction( currentRenderObjectFunction );
  31533. // vsm blur pass
  31534. if ( shadowType === VSMShadowMap && shadow.isPointLightShadow !== true ) {
  31535. this.vsmPass( renderer );
  31536. }
  31537. shadow.camera.layers.mask = _shadowCameraLayer;
  31538. restoreRendererAndSceneState( renderer, scene, _rendererState );
  31539. }
  31540. /**
  31541. * For VSM additional render passes are required.
  31542. *
  31543. * @param {Renderer} renderer - A reference to the current renderer.
  31544. */
  31545. vsmPass( renderer ) {
  31546. const { shadow } = this;
  31547. const depth = this.shadowMap.depth;
  31548. this.vsmShadowMapVertical.setSize( shadow.mapSize.width, shadow.mapSize.height, depth );
  31549. this.vsmShadowMapHorizontal.setSize( shadow.mapSize.width, shadow.mapSize.height, depth );
  31550. renderer.setRenderTarget( this.vsmShadowMapVertical );
  31551. _quadMesh.material = this.vsmMaterialVertical;
  31552. _quadMesh.render( renderer );
  31553. renderer.setRenderTarget( this.vsmShadowMapHorizontal );
  31554. _quadMesh.material = this.vsmMaterialHorizontal;
  31555. _quadMesh.render( renderer );
  31556. }
  31557. /**
  31558. * Frees the internal resources of this shadow node.
  31559. */
  31560. dispose() {
  31561. this._reset();
  31562. super.dispose();
  31563. }
  31564. /**
  31565. * Resets the resouce state of this shadow node.
  31566. *
  31567. * @private
  31568. */
  31569. _reset() {
  31570. this._currentShadowType = null;
  31571. disposeShadowMaterial( this.light );
  31572. if ( this.shadowMap ) {
  31573. this.shadowMap.dispose();
  31574. this.shadowMap = null;
  31575. }
  31576. if ( this.vsmShadowMapVertical !== null ) {
  31577. this.vsmShadowMapVertical.dispose();
  31578. this.vsmShadowMapVertical = null;
  31579. this.vsmMaterialVertical.dispose();
  31580. this.vsmMaterialVertical = null;
  31581. }
  31582. if ( this.vsmShadowMapHorizontal !== null ) {
  31583. this.vsmShadowMapHorizontal.dispose();
  31584. this.vsmShadowMapHorizontal = null;
  31585. this.vsmMaterialHorizontal.dispose();
  31586. this.vsmMaterialHorizontal = null;
  31587. }
  31588. }
  31589. /**
  31590. * The implementation performs the update of the shadow map if necessary.
  31591. *
  31592. * @param {NodeFrame} frame - A reference to the current node frame.
  31593. */
  31594. updateBefore( frame ) {
  31595. const { shadow } = this;
  31596. let needsUpdate = shadow.needsUpdate || shadow.autoUpdate;
  31597. if ( needsUpdate ) {
  31598. if ( this._cameraFrameId[ frame.camera ] === frame.frameId ) {
  31599. needsUpdate = false;
  31600. }
  31601. this._cameraFrameId[ frame.camera ] = frame.frameId;
  31602. }
  31603. if ( needsUpdate ) {
  31604. this.updateShadow( frame );
  31605. if ( this.shadowMap.depthTexture.version === this._depthVersionCached ) {
  31606. shadow.needsUpdate = false;
  31607. }
  31608. }
  31609. }
  31610. }
  31611. /**
  31612. * Shadow Render Object Function.
  31613. *
  31614. * @function shadowRenderObjectFunction
  31615. * @param {Object3D} object - The 3D object to render.
  31616. * @param {Scene} scene - The scene containing the object.
  31617. * @param {Camera} _camera - The camera used for rendering.
  31618. * @param {BufferGeometry} geometry - The geometry of the object.
  31619. * @param {Material} material - The material of the object.
  31620. * @param {Group} group - The group the object belongs to.
  31621. * @param {...any} params - Additional parameters for rendering.
  31622. */
  31623. /**
  31624. * TSL function for creating an instance of `ShadowNode`.
  31625. *
  31626. * @tsl
  31627. * @function
  31628. * @param {Light} light - The shadow casting light.
  31629. * @param {?LightShadow} [shadow] - The light shadow.
  31630. * @return {ShadowNode} The created shadow node.
  31631. */
  31632. const shadow = ( light, shadow ) => nodeObject( new ShadowNode( light, shadow ) );
  31633. const _clearColor$1 = /*@__PURE__*/ new Color();
  31634. const _projScreenMatrix$1 = /*@__PURE__*/ new Matrix4();
  31635. const _lightPositionWorld = /*@__PURE__*/ new Vector3();
  31636. const _lookTarget = /*@__PURE__*/ new Vector3();
  31637. // Cube map face directions and up vectors for point light shadows
  31638. // Face order: +X, -X, +Y, -Y, +Z, -Z
  31639. // WebGPU coordinate system - Y faces swapped to match texture sampling convention
  31640. const _cubeDirectionsWebGPU = [
  31641. /*@__PURE__*/ new Vector3( 1, 0, 0 ), /*@__PURE__*/ new Vector3( -1, 0, 0 ), /*@__PURE__*/ new Vector3( 0, -1, 0 ),
  31642. /*@__PURE__*/ new Vector3( 0, 1, 0 ), /*@__PURE__*/ new Vector3( 0, 0, 1 ), /*@__PURE__*/ new Vector3( 0, 0, -1 )
  31643. ];
  31644. const _cubeUpsWebGPU = [
  31645. /*@__PURE__*/ new Vector3( 0, -1, 0 ), /*@__PURE__*/ new Vector3( 0, -1, 0 ), /*@__PURE__*/ new Vector3( 0, 0, -1 ),
  31646. /*@__PURE__*/ new Vector3( 0, 0, 1 ), /*@__PURE__*/ new Vector3( 0, -1, 0 ), /*@__PURE__*/ new Vector3( 0, -1, 0 )
  31647. ];
  31648. // WebGL coordinate system - standard OpenGL convention
  31649. const _cubeDirectionsWebGL = [
  31650. /*@__PURE__*/ new Vector3( 1, 0, 0 ), /*@__PURE__*/ new Vector3( -1, 0, 0 ), /*@__PURE__*/ new Vector3( 0, 1, 0 ),
  31651. /*@__PURE__*/ new Vector3( 0, -1, 0 ), /*@__PURE__*/ new Vector3( 0, 0, 1 ), /*@__PURE__*/ new Vector3( 0, 0, -1 )
  31652. ];
  31653. const _cubeUpsWebGL = [
  31654. /*@__PURE__*/ new Vector3( 0, -1, 0 ), /*@__PURE__*/ new Vector3( 0, -1, 0 ), /*@__PURE__*/ new Vector3( 0, 0, 1 ),
  31655. /*@__PURE__*/ new Vector3( 0, 0, -1 ), /*@__PURE__*/ new Vector3( 0, -1, 0 ), /*@__PURE__*/ new Vector3( 0, -1, 0 )
  31656. ];
  31657. const BasicPointShadowFilter = /*@__PURE__*/ Fn( ( { depthTexture, bd3D, dp } ) => {
  31658. return cubeTexture( depthTexture, bd3D ).compare( dp );
  31659. } );
  31660. /**
  31661. * A shadow filtering function for point lights using Vogel disk sampling and IGN.
  31662. *
  31663. * Uses 5 samples distributed via Vogel disk pattern in tangent space around the
  31664. * sample direction, rotated per-pixel using Interleaved Gradient Noise (IGN).
  31665. *
  31666. * @method
  31667. * @param {Object} inputs - The input parameter object.
  31668. * @param {CubeDepthTexture} inputs.depthTexture - A reference to the shadow cube map.
  31669. * @param {Node<vec3>} inputs.bd3D - The normalized direction from light to fragment.
  31670. * @param {Node<float>} inputs.dp - The depth value to compare against.
  31671. * @param {LightShadow} inputs.shadow - The light shadow.
  31672. * @return {Node<float>} The filtering result.
  31673. */
  31674. const PointShadowFilter = /*@__PURE__*/ Fn( ( { depthTexture, bd3D, dp, shadow } ) => {
  31675. const radius = reference( 'radius', 'float', shadow ).setGroup( renderGroup );
  31676. const mapSize = reference( 'mapSize', 'vec2', shadow ).setGroup( renderGroup );
  31677. const texelSize = radius.div( mapSize.x );
  31678. // Build a tangent-space coordinate system for applying offsets
  31679. const absDir = abs( bd3D );
  31680. const tangent = normalize( cross( bd3D, absDir.x.greaterThan( absDir.z ).select( vec3( 0, 1, 0 ), vec3( 1, 0, 0 ) ) ) );
  31681. const bitangent = cross( bd3D, tangent );
  31682. // Use IGN to rotate sampling pattern per pixel (phi = IGN * 2π)
  31683. const phi = interleavedGradientNoise( screenCoordinate.xy ).mul( 6.28318530718 );
  31684. // 5 samples using Vogel disk distribution in tangent space
  31685. const sample0 = vogelDiskSample( 0, 5, phi );
  31686. const sample1 = vogelDiskSample( 1, 5, phi );
  31687. const sample2 = vogelDiskSample( 2, 5, phi );
  31688. const sample3 = vogelDiskSample( 3, 5, phi );
  31689. const sample4 = vogelDiskSample( 4, 5, phi );
  31690. return cubeTexture( depthTexture, bd3D.add( tangent.mul( sample0.x ).add( bitangent.mul( sample0.y ) ).mul( texelSize ) ) ).compare( dp )
  31691. .add( cubeTexture( depthTexture, bd3D.add( tangent.mul( sample1.x ).add( bitangent.mul( sample1.y ) ).mul( texelSize ) ) ).compare( dp ) )
  31692. .add( cubeTexture( depthTexture, bd3D.add( tangent.mul( sample2.x ).add( bitangent.mul( sample2.y ) ).mul( texelSize ) ) ).compare( dp ) )
  31693. .add( cubeTexture( depthTexture, bd3D.add( tangent.mul( sample3.x ).add( bitangent.mul( sample3.y ) ).mul( texelSize ) ) ).compare( dp ) )
  31694. .add( cubeTexture( depthTexture, bd3D.add( tangent.mul( sample4.x ).add( bitangent.mul( sample4.y ) ).mul( texelSize ) ) ).compare( dp ) )
  31695. .mul( 1.0 / 5.0 );
  31696. } );
  31697. const pointShadowFilter = /*@__PURE__*/ Fn( ( { filterFn, depthTexture, shadowCoord, shadow } ) => {
  31698. // for point lights, the uniform @vShadowCoord is re-purposed to hold
  31699. // the vector from the light to the world-space position of the fragment.
  31700. const lightToPosition = shadowCoord.xyz.toVar();
  31701. const lightToPositionLength = lightToPosition.length();
  31702. const cameraNearLocal = uniform( 'float' ).setGroup( renderGroup ).onRenderUpdate( () => shadow.camera.near );
  31703. const cameraFarLocal = uniform( 'float' ).setGroup( renderGroup ).onRenderUpdate( () => shadow.camera.far );
  31704. const bias = reference( 'bias', 'float', shadow ).setGroup( renderGroup );
  31705. const result = float( 1.0 ).toVar();
  31706. If( lightToPositionLength.sub( cameraFarLocal ).lessThanEqual( 0.0 ).and( lightToPositionLength.sub( cameraNearLocal ).greaterThanEqual( 0.0 ) ), () => {
  31707. // dp = normalized distance from light to fragment position
  31708. const dp = lightToPositionLength.sub( cameraNearLocal ).div( cameraFarLocal.sub( cameraNearLocal ) ).toVar(); // need to clamp?
  31709. dp.addAssign( bias );
  31710. // bd3D = base direction 3D (direction from light to fragment)
  31711. const bd3D = lightToPosition.normalize();
  31712. // percentage-closer filtering using cube texture sampling
  31713. result.assign( filterFn( { depthTexture, bd3D, dp, shadow } ) );
  31714. } );
  31715. return result;
  31716. } );
  31717. /**
  31718. * Represents the shadow implementation for point light nodes.
  31719. *
  31720. * @augments ShadowNode
  31721. */
  31722. class PointShadowNode extends ShadowNode {
  31723. static get type() {
  31724. return 'PointShadowNode';
  31725. }
  31726. /**
  31727. * Constructs a new point shadow node.
  31728. *
  31729. * @param {PointLight} light - The shadow casting point light.
  31730. * @param {?PointLightShadow} [shadow=null] - An optional point light shadow.
  31731. */
  31732. constructor( light, shadow = null ) {
  31733. super( light, shadow );
  31734. }
  31735. /**
  31736. * Overwrites the default implementation to return point light shadow specific
  31737. * filtering functions.
  31738. *
  31739. * @param {number} type - The shadow type.
  31740. * @return {Function} The filtering function.
  31741. */
  31742. getShadowFilterFn( type ) {
  31743. return type === BasicShadowMap ? BasicPointShadowFilter : PointShadowFilter;
  31744. }
  31745. /**
  31746. * Overwrites the default implementation so the unaltered shadow position is used.
  31747. *
  31748. * @param {NodeBuilder} builder - A reference to the current node builder.
  31749. * @param {Node<vec3>} shadowPosition - A node representing the shadow position.
  31750. * @return {Node<vec3>} The shadow coordinates.
  31751. */
  31752. setupShadowCoord( builder, shadowPosition ) {
  31753. return shadowPosition;
  31754. }
  31755. /**
  31756. * Overwrites the default implementation to only use point light specific
  31757. * shadow filter functions.
  31758. *
  31759. * @param {NodeBuilder} builder - A reference to the current node builder.
  31760. * @param {Object} inputs - A configuration object that defines the shadow filtering.
  31761. * @param {Function} inputs.filterFn - This function defines the filtering type of the shadow map e.g. PCF.
  31762. * @param {DepthTexture} inputs.depthTexture - A reference to the shadow map's depth texture.
  31763. * @param {Node<vec3>} inputs.shadowCoord - Shadow coordinates which are used to sample from the shadow map.
  31764. * @param {LightShadow} inputs.shadow - The light shadow.
  31765. * @return {Node<float>} The result node of the shadow filtering.
  31766. */
  31767. setupShadowFilter( builder, { filterFn, depthTexture, shadowCoord, shadow } ) {
  31768. return pointShadowFilter( { filterFn, depthTexture, shadowCoord, shadow } );
  31769. }
  31770. /**
  31771. * Overwrites the default implementation to create a CubeRenderTarget with CubeDepthTexture.
  31772. *
  31773. * @param {LightShadow} shadow - The light shadow object.
  31774. * @param {NodeBuilder} builder - A reference to the current node builder.
  31775. * @return {Object} An object containing the shadow map and depth texture.
  31776. */
  31777. setupRenderTarget( shadow, builder ) {
  31778. const depthTexture = new CubeDepthTexture( shadow.mapSize.width );
  31779. depthTexture.name = 'PointShadowDepthTexture';
  31780. depthTexture.compareFunction = LessCompare;
  31781. const shadowMap = builder.createCubeRenderTarget( shadow.mapSize.width );
  31782. shadowMap.texture.name = 'PointShadowMap';
  31783. shadowMap.depthTexture = depthTexture;
  31784. return { shadowMap, depthTexture };
  31785. }
  31786. /**
  31787. * Overwrites the default implementation with point light specific
  31788. * rendering code.
  31789. *
  31790. * @param {NodeFrame} frame - A reference to the current node frame.
  31791. */
  31792. renderShadow( frame ) {
  31793. const { shadow, shadowMap, light } = this;
  31794. const { renderer, scene } = frame;
  31795. const camera = shadow.camera;
  31796. const shadowMatrix = shadow.matrix;
  31797. // Select cube directions/ups based on coordinate system
  31798. const isWebGPU = renderer.coordinateSystem === WebGPUCoordinateSystem;
  31799. const cubeDirections = isWebGPU ? _cubeDirectionsWebGPU : _cubeDirectionsWebGL;
  31800. const cubeUps = isWebGPU ? _cubeUpsWebGPU : _cubeUpsWebGL;
  31801. shadowMap.setSize( shadow.mapSize.width, shadow.mapSize.width );
  31802. //
  31803. const previousAutoClear = renderer.autoClear;
  31804. const previousClearColor = renderer.getClearColor( _clearColor$1 );
  31805. const previousClearAlpha = renderer.getClearAlpha();
  31806. renderer.autoClear = false;
  31807. renderer.setClearColor( shadow.clearColor, shadow.clearAlpha );
  31808. // Render each cube face
  31809. for ( let face = 0; face < 6; face ++ ) {
  31810. // Set render target to the specific cube face
  31811. renderer.setRenderTarget( shadowMap, face );
  31812. renderer.clear();
  31813. // Update shadow camera matrices for this face
  31814. const far = light.distance || camera.far;
  31815. if ( far !== camera.far ) {
  31816. camera.far = far;
  31817. camera.updateProjectionMatrix();
  31818. }
  31819. _lightPositionWorld.setFromMatrixPosition( light.matrixWorld );
  31820. camera.position.copy( _lightPositionWorld );
  31821. _lookTarget.copy( camera.position );
  31822. _lookTarget.add( cubeDirections[ face ] );
  31823. camera.up.copy( cubeUps[ face ] );
  31824. camera.lookAt( _lookTarget );
  31825. camera.updateMatrixWorld();
  31826. shadowMatrix.makeTranslation( - _lightPositionWorld.x, - _lightPositionWorld.y, - _lightPositionWorld.z );
  31827. _projScreenMatrix$1.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
  31828. shadow._frustum.setFromProjectionMatrix( _projScreenMatrix$1, camera.coordinateSystem, camera.reversedDepth );
  31829. //
  31830. const currentSceneName = scene.name;
  31831. scene.name = `Point Light Shadow [ ${ light.name || 'ID: ' + light.id } ] - Face ${ face + 1 }`;
  31832. renderer.render( scene, camera );
  31833. scene.name = currentSceneName;
  31834. }
  31835. //
  31836. renderer.autoClear = previousAutoClear;
  31837. renderer.setClearColor( previousClearColor, previousClearAlpha );
  31838. }
  31839. }
  31840. /**
  31841. * TSL function for creating an instance of `PointShadowNode`.
  31842. *
  31843. * @tsl
  31844. * @function
  31845. * @param {PointLight} light - The shadow casting point light.
  31846. * @param {?PointLightShadow} [shadow=null] - An optional point light shadow.
  31847. * @return {PointShadowNode} The created point shadow node.
  31848. */
  31849. const pointShadow = ( light, shadow ) => nodeObject( new PointShadowNode( light, shadow ) );
  31850. /**
  31851. * Base class for analytic light nodes.
  31852. *
  31853. * @augments LightingNode
  31854. */
  31855. class AnalyticLightNode extends LightingNode {
  31856. static get type() {
  31857. return 'AnalyticLightNode';
  31858. }
  31859. /**
  31860. * Constructs a new analytic light node.
  31861. *
  31862. * @param {?Light} [light=null] - The light source.
  31863. */
  31864. constructor( light = null ) {
  31865. super();
  31866. /**
  31867. * The light source.
  31868. *
  31869. * @type {?Light}
  31870. * @default null
  31871. */
  31872. this.light = light;
  31873. /**
  31874. * The light's color value.
  31875. *
  31876. * @type {Color}
  31877. */
  31878. this.color = new Color();
  31879. /**
  31880. * The light's color node. Points to `colorNode` of the light source, if set. Otherwise
  31881. * it creates a uniform node based on {@link AnalyticLightNode#color}.
  31882. *
  31883. * @type {Node}
  31884. */
  31885. this.colorNode = ( light && light.colorNode ) || uniform( this.color ).setGroup( renderGroup );
  31886. /**
  31887. * This property is used to retain a reference to the original value of {@link AnalyticLightNode#colorNode}.
  31888. * The final color node is represented by a different node when using shadows.
  31889. *
  31890. * @type {?Node}
  31891. * @default null
  31892. */
  31893. this.baseColorNode = null;
  31894. /**
  31895. * Represents the light's shadow.
  31896. *
  31897. * @type {?ShadowNode}
  31898. * @default null
  31899. */
  31900. this.shadowNode = null;
  31901. /**
  31902. * Represents the light's shadow color.
  31903. *
  31904. * @type {?Node}
  31905. * @default null
  31906. */
  31907. this.shadowColorNode = null;
  31908. /**
  31909. * This flag can be used for type testing.
  31910. *
  31911. * @type {boolean}
  31912. * @readonly
  31913. * @default true
  31914. */
  31915. this.isAnalyticLightNode = true;
  31916. /**
  31917. * Overwritten since analytic light nodes are updated
  31918. * once per frame.
  31919. *
  31920. * @type {string}
  31921. * @default 'frame'
  31922. */
  31923. this.updateType = NodeUpdateType.FRAME;
  31924. if ( light && light.shadow ) {
  31925. this._shadowDisposeListener = () => {
  31926. this.disposeShadow();
  31927. };
  31928. light.addEventListener( 'dispose', this._shadowDisposeListener );
  31929. }
  31930. }
  31931. dispose() {
  31932. if ( this._shadowDisposeListener ) {
  31933. this.light.removeEventListener( 'dispose', this._shadowDisposeListener );
  31934. }
  31935. super.dispose();
  31936. }
  31937. /**
  31938. * Frees internal resources related to shadows.
  31939. */
  31940. disposeShadow() {
  31941. if ( this.shadowNode !== null ) {
  31942. this.shadowNode.dispose();
  31943. this.shadowNode = null;
  31944. }
  31945. this.shadowColorNode = null;
  31946. if ( this.baseColorNode !== null ) {
  31947. this.colorNode = this.baseColorNode;
  31948. this.baseColorNode = null;
  31949. }
  31950. }
  31951. getHash() {
  31952. return this.light.uuid;
  31953. }
  31954. /**
  31955. * Returns a node representing a direction vector which points from the current
  31956. * position in view space to the light's position in view space.
  31957. *
  31958. * @param {NodeBuilder} builder - The builder object used for setting up the light.
  31959. * @return {Node<vec3>} The light vector node.
  31960. */
  31961. getLightVector( builder ) {
  31962. return lightViewPosition( this.light ).sub( builder.context.positionView || positionView );
  31963. }
  31964. /**
  31965. * Sets up the direct lighting for the analytic light node.
  31966. *
  31967. * @abstract
  31968. * @param {NodeBuilder} builder - The builder object used for setting up the light.
  31969. * @return {Object|undefined} The direct light data (color and direction).
  31970. */
  31971. setupDirect( /*builder*/ ) { }
  31972. /**
  31973. * Sets up the direct rect area lighting for the analytic light node.
  31974. *
  31975. * @abstract
  31976. * @param {NodeBuilder} builder - The builder object used for setting up the light.
  31977. * @return {Object|undefined} The direct rect area light data.
  31978. */
  31979. setupDirectRectArea( /*builder*/ ) { }
  31980. /**
  31981. * Setups the shadow node for this light. The method exists so concrete light classes
  31982. * can setup different types of shadow nodes.
  31983. *
  31984. * @return {ShadowNode} The created shadow node.
  31985. */
  31986. setupShadowNode() {
  31987. return shadow( this.light );
  31988. }
  31989. /**
  31990. * Setups the shadow for this light. This method is only executed if the light
  31991. * cast shadows and the current build object receives shadows. It incorporates
  31992. * shadows into the lighting computation.
  31993. *
  31994. * @param {NodeBuilder} builder - The current node builder.
  31995. */
  31996. setupShadow( builder ) {
  31997. const { renderer } = builder;
  31998. if ( renderer.shadowMap.enabled === false ) return;
  31999. let shadowColorNode = this.shadowColorNode;
  32000. if ( shadowColorNode === null ) {
  32001. const customShadowNode = this.light.shadow.shadowNode;
  32002. let shadowNode;
  32003. if ( customShadowNode !== undefined ) {
  32004. shadowNode = nodeObject( customShadowNode );
  32005. } else {
  32006. shadowNode = this.setupShadowNode();
  32007. }
  32008. this.shadowNode = shadowNode;
  32009. this.shadowColorNode = shadowColorNode = this.colorNode.mul( shadowNode );
  32010. this.baseColorNode = this.colorNode;
  32011. }
  32012. //
  32013. if ( builder.context.getShadow ) {
  32014. shadowColorNode = builder.context.getShadow( this, builder );
  32015. }
  32016. this.colorNode = shadowColorNode;
  32017. }
  32018. /**
  32019. * Unlike most other nodes, lighting nodes do not return a output node in {@link Node#setup}.
  32020. * The main purpose of lighting nodes is to configure the current {@link LightingModel} and/or
  32021. * invocate the respective interface methods.
  32022. *
  32023. * @param {NodeBuilder} builder - The current node builder.
  32024. */
  32025. setup( builder ) {
  32026. this.colorNode = this.baseColorNode || this.colorNode;
  32027. if ( this.light.castShadow ) {
  32028. if ( builder.object.receiveShadow ) {
  32029. this.setupShadow( builder );
  32030. }
  32031. } else if ( this.shadowNode !== null ) {
  32032. this.shadowNode.dispose();
  32033. this.shadowNode = null;
  32034. this.shadowColorNode = null;
  32035. }
  32036. const directLightData = this.setupDirect( builder );
  32037. const directRectAreaLightData = this.setupDirectRectArea( builder );
  32038. if ( directLightData ) {
  32039. builder.lightsNode.setupDirectLight( builder, this, directLightData );
  32040. }
  32041. if ( directRectAreaLightData ) {
  32042. builder.lightsNode.setupDirectRectAreaLight( builder, this, directRectAreaLightData );
  32043. }
  32044. }
  32045. /**
  32046. * The update method is used to update light uniforms per frame.
  32047. * Potentially overwritten in concrete light nodes to update light
  32048. * specific uniforms.
  32049. *
  32050. * @param {NodeFrame} frame - A reference to the current node frame.
  32051. */
  32052. update( /*frame*/ ) {
  32053. const { light } = this;
  32054. this.color.copy( light.color ).multiplyScalar( light.intensity );
  32055. }
  32056. }
  32057. /**
  32058. * Represents a `discard` shader operation in TSL.
  32059. *
  32060. * @method
  32061. * @param {Object} inputs - The input parameter object.
  32062. * @param {Node<float>} inputs.lightDistance - The distance of the light's position to the current fragment position.
  32063. * @param {Node<float>} inputs.cutoffDistance - The light's cutoff distance.
  32064. * @param {Node<float>} inputs.decayExponent - The light's decay exponent.
  32065. * @return {Node<float>} The distance falloff.
  32066. */
  32067. const getDistanceAttenuation = /*@__PURE__*/ Fn( ( { lightDistance, cutoffDistance, decayExponent } ) => {
  32068. // based upon Frostbite 3 Moving to Physically-based Rendering
  32069. // page 32, equation 26: E[window1]
  32070. // https://seblagarde.files.wordpress.com/2015/07/course_notes_moving_frostbite_to_pbr_v32.pdf
  32071. const distanceFalloff = lightDistance.pow( decayExponent ).max( 0.01 ).reciprocal();
  32072. return cutoffDistance.greaterThan( 0 ).select(
  32073. distanceFalloff.mul( lightDistance.div( cutoffDistance ).pow4().oneMinus().clamp().pow2() ),
  32074. distanceFalloff
  32075. );
  32076. } ); // validated
  32077. const directPointLight = ( { color, lightVector, cutoffDistance, decayExponent } ) => {
  32078. const lightDirection = lightVector.normalize();
  32079. const lightDistance = lightVector.length();
  32080. const attenuation = getDistanceAttenuation( {
  32081. lightDistance,
  32082. cutoffDistance,
  32083. decayExponent
  32084. } );
  32085. const lightColor = color.mul( attenuation );
  32086. return { lightDirection, lightColor };
  32087. };
  32088. /**
  32089. * Module for representing point lights as nodes.
  32090. *
  32091. * @augments AnalyticLightNode
  32092. */
  32093. class PointLightNode extends AnalyticLightNode {
  32094. static get type() {
  32095. return 'PointLightNode';
  32096. }
  32097. /**
  32098. * Constructs a new point light node.
  32099. *
  32100. * @param {?PointLight} [light=null] - The point light source.
  32101. */
  32102. constructor( light = null ) {
  32103. super( light );
  32104. /**
  32105. * Uniform node representing the cutoff distance.
  32106. *
  32107. * @type {UniformNode<float>}
  32108. */
  32109. this.cutoffDistanceNode = uniform( 0 ).setGroup( renderGroup );
  32110. /**
  32111. * Uniform node representing the decay exponent.
  32112. *
  32113. * @type {UniformNode<float>}
  32114. */
  32115. this.decayExponentNode = uniform( 2 ).setGroup( renderGroup );
  32116. }
  32117. /**
  32118. * Overwritten to updated point light specific uniforms.
  32119. *
  32120. * @param {NodeFrame} frame - A reference to the current node frame.
  32121. */
  32122. update( frame ) {
  32123. const { light } = this;
  32124. super.update( frame );
  32125. this.cutoffDistanceNode.value = light.distance;
  32126. this.decayExponentNode.value = light.decay;
  32127. }
  32128. /**
  32129. * Overwritten to setup point light specific shadow.
  32130. *
  32131. * @return {PointShadowNode}
  32132. */
  32133. setupShadowNode() {
  32134. return pointShadow( this.light );
  32135. }
  32136. setupDirect( builder ) {
  32137. return directPointLight( {
  32138. color: this.colorNode,
  32139. lightVector: this.getLightVector( builder ),
  32140. cutoffDistance: this.cutoffDistanceNode,
  32141. decayExponent: this.decayExponentNode
  32142. } );
  32143. }
  32144. }
  32145. /**
  32146. * Creates a 2x2 checkerboard pattern that can be used as procedural texture data.
  32147. *
  32148. * @tsl
  32149. * @function
  32150. * @param {Node<vec2>} coord - The uv coordinates.
  32151. * @return {Node<float>} The result data.
  32152. */
  32153. const checker = /*@__PURE__*/ Fn( ( [ coord = uv$1() ] ) => {
  32154. const uv = coord.mul( 2.0 );
  32155. const cx = uv.x.floor();
  32156. const cy = uv.y.floor();
  32157. const result = cx.add( cy ).mod( 2.0 );
  32158. return result.sign();
  32159. } );
  32160. /**
  32161. * Generates a circle based on the uv coordinates.
  32162. *
  32163. * @tsl
  32164. * @function
  32165. * @param {Node<vec2>} coord - The uv to generate the circle.
  32166. * @return {Node<float>} The circle shape.
  32167. */
  32168. const shapeCircle = Fn( ( [ coord = uv$1() ], { renderer, material } ) => {
  32169. const len2 = lengthSq( coord.mul( 2 ).sub( 1 ) );
  32170. let alpha;
  32171. if ( material.alphaToCoverage && renderer.currentSamples > 0 ) {
  32172. const dlen = float( len2.fwidth() ).toVar();
  32173. alpha = smoothstep( dlen.oneMinus(), dlen.add( 1 ), len2 ).oneMinus();
  32174. } else {
  32175. alpha = select( len2.greaterThan( 1.0 ), 0, 1 );
  32176. }
  32177. return alpha;
  32178. } );
  32179. // Three.js Transpiler
  32180. // https://raw.githubusercontent.com/AcademySoftwareFoundation/MaterialX/main/libraries/stdlib/genglsl/lib/mx_noise.glsl
  32181. const mx_select = /*@__PURE__*/ Fn( ( [ b_immutable, t_immutable, f_immutable ] ) => {
  32182. const f = float( f_immutable ).toVar();
  32183. const t = float( t_immutable ).toVar();
  32184. const b = bool( b_immutable ).toVar();
  32185. return select( b, t, f );
  32186. } ).setLayout( {
  32187. name: 'mx_select',
  32188. type: 'float',
  32189. inputs: [
  32190. { name: 'b', type: 'bool' },
  32191. { name: 't', type: 'float' },
  32192. { name: 'f', type: 'float' }
  32193. ]
  32194. } );
  32195. const mx_negate_if = /*@__PURE__*/ Fn( ( [ val_immutable, b_immutable ] ) => {
  32196. const b = bool( b_immutable ).toVar();
  32197. const val = float( val_immutable ).toVar();
  32198. return select( b, val.negate(), val );
  32199. } ).setLayout( {
  32200. name: 'mx_negate_if',
  32201. type: 'float',
  32202. inputs: [
  32203. { name: 'val', type: 'float' },
  32204. { name: 'b', type: 'bool' }
  32205. ]
  32206. } );
  32207. const mx_floor = /*@__PURE__*/ Fn( ( [ x_immutable ] ) => {
  32208. const x = float( x_immutable ).toVar();
  32209. return int( floor( x ) );
  32210. } ).setLayout( {
  32211. name: 'mx_floor',
  32212. type: 'int',
  32213. inputs: [
  32214. { name: 'x', type: 'float' }
  32215. ]
  32216. } );
  32217. const mx_floorfrac = /*@__PURE__*/ Fn( ( [ x_immutable, i ] ) => {
  32218. const x = float( x_immutable ).toVar();
  32219. i.assign( mx_floor( x ) );
  32220. return x.sub( float( i ) );
  32221. } );
  32222. const mx_bilerp_0 = /*@__PURE__*/ Fn( ( [ v0_immutable, v1_immutable, v2_immutable, v3_immutable, s_immutable, t_immutable ] ) => {
  32223. const t = float( t_immutable ).toVar();
  32224. const s = float( s_immutable ).toVar();
  32225. const v3 = float( v3_immutable ).toVar();
  32226. const v2 = float( v2_immutable ).toVar();
  32227. const v1 = float( v1_immutable ).toVar();
  32228. const v0 = float( v0_immutable ).toVar();
  32229. const s1 = float( sub( 1.0, s ) ).toVar();
  32230. return sub( 1.0, t ).mul( v0.mul( s1 ).add( v1.mul( s ) ) ).add( t.mul( v2.mul( s1 ).add( v3.mul( s ) ) ) );
  32231. } ).setLayout( {
  32232. name: 'mx_bilerp_0',
  32233. type: 'float',
  32234. inputs: [
  32235. { name: 'v0', type: 'float' },
  32236. { name: 'v1', type: 'float' },
  32237. { name: 'v2', type: 'float' },
  32238. { name: 'v3', type: 'float' },
  32239. { name: 's', type: 'float' },
  32240. { name: 't', type: 'float' }
  32241. ]
  32242. } );
  32243. const mx_bilerp_1 = /*@__PURE__*/ Fn( ( [ v0_immutable, v1_immutable, v2_immutable, v3_immutable, s_immutable, t_immutable ] ) => {
  32244. const t = float( t_immutable ).toVar();
  32245. const s = float( s_immutable ).toVar();
  32246. const v3 = vec3( v3_immutable ).toVar();
  32247. const v2 = vec3( v2_immutable ).toVar();
  32248. const v1 = vec3( v1_immutable ).toVar();
  32249. const v0 = vec3( v0_immutable ).toVar();
  32250. const s1 = float( sub( 1.0, s ) ).toVar();
  32251. return sub( 1.0, t ).mul( v0.mul( s1 ).add( v1.mul( s ) ) ).add( t.mul( v2.mul( s1 ).add( v3.mul( s ) ) ) );
  32252. } ).setLayout( {
  32253. name: 'mx_bilerp_1',
  32254. type: 'vec3',
  32255. inputs: [
  32256. { name: 'v0', type: 'vec3' },
  32257. { name: 'v1', type: 'vec3' },
  32258. { name: 'v2', type: 'vec3' },
  32259. { name: 'v3', type: 'vec3' },
  32260. { name: 's', type: 'float' },
  32261. { name: 't', type: 'float' }
  32262. ]
  32263. } );
  32264. const mx_bilerp = /*@__PURE__*/ overloadingFn( [ mx_bilerp_0, mx_bilerp_1 ] );
  32265. 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 ] ) => {
  32266. const r = float( r_immutable ).toVar();
  32267. const t = float( t_immutable ).toVar();
  32268. const s = float( s_immutable ).toVar();
  32269. const v7 = float( v7_immutable ).toVar();
  32270. const v6 = float( v6_immutable ).toVar();
  32271. const v5 = float( v5_immutable ).toVar();
  32272. const v4 = float( v4_immutable ).toVar();
  32273. const v3 = float( v3_immutable ).toVar();
  32274. const v2 = float( v2_immutable ).toVar();
  32275. const v1 = float( v1_immutable ).toVar();
  32276. const v0 = float( v0_immutable ).toVar();
  32277. const s1 = float( sub( 1.0, s ) ).toVar();
  32278. const t1 = float( sub( 1.0, t ) ).toVar();
  32279. const r1 = float( sub( 1.0, r ) ).toVar();
  32280. 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 ) ) ) ) ) );
  32281. } ).setLayout( {
  32282. name: 'mx_trilerp_0',
  32283. type: 'float',
  32284. inputs: [
  32285. { name: 'v0', type: 'float' },
  32286. { name: 'v1', type: 'float' },
  32287. { name: 'v2', type: 'float' },
  32288. { name: 'v3', type: 'float' },
  32289. { name: 'v4', type: 'float' },
  32290. { name: 'v5', type: 'float' },
  32291. { name: 'v6', type: 'float' },
  32292. { name: 'v7', type: 'float' },
  32293. { name: 's', type: 'float' },
  32294. { name: 't', type: 'float' },
  32295. { name: 'r', type: 'float' }
  32296. ]
  32297. } );
  32298. 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 ] ) => {
  32299. const r = float( r_immutable ).toVar();
  32300. const t = float( t_immutable ).toVar();
  32301. const s = float( s_immutable ).toVar();
  32302. const v7 = vec3( v7_immutable ).toVar();
  32303. const v6 = vec3( v6_immutable ).toVar();
  32304. const v5 = vec3( v5_immutable ).toVar();
  32305. const v4 = vec3( v4_immutable ).toVar();
  32306. const v3 = vec3( v3_immutable ).toVar();
  32307. const v2 = vec3( v2_immutable ).toVar();
  32308. const v1 = vec3( v1_immutable ).toVar();
  32309. const v0 = vec3( v0_immutable ).toVar();
  32310. const s1 = float( sub( 1.0, s ) ).toVar();
  32311. const t1 = float( sub( 1.0, t ) ).toVar();
  32312. const r1 = float( sub( 1.0, r ) ).toVar();
  32313. 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 ) ) ) ) ) );
  32314. } ).setLayout( {
  32315. name: 'mx_trilerp_1',
  32316. type: 'vec3',
  32317. inputs: [
  32318. { name: 'v0', type: 'vec3' },
  32319. { name: 'v1', type: 'vec3' },
  32320. { name: 'v2', type: 'vec3' },
  32321. { name: 'v3', type: 'vec3' },
  32322. { name: 'v4', type: 'vec3' },
  32323. { name: 'v5', type: 'vec3' },
  32324. { name: 'v6', type: 'vec3' },
  32325. { name: 'v7', type: 'vec3' },
  32326. { name: 's', type: 'float' },
  32327. { name: 't', type: 'float' },
  32328. { name: 'r', type: 'float' }
  32329. ]
  32330. } );
  32331. const mx_trilerp = /*@__PURE__*/ overloadingFn( [ mx_trilerp_0, mx_trilerp_1 ] );
  32332. const mx_gradient_float_0 = /*@__PURE__*/ Fn( ( [ hash_immutable, x_immutable, y_immutable ] ) => {
  32333. const y = float( y_immutable ).toVar();
  32334. const x = float( x_immutable ).toVar();
  32335. const hash = uint( hash_immutable ).toVar();
  32336. const h = uint( hash.bitAnd( uint( 7 ) ) ).toVar();
  32337. const u = float( mx_select( h.lessThan( uint( 4 ) ), x, y ) ).toVar();
  32338. const v = float( mul( 2.0, mx_select( h.lessThan( uint( 4 ) ), y, x ) ) ).toVar();
  32339. return mx_negate_if( u, bool( h.bitAnd( uint( 1 ) ) ) ).add( mx_negate_if( v, bool( h.bitAnd( uint( 2 ) ) ) ) );
  32340. } ).setLayout( {
  32341. name: 'mx_gradient_float_0',
  32342. type: 'float',
  32343. inputs: [
  32344. { name: 'hash', type: 'uint' },
  32345. { name: 'x', type: 'float' },
  32346. { name: 'y', type: 'float' }
  32347. ]
  32348. } );
  32349. const mx_gradient_float_1 = /*@__PURE__*/ Fn( ( [ hash_immutable, x_immutable, y_immutable, z_immutable ] ) => {
  32350. const z = float( z_immutable ).toVar();
  32351. const y = float( y_immutable ).toVar();
  32352. const x = float( x_immutable ).toVar();
  32353. const hash = uint( hash_immutable ).toVar();
  32354. const h = uint( hash.bitAnd( uint( 15 ) ) ).toVar();
  32355. const u = float( mx_select( h.lessThan( uint( 8 ) ), x, y ) ).toVar();
  32356. const v = float( mx_select( h.lessThan( uint( 4 ) ), y, mx_select( h.equal( uint( 12 ) ).or( h.equal( uint( 14 ) ) ), x, z ) ) ).toVar();
  32357. return mx_negate_if( u, bool( h.bitAnd( uint( 1 ) ) ) ).add( mx_negate_if( v, bool( h.bitAnd( uint( 2 ) ) ) ) );
  32358. } ).setLayout( {
  32359. name: 'mx_gradient_float_1',
  32360. type: 'float',
  32361. inputs: [
  32362. { name: 'hash', type: 'uint' },
  32363. { name: 'x', type: 'float' },
  32364. { name: 'y', type: 'float' },
  32365. { name: 'z', type: 'float' }
  32366. ]
  32367. } );
  32368. const mx_gradient_float = /*@__PURE__*/ overloadingFn( [ mx_gradient_float_0, mx_gradient_float_1 ] );
  32369. const mx_gradient_vec3_0 = /*@__PURE__*/ Fn( ( [ hash_immutable, x_immutable, y_immutable ] ) => {
  32370. const y = float( y_immutable ).toVar();
  32371. const x = float( x_immutable ).toVar();
  32372. const hash = uvec3( hash_immutable ).toVar();
  32373. return vec3( mx_gradient_float( hash.x, x, y ), mx_gradient_float( hash.y, x, y ), mx_gradient_float( hash.z, x, y ) );
  32374. } ).setLayout( {
  32375. name: 'mx_gradient_vec3_0',
  32376. type: 'vec3',
  32377. inputs: [
  32378. { name: 'hash', type: 'uvec3' },
  32379. { name: 'x', type: 'float' },
  32380. { name: 'y', type: 'float' }
  32381. ]
  32382. } );
  32383. const mx_gradient_vec3_1 = /*@__PURE__*/ Fn( ( [ hash_immutable, x_immutable, y_immutable, z_immutable ] ) => {
  32384. const z = float( z_immutable ).toVar();
  32385. const y = float( y_immutable ).toVar();
  32386. const x = float( x_immutable ).toVar();
  32387. const hash = uvec3( hash_immutable ).toVar();
  32388. 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 ) );
  32389. } ).setLayout( {
  32390. name: 'mx_gradient_vec3_1',
  32391. type: 'vec3',
  32392. inputs: [
  32393. { name: 'hash', type: 'uvec3' },
  32394. { name: 'x', type: 'float' },
  32395. { name: 'y', type: 'float' },
  32396. { name: 'z', type: 'float' }
  32397. ]
  32398. } );
  32399. const mx_gradient_vec3 = /*@__PURE__*/ overloadingFn( [ mx_gradient_vec3_0, mx_gradient_vec3_1 ] );
  32400. const mx_gradient_scale2d_0 = /*@__PURE__*/ Fn( ( [ v_immutable ] ) => {
  32401. const v = float( v_immutable ).toVar();
  32402. return mul( 0.6616, v );
  32403. } ).setLayout( {
  32404. name: 'mx_gradient_scale2d_0',
  32405. type: 'float',
  32406. inputs: [
  32407. { name: 'v', type: 'float' }
  32408. ]
  32409. } );
  32410. const mx_gradient_scale3d_0 = /*@__PURE__*/ Fn( ( [ v_immutable ] ) => {
  32411. const v = float( v_immutable ).toVar();
  32412. return mul( 0.9820, v );
  32413. } ).setLayout( {
  32414. name: 'mx_gradient_scale3d_0',
  32415. type: 'float',
  32416. inputs: [
  32417. { name: 'v', type: 'float' }
  32418. ]
  32419. } );
  32420. const mx_gradient_scale2d_1 = /*@__PURE__*/ Fn( ( [ v_immutable ] ) => {
  32421. const v = vec3( v_immutable ).toVar();
  32422. return mul( 0.6616, v );
  32423. } ).setLayout( {
  32424. name: 'mx_gradient_scale2d_1',
  32425. type: 'vec3',
  32426. inputs: [
  32427. { name: 'v', type: 'vec3' }
  32428. ]
  32429. } );
  32430. const mx_gradient_scale2d = /*@__PURE__*/ overloadingFn( [ mx_gradient_scale2d_0, mx_gradient_scale2d_1 ] );
  32431. const mx_gradient_scale3d_1 = /*@__PURE__*/ Fn( ( [ v_immutable ] ) => {
  32432. const v = vec3( v_immutable ).toVar();
  32433. return mul( 0.9820, v );
  32434. } ).setLayout( {
  32435. name: 'mx_gradient_scale3d_1',
  32436. type: 'vec3',
  32437. inputs: [
  32438. { name: 'v', type: 'vec3' }
  32439. ]
  32440. } );
  32441. const mx_gradient_scale3d = /*@__PURE__*/ overloadingFn( [ mx_gradient_scale3d_0, mx_gradient_scale3d_1 ] );
  32442. const mx_rotl32 = /*@__PURE__*/ Fn( ( [ x_immutable, k_immutable ] ) => {
  32443. const k = int( k_immutable ).toVar();
  32444. const x = uint( x_immutable ).toVar();
  32445. return x.shiftLeft( k ).bitOr( x.shiftRight( int( 32 ).sub( k ) ) );
  32446. } ).setLayout( {
  32447. name: 'mx_rotl32',
  32448. type: 'uint',
  32449. inputs: [
  32450. { name: 'x', type: 'uint' },
  32451. { name: 'k', type: 'int' }
  32452. ]
  32453. } );
  32454. const mx_bjmix = /*@__PURE__*/ Fn( ( [ a, b, c ] ) => {
  32455. a.subAssign( c );
  32456. a.bitXorAssign( mx_rotl32( c, int( 4 ) ) );
  32457. c.addAssign( b );
  32458. b.subAssign( a );
  32459. b.bitXorAssign( mx_rotl32( a, int( 6 ) ) );
  32460. a.addAssign( c );
  32461. c.subAssign( b );
  32462. c.bitXorAssign( mx_rotl32( b, int( 8 ) ) );
  32463. b.addAssign( a );
  32464. a.subAssign( c );
  32465. a.bitXorAssign( mx_rotl32( c, int( 16 ) ) );
  32466. c.addAssign( b );
  32467. b.subAssign( a );
  32468. b.bitXorAssign( mx_rotl32( a, int( 19 ) ) );
  32469. a.addAssign( c );
  32470. c.subAssign( b );
  32471. c.bitXorAssign( mx_rotl32( b, int( 4 ) ) );
  32472. b.addAssign( a );
  32473. } );
  32474. const mx_bjfinal = /*@__PURE__*/ Fn( ( [ a_immutable, b_immutable, c_immutable ] ) => {
  32475. const c = uint( c_immutable ).toVar();
  32476. const b = uint( b_immutable ).toVar();
  32477. const a = uint( a_immutable ).toVar();
  32478. c.bitXorAssign( b );
  32479. c.subAssign( mx_rotl32( b, int( 14 ) ) );
  32480. a.bitXorAssign( c );
  32481. a.subAssign( mx_rotl32( c, int( 11 ) ) );
  32482. b.bitXorAssign( a );
  32483. b.subAssign( mx_rotl32( a, int( 25 ) ) );
  32484. c.bitXorAssign( b );
  32485. c.subAssign( mx_rotl32( b, int( 16 ) ) );
  32486. a.bitXorAssign( c );
  32487. a.subAssign( mx_rotl32( c, int( 4 ) ) );
  32488. b.bitXorAssign( a );
  32489. b.subAssign( mx_rotl32( a, int( 14 ) ) );
  32490. c.bitXorAssign( b );
  32491. c.subAssign( mx_rotl32( b, int( 24 ) ) );
  32492. return c;
  32493. } ).setLayout( {
  32494. name: 'mx_bjfinal',
  32495. type: 'uint',
  32496. inputs: [
  32497. { name: 'a', type: 'uint' },
  32498. { name: 'b', type: 'uint' },
  32499. { name: 'c', type: 'uint' }
  32500. ]
  32501. } );
  32502. const mx_bits_to_01 = /*@__PURE__*/ Fn( ( [ bits_immutable ] ) => {
  32503. const bits = uint( bits_immutable ).toVar();
  32504. return float( bits ).div( float( uint( int( 0xffffffff ) ) ) );
  32505. } ).setLayout( {
  32506. name: 'mx_bits_to_01',
  32507. type: 'float',
  32508. inputs: [
  32509. { name: 'bits', type: 'uint' }
  32510. ]
  32511. } );
  32512. const mx_fade = /*@__PURE__*/ Fn( ( [ t_immutable ] ) => {
  32513. const t = float( t_immutable ).toVar();
  32514. return t.mul( t ).mul( t ).mul( t.mul( t.mul( 6.0 ).sub( 15.0 ) ).add( 10.0 ) );
  32515. } ).setLayout( {
  32516. name: 'mx_fade',
  32517. type: 'float',
  32518. inputs: [
  32519. { name: 't', type: 'float' }
  32520. ]
  32521. } );
  32522. const mx_hash_int_0 = /*@__PURE__*/ Fn( ( [ x_immutable ] ) => {
  32523. const x = int( x_immutable ).toVar();
  32524. const len = uint( uint( 1 ) ).toVar();
  32525. const seed = uint( uint( int( 0xdeadbeef ) ).add( len.shiftLeft( uint( 2 ) ) ).add( uint( 13 ) ) ).toVar();
  32526. return mx_bjfinal( seed.add( uint( x ) ), seed, seed );
  32527. } ).setLayout( {
  32528. name: 'mx_hash_int_0',
  32529. type: 'uint',
  32530. inputs: [
  32531. { name: 'x', type: 'int' }
  32532. ]
  32533. } );
  32534. const mx_hash_int_1 = /*@__PURE__*/ Fn( ( [ x_immutable, y_immutable ] ) => {
  32535. const y = int( y_immutable ).toVar();
  32536. const x = int( x_immutable ).toVar();
  32537. const len = uint( uint( 2 ) ).toVar();
  32538. const a = uint().toVar(), b = uint().toVar(), c = uint().toVar();
  32539. a.assign( b.assign( c.assign( uint( int( 0xdeadbeef ) ).add( len.shiftLeft( uint( 2 ) ) ).add( uint( 13 ) ) ) ) );
  32540. a.addAssign( uint( x ) );
  32541. b.addAssign( uint( y ) );
  32542. return mx_bjfinal( a, b, c );
  32543. } ).setLayout( {
  32544. name: 'mx_hash_int_1',
  32545. type: 'uint',
  32546. inputs: [
  32547. { name: 'x', type: 'int' },
  32548. { name: 'y', type: 'int' }
  32549. ]
  32550. } );
  32551. const mx_hash_int_2 = /*@__PURE__*/ Fn( ( [ x_immutable, y_immutable, z_immutable ] ) => {
  32552. const z = int( z_immutable ).toVar();
  32553. const y = int( y_immutable ).toVar();
  32554. const x = int( x_immutable ).toVar();
  32555. const len = uint( uint( 3 ) ).toVar();
  32556. const a = uint().toVar(), b = uint().toVar(), c = uint().toVar();
  32557. a.assign( b.assign( c.assign( uint( int( 0xdeadbeef ) ).add( len.shiftLeft( uint( 2 ) ) ).add( uint( 13 ) ) ) ) );
  32558. a.addAssign( uint( x ) );
  32559. b.addAssign( uint( y ) );
  32560. c.addAssign( uint( z ) );
  32561. return mx_bjfinal( a, b, c );
  32562. } ).setLayout( {
  32563. name: 'mx_hash_int_2',
  32564. type: 'uint',
  32565. inputs: [
  32566. { name: 'x', type: 'int' },
  32567. { name: 'y', type: 'int' },
  32568. { name: 'z', type: 'int' }
  32569. ]
  32570. } );
  32571. const mx_hash_int_3 = /*@__PURE__*/ Fn( ( [ x_immutable, y_immutable, z_immutable, xx_immutable ] ) => {
  32572. const xx = int( xx_immutable ).toVar();
  32573. const z = int( z_immutable ).toVar();
  32574. const y = int( y_immutable ).toVar();
  32575. const x = int( x_immutable ).toVar();
  32576. const len = uint( uint( 4 ) ).toVar();
  32577. const a = uint().toVar(), b = uint().toVar(), c = uint().toVar();
  32578. a.assign( b.assign( c.assign( uint( int( 0xdeadbeef ) ).add( len.shiftLeft( uint( 2 ) ) ).add( uint( 13 ) ) ) ) );
  32579. a.addAssign( uint( x ) );
  32580. b.addAssign( uint( y ) );
  32581. c.addAssign( uint( z ) );
  32582. mx_bjmix( a, b, c );
  32583. a.addAssign( uint( xx ) );
  32584. return mx_bjfinal( a, b, c );
  32585. } ).setLayout( {
  32586. name: 'mx_hash_int_3',
  32587. type: 'uint',
  32588. inputs: [
  32589. { name: 'x', type: 'int' },
  32590. { name: 'y', type: 'int' },
  32591. { name: 'z', type: 'int' },
  32592. { name: 'xx', type: 'int' }
  32593. ]
  32594. } );
  32595. const mx_hash_int_4 = /*@__PURE__*/ Fn( ( [ x_immutable, y_immutable, z_immutable, xx_immutable, yy_immutable ] ) => {
  32596. const yy = int( yy_immutable ).toVar();
  32597. const xx = int( xx_immutable ).toVar();
  32598. const z = int( z_immutable ).toVar();
  32599. const y = int( y_immutable ).toVar();
  32600. const x = int( x_immutable ).toVar();
  32601. const len = uint( uint( 5 ) ).toVar();
  32602. const a = uint().toVar(), b = uint().toVar(), c = uint().toVar();
  32603. a.assign( b.assign( c.assign( uint( int( 0xdeadbeef ) ).add( len.shiftLeft( uint( 2 ) ) ).add( uint( 13 ) ) ) ) );
  32604. a.addAssign( uint( x ) );
  32605. b.addAssign( uint( y ) );
  32606. c.addAssign( uint( z ) );
  32607. mx_bjmix( a, b, c );
  32608. a.addAssign( uint( xx ) );
  32609. b.addAssign( uint( yy ) );
  32610. return mx_bjfinal( a, b, c );
  32611. } ).setLayout( {
  32612. name: 'mx_hash_int_4',
  32613. type: 'uint',
  32614. inputs: [
  32615. { name: 'x', type: 'int' },
  32616. { name: 'y', type: 'int' },
  32617. { name: 'z', type: 'int' },
  32618. { name: 'xx', type: 'int' },
  32619. { name: 'yy', type: 'int' }
  32620. ]
  32621. } );
  32622. 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 ] );
  32623. const mx_hash_vec3_0 = /*@__PURE__*/ Fn( ( [ x_immutable, y_immutable ] ) => {
  32624. const y = int( y_immutable ).toVar();
  32625. const x = int( x_immutable ).toVar();
  32626. const h = uint( mx_hash_int( x, y ) ).toVar();
  32627. const result = uvec3().toVar();
  32628. result.x.assign( h.bitAnd( int( 0xFF ) ) );
  32629. result.y.assign( h.shiftRight( int( 8 ) ).bitAnd( int( 0xFF ) ) );
  32630. result.z.assign( h.shiftRight( int( 16 ) ).bitAnd( int( 0xFF ) ) );
  32631. return result;
  32632. } ).setLayout( {
  32633. name: 'mx_hash_vec3_0',
  32634. type: 'uvec3',
  32635. inputs: [
  32636. { name: 'x', type: 'int' },
  32637. { name: 'y', type: 'int' }
  32638. ]
  32639. } );
  32640. const mx_hash_vec3_1 = /*@__PURE__*/ Fn( ( [ x_immutable, y_immutable, z_immutable ] ) => {
  32641. const z = int( z_immutable ).toVar();
  32642. const y = int( y_immutable ).toVar();
  32643. const x = int( x_immutable ).toVar();
  32644. const h = uint( mx_hash_int( x, y, z ) ).toVar();
  32645. const result = uvec3().toVar();
  32646. result.x.assign( h.bitAnd( int( 0xFF ) ) );
  32647. result.y.assign( h.shiftRight( int( 8 ) ).bitAnd( int( 0xFF ) ) );
  32648. result.z.assign( h.shiftRight( int( 16 ) ).bitAnd( int( 0xFF ) ) );
  32649. return result;
  32650. } ).setLayout( {
  32651. name: 'mx_hash_vec3_1',
  32652. type: 'uvec3',
  32653. inputs: [
  32654. { name: 'x', type: 'int' },
  32655. { name: 'y', type: 'int' },
  32656. { name: 'z', type: 'int' }
  32657. ]
  32658. } );
  32659. const mx_hash_vec3 = /*@__PURE__*/ overloadingFn( [ mx_hash_vec3_0, mx_hash_vec3_1 ] );
  32660. const mx_perlin_noise_float_0 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  32661. const p = vec2( p_immutable ).toVar();
  32662. const X = int().toVar(), Y = int().toVar();
  32663. const fx = float( mx_floorfrac( p.x, X ) ).toVar();
  32664. const fy = float( mx_floorfrac( p.y, Y ) ).toVar();
  32665. const u = float( mx_fade( fx ) ).toVar();
  32666. const v = float( mx_fade( fy ) ).toVar();
  32667. 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();
  32668. return mx_gradient_scale2d( result );
  32669. } ).setLayout( {
  32670. name: 'mx_perlin_noise_float_0',
  32671. type: 'float',
  32672. inputs: [
  32673. { name: 'p', type: 'vec2' }
  32674. ]
  32675. } );
  32676. const mx_perlin_noise_float_1 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  32677. const p = vec3( p_immutable ).toVar();
  32678. const X = int().toVar(), Y = int().toVar(), Z = int().toVar();
  32679. const fx = float( mx_floorfrac( p.x, X ) ).toVar();
  32680. const fy = float( mx_floorfrac( p.y, Y ) ).toVar();
  32681. const fz = float( mx_floorfrac( p.z, Z ) ).toVar();
  32682. const u = float( mx_fade( fx ) ).toVar();
  32683. const v = float( mx_fade( fy ) ).toVar();
  32684. const w = float( mx_fade( fz ) ).toVar();
  32685. 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();
  32686. return mx_gradient_scale3d( result );
  32687. } ).setLayout( {
  32688. name: 'mx_perlin_noise_float_1',
  32689. type: 'float',
  32690. inputs: [
  32691. { name: 'p', type: 'vec3' }
  32692. ]
  32693. } );
  32694. const mx_perlin_noise_float = /*@__PURE__*/ overloadingFn( [ mx_perlin_noise_float_0, mx_perlin_noise_float_1 ] );
  32695. const mx_perlin_noise_vec3_0 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  32696. const p = vec2( p_immutable ).toVar();
  32697. const X = int().toVar(), Y = int().toVar();
  32698. const fx = float( mx_floorfrac( p.x, X ) ).toVar();
  32699. const fy = float( mx_floorfrac( p.y, Y ) ).toVar();
  32700. const u = float( mx_fade( fx ) ).toVar();
  32701. const v = float( mx_fade( fy ) ).toVar();
  32702. 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();
  32703. return mx_gradient_scale2d( result );
  32704. } ).setLayout( {
  32705. name: 'mx_perlin_noise_vec3_0',
  32706. type: 'vec3',
  32707. inputs: [
  32708. { name: 'p', type: 'vec2' }
  32709. ]
  32710. } );
  32711. const mx_perlin_noise_vec3_1 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  32712. const p = vec3( p_immutable ).toVar();
  32713. const X = int().toVar(), Y = int().toVar(), Z = int().toVar();
  32714. const fx = float( mx_floorfrac( p.x, X ) ).toVar();
  32715. const fy = float( mx_floorfrac( p.y, Y ) ).toVar();
  32716. const fz = float( mx_floorfrac( p.z, Z ) ).toVar();
  32717. const u = float( mx_fade( fx ) ).toVar();
  32718. const v = float( mx_fade( fy ) ).toVar();
  32719. const w = float( mx_fade( fz ) ).toVar();
  32720. 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();
  32721. return mx_gradient_scale3d( result );
  32722. } ).setLayout( {
  32723. name: 'mx_perlin_noise_vec3_1',
  32724. type: 'vec3',
  32725. inputs: [
  32726. { name: 'p', type: 'vec3' }
  32727. ]
  32728. } );
  32729. const mx_perlin_noise_vec3 = /*@__PURE__*/ overloadingFn( [ mx_perlin_noise_vec3_0, mx_perlin_noise_vec3_1 ] );
  32730. const mx_cell_noise_float_0 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  32731. const p = float( p_immutable ).toVar();
  32732. const ix = int( mx_floor( p ) ).toVar();
  32733. return mx_bits_to_01( mx_hash_int( ix ) );
  32734. } ).setLayout( {
  32735. name: 'mx_cell_noise_float_0',
  32736. type: 'float',
  32737. inputs: [
  32738. { name: 'p', type: 'float' }
  32739. ]
  32740. } );
  32741. const mx_cell_noise_float_1 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  32742. const p = vec2( p_immutable ).toVar();
  32743. const ix = int( mx_floor( p.x ) ).toVar();
  32744. const iy = int( mx_floor( p.y ) ).toVar();
  32745. return mx_bits_to_01( mx_hash_int( ix, iy ) );
  32746. } ).setLayout( {
  32747. name: 'mx_cell_noise_float_1',
  32748. type: 'float',
  32749. inputs: [
  32750. { name: 'p', type: 'vec2' }
  32751. ]
  32752. } );
  32753. const mx_cell_noise_float_2 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  32754. const p = vec3( p_immutable ).toVar();
  32755. const ix = int( mx_floor( p.x ) ).toVar();
  32756. const iy = int( mx_floor( p.y ) ).toVar();
  32757. const iz = int( mx_floor( p.z ) ).toVar();
  32758. return mx_bits_to_01( mx_hash_int( ix, iy, iz ) );
  32759. } ).setLayout( {
  32760. name: 'mx_cell_noise_float_2',
  32761. type: 'float',
  32762. inputs: [
  32763. { name: 'p', type: 'vec3' }
  32764. ]
  32765. } );
  32766. const mx_cell_noise_float_3 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  32767. const p = vec4( p_immutable ).toVar();
  32768. const ix = int( mx_floor( p.x ) ).toVar();
  32769. const iy = int( mx_floor( p.y ) ).toVar();
  32770. const iz = int( mx_floor( p.z ) ).toVar();
  32771. const iw = int( mx_floor( p.w ) ).toVar();
  32772. return mx_bits_to_01( mx_hash_int( ix, iy, iz, iw ) );
  32773. } ).setLayout( {
  32774. name: 'mx_cell_noise_float_3',
  32775. type: 'float',
  32776. inputs: [
  32777. { name: 'p', type: 'vec4' }
  32778. ]
  32779. } );
  32780. 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 ] );
  32781. const mx_cell_noise_vec3_0 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  32782. const p = float( p_immutable ).toVar();
  32783. const ix = int( mx_floor( p ) ).toVar();
  32784. 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 ) ) ) );
  32785. } ).setLayout( {
  32786. name: 'mx_cell_noise_vec3_0',
  32787. type: 'vec3',
  32788. inputs: [
  32789. { name: 'p', type: 'float' }
  32790. ]
  32791. } );
  32792. const mx_cell_noise_vec3_1 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  32793. const p = vec2( p_immutable ).toVar();
  32794. const ix = int( mx_floor( p.x ) ).toVar();
  32795. const iy = int( mx_floor( p.y ) ).toVar();
  32796. 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 ) ) ) );
  32797. } ).setLayout( {
  32798. name: 'mx_cell_noise_vec3_1',
  32799. type: 'vec3',
  32800. inputs: [
  32801. { name: 'p', type: 'vec2' }
  32802. ]
  32803. } );
  32804. const mx_cell_noise_vec3_2 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  32805. const p = vec3( p_immutable ).toVar();
  32806. const ix = int( mx_floor( p.x ) ).toVar();
  32807. const iy = int( mx_floor( p.y ) ).toVar();
  32808. const iz = int( mx_floor( p.z ) ).toVar();
  32809. 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 ) ) ) );
  32810. } ).setLayout( {
  32811. name: 'mx_cell_noise_vec3_2',
  32812. type: 'vec3',
  32813. inputs: [
  32814. { name: 'p', type: 'vec3' }
  32815. ]
  32816. } );
  32817. const mx_cell_noise_vec3_3 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  32818. const p = vec4( p_immutable ).toVar();
  32819. const ix = int( mx_floor( p.x ) ).toVar();
  32820. const iy = int( mx_floor( p.y ) ).toVar();
  32821. const iz = int( mx_floor( p.z ) ).toVar();
  32822. const iw = int( mx_floor( p.w ) ).toVar();
  32823. 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 ) ) ) );
  32824. } ).setLayout( {
  32825. name: 'mx_cell_noise_vec3_3',
  32826. type: 'vec3',
  32827. inputs: [
  32828. { name: 'p', type: 'vec4' }
  32829. ]
  32830. } );
  32831. 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 ] );
  32832. const mx_fractal_noise_float$1 = /*@__PURE__*/ Fn( ( [ p_immutable, octaves_immutable, lacunarity_immutable, diminish_immutable ] ) => {
  32833. const diminish = float( diminish_immutable ).toVar();
  32834. const lacunarity = float( lacunarity_immutable ).toVar();
  32835. const octaves = int( octaves_immutable ).toVar();
  32836. const p = vec3( p_immutable ).toVar();
  32837. const result = float( 0.0 ).toVar();
  32838. const amplitude = float( 1.0 ).toVar();
  32839. Loop( octaves, () => {
  32840. result.addAssign( amplitude.mul( mx_perlin_noise_float( p ) ) );
  32841. amplitude.mulAssign( diminish );
  32842. p.mulAssign( lacunarity );
  32843. } );
  32844. return result;
  32845. } ).setLayout( {
  32846. name: 'mx_fractal_noise_float',
  32847. type: 'float',
  32848. inputs: [
  32849. { name: 'p', type: 'vec3' },
  32850. { name: 'octaves', type: 'int' },
  32851. { name: 'lacunarity', type: 'float' },
  32852. { name: 'diminish', type: 'float' }
  32853. ]
  32854. } );
  32855. const mx_fractal_noise_vec3$1 = /*@__PURE__*/ Fn( ( [ p_immutable, octaves_immutable, lacunarity_immutable, diminish_immutable ] ) => {
  32856. const diminish = float( diminish_immutable ).toVar();
  32857. const lacunarity = float( lacunarity_immutable ).toVar();
  32858. const octaves = int( octaves_immutable ).toVar();
  32859. const p = vec3( p_immutable ).toVar();
  32860. const result = vec3( 0.0 ).toVar();
  32861. const amplitude = float( 1.0 ).toVar();
  32862. Loop( octaves, () => {
  32863. result.addAssign( amplitude.mul( mx_perlin_noise_vec3( p ) ) );
  32864. amplitude.mulAssign( diminish );
  32865. p.mulAssign( lacunarity );
  32866. } );
  32867. return result;
  32868. } ).setLayout( {
  32869. name: 'mx_fractal_noise_vec3',
  32870. type: 'vec3',
  32871. inputs: [
  32872. { name: 'p', type: 'vec3' },
  32873. { name: 'octaves', type: 'int' },
  32874. { name: 'lacunarity', type: 'float' },
  32875. { name: 'diminish', type: 'float' }
  32876. ]
  32877. } );
  32878. const mx_fractal_noise_vec2$1 = /*@__PURE__*/ Fn( ( [ p_immutable, octaves_immutable, lacunarity_immutable, diminish_immutable ] ) => {
  32879. const diminish = float( diminish_immutable ).toVar();
  32880. const lacunarity = float( lacunarity_immutable ).toVar();
  32881. const octaves = int( octaves_immutable ).toVar();
  32882. const p = vec3( p_immutable ).toVar();
  32883. 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 ) );
  32884. } ).setLayout( {
  32885. name: 'mx_fractal_noise_vec2',
  32886. type: 'vec2',
  32887. inputs: [
  32888. { name: 'p', type: 'vec3' },
  32889. { name: 'octaves', type: 'int' },
  32890. { name: 'lacunarity', type: 'float' },
  32891. { name: 'diminish', type: 'float' }
  32892. ]
  32893. } );
  32894. const mx_fractal_noise_vec4$1 = /*@__PURE__*/ Fn( ( [ p_immutable, octaves_immutable, lacunarity_immutable, diminish_immutable ] ) => {
  32895. const diminish = float( diminish_immutable ).toVar();
  32896. const lacunarity = float( lacunarity_immutable ).toVar();
  32897. const octaves = int( octaves_immutable ).toVar();
  32898. const p = vec3( p_immutable ).toVar();
  32899. const c = vec3( mx_fractal_noise_vec3$1( p, octaves, lacunarity, diminish ) ).toVar();
  32900. const f = float( mx_fractal_noise_float$1( p.add( vec3( int( 19 ), int( 193 ), int( 17 ) ) ), octaves, lacunarity, diminish ) ).toVar();
  32901. return vec4( c, f );
  32902. } ).setLayout( {
  32903. name: 'mx_fractal_noise_vec4',
  32904. type: 'vec4',
  32905. inputs: [
  32906. { name: 'p', type: 'vec3' },
  32907. { name: 'octaves', type: 'int' },
  32908. { name: 'lacunarity', type: 'float' },
  32909. { name: 'diminish', type: 'float' }
  32910. ]
  32911. } );
  32912. const mx_worley_distance_0 = /*@__PURE__*/ Fn( ( [ p_immutable, x_immutable, y_immutable, xoff_immutable, yoff_immutable, jitter_immutable, metric_immutable ] ) => {
  32913. const metric = int( metric_immutable ).toVar();
  32914. const jitter = float( jitter_immutable ).toVar();
  32915. const yoff = int( yoff_immutable ).toVar();
  32916. const xoff = int( xoff_immutable ).toVar();
  32917. const y = int( y_immutable ).toVar();
  32918. const x = int( x_immutable ).toVar();
  32919. const p = vec2( p_immutable ).toVar();
  32920. const tmp = vec3( mx_cell_noise_vec3( vec2( x.add( xoff ), y.add( yoff ) ) ) ).toVar();
  32921. const off = vec2( tmp.x, tmp.y ).toVar();
  32922. off.subAssign( 0.5 );
  32923. off.mulAssign( jitter );
  32924. off.addAssign( 0.5 );
  32925. const cellpos = vec2( vec2( float( x ), float( y ) ).add( off ) ).toVar();
  32926. const diff = vec2( cellpos.sub( p ) ).toVar();
  32927. If( metric.equal( int( 2 ) ), () => {
  32928. return abs( diff.x ).add( abs( diff.y ) );
  32929. } );
  32930. If( metric.equal( int( 3 ) ), () => {
  32931. return max$1( abs( diff.x ), abs( diff.y ) );
  32932. } );
  32933. return dot( diff, diff );
  32934. } ).setLayout( {
  32935. name: 'mx_worley_distance_0',
  32936. type: 'float',
  32937. inputs: [
  32938. { name: 'p', type: 'vec2' },
  32939. { name: 'x', type: 'int' },
  32940. { name: 'y', type: 'int' },
  32941. { name: 'xoff', type: 'int' },
  32942. { name: 'yoff', type: 'int' },
  32943. { name: 'jitter', type: 'float' },
  32944. { name: 'metric', type: 'int' }
  32945. ]
  32946. } );
  32947. 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 ] ) => {
  32948. const metric = int( metric_immutable ).toVar();
  32949. const jitter = float( jitter_immutable ).toVar();
  32950. const zoff = int( zoff_immutable ).toVar();
  32951. const yoff = int( yoff_immutable ).toVar();
  32952. const xoff = int( xoff_immutable ).toVar();
  32953. const z = int( z_immutable ).toVar();
  32954. const y = int( y_immutable ).toVar();
  32955. const x = int( x_immutable ).toVar();
  32956. const p = vec3( p_immutable ).toVar();
  32957. const off = vec3( mx_cell_noise_vec3( vec3( x.add( xoff ), y.add( yoff ), z.add( zoff ) ) ) ).toVar();
  32958. off.subAssign( 0.5 );
  32959. off.mulAssign( jitter );
  32960. off.addAssign( 0.5 );
  32961. const cellpos = vec3( vec3( float( x ), float( y ), float( z ) ).add( off ) ).toVar();
  32962. const diff = vec3( cellpos.sub( p ) ).toVar();
  32963. If( metric.equal( int( 2 ) ), () => {
  32964. return abs( diff.x ).add( abs( diff.y ) ).add( abs( diff.z ) );
  32965. } );
  32966. If( metric.equal( int( 3 ) ), () => {
  32967. return max$1( abs( diff.x ), abs( diff.y ), abs( diff.z ) );
  32968. } );
  32969. return dot( diff, diff );
  32970. } ).setLayout( {
  32971. name: 'mx_worley_distance_1',
  32972. type: 'float',
  32973. inputs: [
  32974. { name: 'p', type: 'vec3' },
  32975. { name: 'x', type: 'int' },
  32976. { name: 'y', type: 'int' },
  32977. { name: 'z', type: 'int' },
  32978. { name: 'xoff', type: 'int' },
  32979. { name: 'yoff', type: 'int' },
  32980. { name: 'zoff', type: 'int' },
  32981. { name: 'jitter', type: 'float' },
  32982. { name: 'metric', type: 'int' }
  32983. ]
  32984. } );
  32985. const mx_worley_distance = /*@__PURE__*/ overloadingFn( [ mx_worley_distance_0, mx_worley_distance_1 ] );
  32986. const mx_worley_noise_float_0 = /*@__PURE__*/ Fn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  32987. const metric = int( metric_immutable ).toVar();
  32988. const jitter = float( jitter_immutable ).toVar();
  32989. const p = vec2( p_immutable ).toVar();
  32990. const X = int().toVar(), Y = int().toVar();
  32991. const localpos = vec2( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ) ).toVar();
  32992. const sqdist = float( 1e6 ).toVar();
  32993. Loop( { start: -1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  32994. Loop( { start: -1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  32995. const dist = float( mx_worley_distance( localpos, x, y, X, Y, jitter, metric ) ).toVar();
  32996. sqdist.assign( min$1( sqdist, dist ) );
  32997. } );
  32998. } );
  32999. If( metric.equal( int( 0 ) ), () => {
  33000. sqdist.assign( sqrt( sqdist ) );
  33001. } );
  33002. return sqdist;
  33003. } ).setLayout( {
  33004. name: 'mx_worley_noise_float_0',
  33005. type: 'float',
  33006. inputs: [
  33007. { name: 'p', type: 'vec2' },
  33008. { name: 'jitter', type: 'float' },
  33009. { name: 'metric', type: 'int' }
  33010. ]
  33011. } );
  33012. const mx_worley_noise_vec2_0 = /*@__PURE__*/ Fn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  33013. const metric = int( metric_immutable ).toVar();
  33014. const jitter = float( jitter_immutable ).toVar();
  33015. const p = vec2( p_immutable ).toVar();
  33016. const X = int().toVar(), Y = int().toVar();
  33017. const localpos = vec2( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ) ).toVar();
  33018. const sqdist = vec2( 1e6, 1e6 ).toVar();
  33019. Loop( { start: -1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  33020. Loop( { start: -1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  33021. const dist = float( mx_worley_distance( localpos, x, y, X, Y, jitter, metric ) ).toVar();
  33022. If( dist.lessThan( sqdist.x ), () => {
  33023. sqdist.y.assign( sqdist.x );
  33024. sqdist.x.assign( dist );
  33025. } ).ElseIf( dist.lessThan( sqdist.y ), () => {
  33026. sqdist.y.assign( dist );
  33027. } );
  33028. } );
  33029. } );
  33030. If( metric.equal( int( 0 ) ), () => {
  33031. sqdist.assign( sqrt( sqdist ) );
  33032. } );
  33033. return sqdist;
  33034. } ).setLayout( {
  33035. name: 'mx_worley_noise_vec2_0',
  33036. type: 'vec2',
  33037. inputs: [
  33038. { name: 'p', type: 'vec2' },
  33039. { name: 'jitter', type: 'float' },
  33040. { name: 'metric', type: 'int' }
  33041. ]
  33042. } );
  33043. const mx_worley_noise_vec3_0 = /*@__PURE__*/ Fn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  33044. const metric = int( metric_immutable ).toVar();
  33045. const jitter = float( jitter_immutable ).toVar();
  33046. const p = vec2( p_immutable ).toVar();
  33047. const X = int().toVar(), Y = int().toVar();
  33048. const localpos = vec2( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ) ).toVar();
  33049. const sqdist = vec3( 1e6, 1e6, 1e6 ).toVar();
  33050. Loop( { start: -1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  33051. Loop( { start: -1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  33052. const dist = float( mx_worley_distance( localpos, x, y, X, Y, jitter, metric ) ).toVar();
  33053. If( dist.lessThan( sqdist.x ), () => {
  33054. sqdist.z.assign( sqdist.y );
  33055. sqdist.y.assign( sqdist.x );
  33056. sqdist.x.assign( dist );
  33057. } ).ElseIf( dist.lessThan( sqdist.y ), () => {
  33058. sqdist.z.assign( sqdist.y );
  33059. sqdist.y.assign( dist );
  33060. } ).ElseIf( dist.lessThan( sqdist.z ), () => {
  33061. sqdist.z.assign( dist );
  33062. } );
  33063. } );
  33064. } );
  33065. If( metric.equal( int( 0 ) ), () => {
  33066. sqdist.assign( sqrt( sqdist ) );
  33067. } );
  33068. return sqdist;
  33069. } ).setLayout( {
  33070. name: 'mx_worley_noise_vec3_0',
  33071. type: 'vec3',
  33072. inputs: [
  33073. { name: 'p', type: 'vec2' },
  33074. { name: 'jitter', type: 'float' },
  33075. { name: 'metric', type: 'int' }
  33076. ]
  33077. } );
  33078. const mx_worley_noise_float_1 = /*@__PURE__*/ Fn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  33079. const metric = int( metric_immutable ).toVar();
  33080. const jitter = float( jitter_immutable ).toVar();
  33081. const p = vec3( p_immutable ).toVar();
  33082. const X = int().toVar(), Y = int().toVar(), Z = int().toVar();
  33083. const localpos = vec3( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ), mx_floorfrac( p.z, Z ) ).toVar();
  33084. const sqdist = float( 1e6 ).toVar();
  33085. Loop( { start: -1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  33086. Loop( { start: -1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  33087. Loop( { start: -1, end: int( 1 ), name: 'z', condition: '<=' }, ( { z } ) => {
  33088. const dist = float( mx_worley_distance( localpos, x, y, z, X, Y, Z, jitter, metric ) ).toVar();
  33089. sqdist.assign( min$1( sqdist, dist ) );
  33090. } );
  33091. } );
  33092. } );
  33093. If( metric.equal( int( 0 ) ), () => {
  33094. sqdist.assign( sqrt( sqdist ) );
  33095. } );
  33096. return sqdist;
  33097. } ).setLayout( {
  33098. name: 'mx_worley_noise_float_1',
  33099. type: 'float',
  33100. inputs: [
  33101. { name: 'p', type: 'vec3' },
  33102. { name: 'jitter', type: 'float' },
  33103. { name: 'metric', type: 'int' }
  33104. ]
  33105. } );
  33106. const mx_worley_noise_float$1 = /*@__PURE__*/ overloadingFn( [ mx_worley_noise_float_0, mx_worley_noise_float_1 ] );
  33107. const mx_worley_noise_vec2_1 = /*@__PURE__*/ Fn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  33108. const metric = int( metric_immutable ).toVar();
  33109. const jitter = float( jitter_immutable ).toVar();
  33110. const p = vec3( p_immutable ).toVar();
  33111. const X = int().toVar(), Y = int().toVar(), Z = int().toVar();
  33112. const localpos = vec3( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ), mx_floorfrac( p.z, Z ) ).toVar();
  33113. const sqdist = vec2( 1e6, 1e6 ).toVar();
  33114. Loop( { start: -1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  33115. Loop( { start: -1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  33116. Loop( { start: -1, end: int( 1 ), name: 'z', condition: '<=' }, ( { z } ) => {
  33117. const dist = float( mx_worley_distance( localpos, x, y, z, X, Y, Z, jitter, metric ) ).toVar();
  33118. If( dist.lessThan( sqdist.x ), () => {
  33119. sqdist.y.assign( sqdist.x );
  33120. sqdist.x.assign( dist );
  33121. } ).ElseIf( dist.lessThan( sqdist.y ), () => {
  33122. sqdist.y.assign( dist );
  33123. } );
  33124. } );
  33125. } );
  33126. } );
  33127. If( metric.equal( int( 0 ) ), () => {
  33128. sqdist.assign( sqrt( sqdist ) );
  33129. } );
  33130. return sqdist;
  33131. } ).setLayout( {
  33132. name: 'mx_worley_noise_vec2_1',
  33133. type: 'vec2',
  33134. inputs: [
  33135. { name: 'p', type: 'vec3' },
  33136. { name: 'jitter', type: 'float' },
  33137. { name: 'metric', type: 'int' }
  33138. ]
  33139. } );
  33140. const mx_worley_noise_vec2$1 = /*@__PURE__*/ overloadingFn( [ mx_worley_noise_vec2_0, mx_worley_noise_vec2_1 ] );
  33141. const mx_worley_noise_vec3_1 = /*@__PURE__*/ Fn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  33142. const metric = int( metric_immutable ).toVar();
  33143. const jitter = float( jitter_immutable ).toVar();
  33144. const p = vec3( p_immutable ).toVar();
  33145. const X = int().toVar(), Y = int().toVar(), Z = int().toVar();
  33146. const localpos = vec3( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ), mx_floorfrac( p.z, Z ) ).toVar();
  33147. const sqdist = vec3( 1e6, 1e6, 1e6 ).toVar();
  33148. Loop( { start: -1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  33149. Loop( { start: -1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  33150. Loop( { start: -1, end: int( 1 ), name: 'z', condition: '<=' }, ( { z } ) => {
  33151. const dist = float( mx_worley_distance( localpos, x, y, z, X, Y, Z, jitter, metric ) ).toVar();
  33152. If( dist.lessThan( sqdist.x ), () => {
  33153. sqdist.z.assign( sqdist.y );
  33154. sqdist.y.assign( sqdist.x );
  33155. sqdist.x.assign( dist );
  33156. } ).ElseIf( dist.lessThan( sqdist.y ), () => {
  33157. sqdist.z.assign( sqdist.y );
  33158. sqdist.y.assign( dist );
  33159. } ).ElseIf( dist.lessThan( sqdist.z ), () => {
  33160. sqdist.z.assign( dist );
  33161. } );
  33162. } );
  33163. } );
  33164. } );
  33165. If( metric.equal( int( 0 ) ), () => {
  33166. sqdist.assign( sqrt( sqdist ) );
  33167. } );
  33168. return sqdist;
  33169. } ).setLayout( {
  33170. name: 'mx_worley_noise_vec3_1',
  33171. type: 'vec3',
  33172. inputs: [
  33173. { name: 'p', type: 'vec3' },
  33174. { name: 'jitter', type: 'float' },
  33175. { name: 'metric', type: 'int' }
  33176. ]
  33177. } );
  33178. const mx_worley_noise_vec3$1 = /*@__PURE__*/ overloadingFn( [ mx_worley_noise_vec3_0, mx_worley_noise_vec3_1 ] );
  33179. // Unified Noise 2D
  33180. const mx_unifiednoise2d$1 = /*@__PURE__*/ Fn( ( [
  33181. noiseType_immutable, texcoord_immutable, freq_immutable, offset_immutable,
  33182. jitter_immutable, outmin_immutable, outmax_immutable, clampoutput_immutable,
  33183. octaves_immutable, lacunarity_immutable, diminish_immutable
  33184. ] ) => {
  33185. const noiseType = int( noiseType_immutable ).toVar();
  33186. const texcoord = vec2( texcoord_immutable ).toVar();
  33187. const freq = vec2( freq_immutable ).toVar();
  33188. const offset = vec2( offset_immutable ).toVar();
  33189. const jitter = float( jitter_immutable ).toVar();
  33190. const outmin = float( outmin_immutable ).toVar();
  33191. const outmax = float( outmax_immutable ).toVar();
  33192. const clampoutput = bool( clampoutput_immutable ).toVar();
  33193. const octaves = int( octaves_immutable ).toVar();
  33194. const lacunarity = float( lacunarity_immutable ).toVar();
  33195. const diminish = float( diminish_immutable ).toVar();
  33196. // Compute input position
  33197. const p = texcoord.mul( freq ).add( offset );
  33198. const result = float( 0.0 ).toVar();
  33199. // Perlin
  33200. If( noiseType.equal( int( 0 ) ), () => {
  33201. result.assign( mx_perlin_noise_vec3( p ) );
  33202. } );
  33203. // Cell
  33204. If( noiseType.equal( int( 1 ) ), () => {
  33205. result.assign( mx_cell_noise_vec3( p ) );
  33206. } );
  33207. // Worley (metric=0 = euclidean)
  33208. If( noiseType.equal( int( 2 ) ), () => {
  33209. result.assign( mx_worley_noise_vec3$1( p, jitter, int( 0 ) ) );
  33210. } );
  33211. // Fractal (use vec3(p, 0.0) for 2D input)
  33212. If( noiseType.equal( int( 3 ) ), () => {
  33213. result.assign( mx_fractal_noise_vec3$1( vec3( p, 0.0 ), octaves, lacunarity, diminish ) );
  33214. } );
  33215. // Remap output to [outmin, outmax]
  33216. result.assign( result.mul( outmax.sub( outmin ) ).add( outmin ) );
  33217. // Clamp if requested
  33218. If( clampoutput, () => {
  33219. result.assign( clamp( result, outmin, outmax ) );
  33220. } );
  33221. return result;
  33222. } ).setLayout( {
  33223. name: 'mx_unifiednoise2d',
  33224. type: 'float',
  33225. inputs: [
  33226. { name: 'noiseType', type: 'int' },
  33227. { name: 'texcoord', type: 'vec2' },
  33228. { name: 'freq', type: 'vec2' },
  33229. { name: 'offset', type: 'vec2' },
  33230. { name: 'jitter', type: 'float' },
  33231. { name: 'outmin', type: 'float' },
  33232. { name: 'outmax', type: 'float' },
  33233. { name: 'clampoutput', type: 'bool' },
  33234. { name: 'octaves', type: 'int' },
  33235. { name: 'lacunarity', type: 'float' },
  33236. { name: 'diminish', type: 'float' }
  33237. ]
  33238. } );
  33239. // Unified Noise 3D
  33240. const mx_unifiednoise3d$1 = /*@__PURE__*/ Fn( ( [
  33241. noiseType_immutable, position_immutable, freq_immutable, offset_immutable,
  33242. jitter_immutable, outmin_immutable, outmax_immutable, clampoutput_immutable,
  33243. octaves_immutable, lacunarity_immutable, diminish_immutable
  33244. ] ) => {
  33245. const noiseType = int( noiseType_immutable ).toVar();
  33246. const position = vec3( position_immutable ).toVar();
  33247. const freq = vec3( freq_immutable ).toVar();
  33248. const offset = vec3( offset_immutable ).toVar();
  33249. const jitter = float( jitter_immutable ).toVar();
  33250. const outmin = float( outmin_immutable ).toVar();
  33251. const outmax = float( outmax_immutable ).toVar();
  33252. const clampoutput = bool( clampoutput_immutable ).toVar();
  33253. const octaves = int( octaves_immutable ).toVar();
  33254. const lacunarity = float( lacunarity_immutable ).toVar();
  33255. const diminish = float( diminish_immutable ).toVar();
  33256. // Compute input position
  33257. const p = position.mul( freq ).add( offset );
  33258. const result = float( 0.0 ).toVar();
  33259. // Perlin
  33260. If( noiseType.equal( int( 0 ) ), () => {
  33261. result.assign( mx_perlin_noise_vec3( p ) );
  33262. } );
  33263. // Cell
  33264. If( noiseType.equal( int( 1 ) ), () => {
  33265. result.assign( mx_cell_noise_vec3( p ) );
  33266. } );
  33267. // Worley (metric=0 = euclidean)
  33268. If( noiseType.equal( int( 2 ) ), () => {
  33269. result.assign( mx_worley_noise_vec3$1( p, jitter, int( 0 ) ) );
  33270. } );
  33271. // Fractal
  33272. If( noiseType.equal( int( 3 ) ), () => {
  33273. result.assign( mx_fractal_noise_vec3$1( p, octaves, lacunarity, diminish ) );
  33274. } );
  33275. // Remap output to [outmin, outmax]
  33276. result.assign( result.mul( outmax.sub( outmin ) ).add( outmin ) );
  33277. // Clamp if requested
  33278. If( clampoutput, () => {
  33279. result.assign( clamp( result, outmin, outmax ) );
  33280. } );
  33281. return result;
  33282. } ).setLayout( {
  33283. name: 'mx_unifiednoise3d',
  33284. type: 'float',
  33285. inputs: [
  33286. { name: 'noiseType', type: 'int' },
  33287. { name: 'position', type: 'vec3' },
  33288. { name: 'freq', type: 'vec3' },
  33289. { name: 'offset', type: 'vec3' },
  33290. { name: 'jitter', type: 'float' },
  33291. { name: 'outmin', type: 'float' },
  33292. { name: 'outmax', type: 'float' },
  33293. { name: 'clampoutput', type: 'bool' },
  33294. { name: 'octaves', type: 'int' },
  33295. { name: 'lacunarity', type: 'float' },
  33296. { name: 'diminish', type: 'float' }
  33297. ]
  33298. } );
  33299. // Three.js Transpiler
  33300. // https://github.com/AcademySoftwareFoundation/MaterialX/blob/main/libraries/stdlib/genglsl/lib/mx_hsv.glsl
  33301. const mx_hsvtorgb = /*@__PURE__*/ Fn( ( [ hsv ] ) => {
  33302. const s = hsv.y;
  33303. const v = hsv.z;
  33304. const result = vec3().toVar();
  33305. If( s.lessThan( 0.0001 ), () => {
  33306. result.assign( vec3( v, v, v ) );
  33307. } ).Else( () => {
  33308. let h = hsv.x;
  33309. h = h.sub( floor( h ) ).mul( 6.0 ).toVar(); // TODO: check what .toVar() is needed in node system cache
  33310. const hi = int( trunc( h ) );
  33311. const f = h.sub( float( hi ) );
  33312. const p = v.mul( s.oneMinus() );
  33313. const q = v.mul( s.mul( f ).oneMinus() );
  33314. const t = v.mul( s.mul( f.oneMinus() ).oneMinus() );
  33315. If( hi.equal( int( 0 ) ), () => {
  33316. result.assign( vec3( v, t, p ) );
  33317. } ).ElseIf( hi.equal( int( 1 ) ), () => {
  33318. result.assign( vec3( q, v, p ) );
  33319. } ).ElseIf( hi.equal( int( 2 ) ), () => {
  33320. result.assign( vec3( p, v, t ) );
  33321. } ).ElseIf( hi.equal( int( 3 ) ), () => {
  33322. result.assign( vec3( p, q, v ) );
  33323. } ).ElseIf( hi.equal( int( 4 ) ), () => {
  33324. result.assign( vec3( t, p, v ) );
  33325. } ).Else( () => {
  33326. result.assign( vec3( v, p, q ) );
  33327. } );
  33328. } );
  33329. return result;
  33330. } ).setLayout( {
  33331. name: 'mx_hsvtorgb',
  33332. type: 'vec3',
  33333. inputs: [
  33334. { name: 'hsv', type: 'vec3' }
  33335. ]
  33336. } );
  33337. const mx_rgbtohsv = /*@__PURE__*/ Fn( ( [ c_immutable ] ) => {
  33338. const c = vec3( c_immutable ).toVar();
  33339. const r = float( c.x ).toVar();
  33340. const g = float( c.y ).toVar();
  33341. const b = float( c.z ).toVar();
  33342. const mincomp = float( min$1( r, min$1( g, b ) ) ).toVar();
  33343. const maxcomp = float( max$1( r, max$1( g, b ) ) ).toVar();
  33344. const delta = float( maxcomp.sub( mincomp ) ).toVar();
  33345. const h = float().toVar(), s = float().toVar(), v = float().toVar();
  33346. v.assign( maxcomp );
  33347. If( maxcomp.greaterThan( 0.0 ), () => {
  33348. s.assign( delta.div( maxcomp ) );
  33349. } ).Else( () => {
  33350. s.assign( 0.0 );
  33351. } );
  33352. If( s.lessThanEqual( 0.0 ), () => {
  33353. h.assign( 0.0 );
  33354. } ).Else( () => {
  33355. If( r.greaterThanEqual( maxcomp ), () => {
  33356. h.assign( g.sub( b ).div( delta ) );
  33357. } ).ElseIf( g.greaterThanEqual( maxcomp ), () => {
  33358. h.assign( add( 2.0, b.sub( r ).div( delta ) ) );
  33359. } ).Else( () => {
  33360. h.assign( add( 4.0, r.sub( g ).div( delta ) ) );
  33361. } );
  33362. h.mulAssign( 1.0 / 6.0 );
  33363. If( h.lessThan( 0.0 ), () => {
  33364. h.addAssign( 1.0 );
  33365. } );
  33366. } );
  33367. return vec3( h, s, v );
  33368. } ).setLayout( {
  33369. name: 'mx_rgbtohsv',
  33370. type: 'vec3',
  33371. inputs: [
  33372. { name: 'c', type: 'vec3' }
  33373. ]
  33374. } );
  33375. // Three.js Transpiler
  33376. // https://github.com/AcademySoftwareFoundation/MaterialX/blob/main/libraries/stdlib/genglsl/lib/mx_transform_color.glsl
  33377. const mx_srgb_texture_to_lin_rec709 = /*@__PURE__*/ Fn( ( [ color_immutable ] ) => {
  33378. const color = vec3( color_immutable ).toVar();
  33379. const isAbove = bvec3( greaterThan( color, vec3( 0.04045 ) ) ).toVar();
  33380. const linSeg = vec3( color.div( 12.92 ) ).toVar();
  33381. const powSeg = vec3( pow( max$1( color.add( vec3( 0.055 ) ), vec3( 0.0 ) ).div( 1.055 ), vec3( 2.4 ) ) ).toVar();
  33382. return mix( linSeg, powSeg, isAbove );
  33383. } ).setLayout( {
  33384. name: 'mx_srgb_texture_to_lin_rec709',
  33385. type: 'vec3',
  33386. inputs: [
  33387. { name: 'color', type: 'vec3' }
  33388. ]
  33389. } );
  33390. const mx_aastep = ( threshold, value ) => {
  33391. threshold = float( threshold );
  33392. value = float( value );
  33393. const afwidth = vec2( value.dFdx(), value.dFdy() ).length().mul( 0.70710678118654757 );
  33394. return smoothstep( threshold.sub( afwidth ), threshold.add( afwidth ), value );
  33395. };
  33396. const _ramp = ( a, b, uv, p ) => mix( a, b, uv[ p ].clamp() );
  33397. const mx_ramplr = ( valuel, valuer, texcoord = uv$1() ) => _ramp( valuel, valuer, texcoord, 'x' );
  33398. const mx_ramptb = ( valuet, valueb, texcoord = uv$1() ) => _ramp( valuet, valueb, texcoord, 'y' );
  33399. // Bilinear ramp: interpolate between four corners (tl, tr, bl, br) using texcoord.x and texcoord.y
  33400. const mx_ramp4 = (
  33401. valuetl, valuetr, valuebl, valuebr, texcoord = uv$1()
  33402. ) => {
  33403. const u = texcoord.x.clamp();
  33404. const v = texcoord.y.clamp();
  33405. const top = mix( valuetl, valuetr, u );
  33406. const bottom = mix( valuebl, valuebr, u );
  33407. return mix( top, bottom, v );
  33408. };
  33409. const _split = ( a, b, center, uv, p ) => mix( a, b, mx_aastep( center, uv[ p ] ) );
  33410. const mx_splitlr = ( valuel, valuer, center, texcoord = uv$1() ) => _split( valuel, valuer, center, texcoord, 'x' );
  33411. const mx_splittb = ( valuet, valueb, center, texcoord = uv$1() ) => _split( valuet, valueb, center, texcoord, 'y' );
  33412. const mx_transform_uv = ( uv_scale = 1, uv_offset = 0, uv_geo = uv$1() ) => uv_geo.mul( uv_scale ).add( uv_offset );
  33413. const mx_safepower = ( in1, in2 = 1 ) => {
  33414. in1 = float( in1 );
  33415. return in1.abs().pow( in2 ).mul( in1.sign() );
  33416. };
  33417. const mx_contrast = ( input, amount = 1, pivot = .5 ) => float( input ).sub( pivot ).mul( amount ).add( pivot );
  33418. const mx_noise_float = ( texcoord = uv$1(), amplitude = 1, pivot = 0 ) => mx_perlin_noise_float( texcoord.convert( 'vec2|vec3' ) ).mul( amplitude ).add( pivot );
  33419. //export const mx_noise_vec2 = ( texcoord = uv(), amplitude = 1, pivot = 0 ) => mx_perlin_noise_vec3( texcoord.convert( 'vec2|vec3' ) ).mul( amplitude ).add( pivot );
  33420. const mx_noise_vec3 = ( texcoord = uv$1(), amplitude = 1, pivot = 0 ) => mx_perlin_noise_vec3( texcoord.convert( 'vec2|vec3' ) ).mul( amplitude ).add( pivot );
  33421. const mx_noise_vec4 = ( texcoord = uv$1(), amplitude = 1, pivot = 0 ) => {
  33422. texcoord = texcoord.convert( 'vec2|vec3' ); // overloading type
  33423. const noise_vec4 = vec4( mx_perlin_noise_vec3( texcoord ), mx_perlin_noise_float( texcoord.add( vec2( 19, 73 ) ) ) );
  33424. return noise_vec4.mul( amplitude ).add( pivot );
  33425. };
  33426. 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 );
  33427. 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 );
  33428. const mx_worley_noise_float = ( texcoord = uv$1(), jitter = 1 ) => mx_worley_noise_float$1( texcoord.convert( 'vec2|vec3' ), jitter, int( 1 ) );
  33429. const mx_worley_noise_vec2 = ( texcoord = uv$1(), jitter = 1 ) => mx_worley_noise_vec2$1( texcoord.convert( 'vec2|vec3' ), jitter, int( 1 ) );
  33430. const mx_worley_noise_vec3 = ( texcoord = uv$1(), jitter = 1 ) => mx_worley_noise_vec3$1( texcoord.convert( 'vec2|vec3' ), jitter, int( 1 ) );
  33431. const mx_cell_noise_float = ( texcoord = uv$1() ) => mx_cell_noise_float$1( texcoord.convert( 'vec2|vec3' ) );
  33432. 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 );
  33433. 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 );
  33434. 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 );
  33435. 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 );
  33436. // === Moved from MaterialXLoader.js ===
  33437. // Math ops
  33438. const mx_add = ( in1, in2 = float( 0 ) ) => add( in1, in2 );
  33439. const mx_subtract = ( in1, in2 = float( 0 ) ) => sub( in1, in2 );
  33440. const mx_multiply = ( in1, in2 = float( 1 ) ) => mul( in1, in2 );
  33441. const mx_divide = ( in1, in2 = float( 1 ) ) => div( in1, in2 );
  33442. const mx_modulo = ( in1, in2 = float( 1 ) ) => mod( in1, in2 );
  33443. const mx_power = ( in1, in2 = float( 1 ) ) => pow( in1, in2 );
  33444. const mx_atan2 = ( in1 = float( 0 ), in2 = float( 1 ) ) => atan( in1, in2 );
  33445. const mx_timer = () => time;
  33446. const mx_frame = () => frameId;
  33447. const mx_invert = ( in1, amount = float( 1 ) ) => sub( amount, in1 );
  33448. const mx_ifgreater = ( value1, value2, in1, in2 ) => value1.greaterThan( value2 ).mix( in1, in2 );
  33449. const mx_ifgreatereq = ( value1, value2, in1, in2 ) => value1.greaterThanEqual( value2 ).mix( in1, in2 );
  33450. const mx_ifequal = ( value1, value2, in1, in2 ) => value1.equal( value2 ).mix( in1, in2 );
  33451. // Enhanced separate node to support multi-output referencing (outx, outy, outz, outw)
  33452. const mx_separate = ( in1, channelOrOut = null ) => {
  33453. if ( typeof channelOrOut === 'string' ) {
  33454. const map = { x: 0, r: 0, y: 1, g: 1, z: 2, b: 2, w: 3, a: 3 };
  33455. const c = channelOrOut.replace( /^out/, '' ).toLowerCase();
  33456. if ( map[ c ] !== undefined ) return in1.element( map[ c ] );
  33457. }
  33458. if ( typeof channelOrOut === 'number' ) {
  33459. return in1.element( channelOrOut );
  33460. }
  33461. if ( typeof channelOrOut === 'string' && channelOrOut.length === 1 ) {
  33462. const map = { x: 0, r: 0, y: 1, g: 1, z: 2, b: 2, w: 3, a: 3 };
  33463. if ( map[ channelOrOut ] !== undefined ) return in1.element( map[ channelOrOut ] );
  33464. }
  33465. return in1;
  33466. };
  33467. const mx_place2d = (
  33468. texcoord, pivot = vec2( 0.5, 0.5 ), scale = vec2( 1, 1 ), rotate = float( 0 ), offset = vec2( 0, 0 )/*, operationorder = int( 0 )*/
  33469. ) => {
  33470. let uv = texcoord;
  33471. if ( pivot ) uv = uv.sub( pivot );
  33472. if ( scale ) uv = uv.mul( scale );
  33473. if ( rotate ) {
  33474. const rad = rotate.mul( Math.PI / 180.0 );
  33475. const cosR = rad.cos();
  33476. const sinR = rad.sin();
  33477. uv = vec2(
  33478. uv.x.mul( cosR ).sub( uv.y.mul( sinR ) ),
  33479. uv.x.mul( sinR ).add( uv.y.mul( cosR ) )
  33480. );
  33481. }
  33482. if ( pivot ) uv = uv.add( pivot );
  33483. if ( offset ) uv = uv.add( offset );
  33484. return uv;
  33485. };
  33486. const mx_rotate2d = ( input, amount ) => {
  33487. input = vec2( input );
  33488. amount = float( amount );
  33489. const radians = amount.mul( Math.PI / 180.0 );
  33490. return rotate( input, radians );
  33491. };
  33492. const mx_rotate3d = ( input, amount, axis ) => {
  33493. input = vec3( input );
  33494. amount = float( amount );
  33495. axis = vec3( axis );
  33496. const radians = amount.mul( Math.PI / 180.0 );
  33497. const nAxis = axis.normalize();
  33498. const cosA = radians.cos();
  33499. const sinA = radians.sin();
  33500. const oneMinusCosA = float( 1 ).sub( cosA );
  33501. const rot =
  33502. input.mul( cosA )
  33503. .add( nAxis.cross( input ).mul( sinA ) )
  33504. .add( nAxis.mul( nAxis.dot( input ) ).mul( oneMinusCosA ) );
  33505. return rot;
  33506. };
  33507. const mx_heighttonormal = ( input, scale/*, texcoord*/ ) => {
  33508. input = vec3( input );
  33509. scale = float( scale );
  33510. return bumpMap( input, scale );
  33511. };
  33512. /**
  33513. * This computes a parallax corrected normal which is used for box-projected cube mapping (BPCEM).
  33514. *
  33515. * Reference: {@link https://devlog-martinsh.blogspot.com/2011/09/box-projected-cube-environment-mapping.html}
  33516. *
  33517. * ```js
  33518. * const uvNode = getParallaxCorrectNormal( reflectVector, vec3( 200, 100, 100 ), vec3( 0, - 50, 0 ) );
  33519. * material.envNode = pmremTexture( renderTarget.texture, uvNode );
  33520. * ```
  33521. *
  33522. * @tsl
  33523. * @function
  33524. * @param {Node<vec3>} normal - The normal to correct.
  33525. * @param {Node<vec3>} cubeSize - The cube size should reflect the size of the environment (BPCEM is usually applied in closed environments like rooms).
  33526. * @param {Node<vec3>} cubePos - The cube position.
  33527. * @return {Node<vec3>} The parallax corrected normal.
  33528. */
  33529. const getParallaxCorrectNormal = /*@__PURE__*/ Fn( ( [ normal, cubeSize, cubePos ] ) => {
  33530. const nDir = normalize( normal ).toVar();
  33531. const rbmax = sub( float( 0.5 ).mul( cubeSize.sub( cubePos ) ), positionWorld ).div( nDir ).toVar();
  33532. const rbmin = sub( float( -0.5 ).mul( cubeSize.sub( cubePos ) ), positionWorld ).div( nDir ).toVar();
  33533. const rbminmax = vec3().toVar();
  33534. rbminmax.x = nDir.x.greaterThan( float( 0 ) ).select( rbmax.x, rbmin.x );
  33535. rbminmax.y = nDir.y.greaterThan( float( 0 ) ).select( rbmax.y, rbmin.y );
  33536. rbminmax.z = nDir.z.greaterThan( float( 0 ) ).select( rbmax.z, rbmin.z );
  33537. const correction = min$1( rbminmax.x, rbminmax.y, rbminmax.z ).toVar();
  33538. const boxIntersection = positionWorld.add( nDir.mul( correction ) ).toVar();
  33539. return boxIntersection.sub( cubePos );
  33540. } );
  33541. const getShIrradianceAt = /*@__PURE__*/ Fn( ( [ normal, shCoefficients ] ) => {
  33542. // normal is assumed to have unit length
  33543. const x = normal.x, y = normal.y, z = normal.z;
  33544. // band 0
  33545. let result = shCoefficients.element( 0 ).mul( 0.886227 );
  33546. // band 1
  33547. result = result.add( shCoefficients.element( 1 ).mul( 2.0 * 0.511664 ).mul( y ) );
  33548. result = result.add( shCoefficients.element( 2 ).mul( 2.0 * 0.511664 ).mul( z ) );
  33549. result = result.add( shCoefficients.element( 3 ).mul( 2.0 * 0.511664 ).mul( x ) );
  33550. // band 2
  33551. result = result.add( shCoefficients.element( 4 ).mul( 2.0 * 0.429043 ).mul( x ).mul( y ) );
  33552. result = result.add( shCoefficients.element( 5 ).mul( 2.0 * 0.429043 ).mul( y ).mul( z ) );
  33553. result = result.add( shCoefficients.element( 6 ).mul( z.mul( z ).mul( 0.743125 ).sub( 0.247708 ) ) );
  33554. result = result.add( shCoefficients.element( 7 ).mul( 2.0 * 0.429043 ).mul( x ).mul( z ) );
  33555. result = result.add( shCoefficients.element( 8 ).mul( 0.429043 ).mul( mul( x, x ).sub( mul( y, y ) ) ) );
  33556. return result;
  33557. } );
  33558. // constants
  33559. var TSL = /*#__PURE__*/Object.freeze({
  33560. __proto__: null,
  33561. BRDF_GGX: BRDF_GGX,
  33562. BRDF_Lambert: BRDF_Lambert,
  33563. BasicPointShadowFilter: BasicPointShadowFilter,
  33564. BasicShadowFilter: BasicShadowFilter,
  33565. Break: Break,
  33566. Const: Const,
  33567. Continue: Continue,
  33568. DFGLUT: DFGLUT,
  33569. D_GGX: D_GGX,
  33570. Discard: Discard,
  33571. EPSILON: EPSILON,
  33572. F_Schlick: F_Schlick,
  33573. Fn: Fn,
  33574. HALF_PI: HALF_PI,
  33575. INFINITY: INFINITY,
  33576. If: If,
  33577. Loop: Loop,
  33578. NodeAccess: NodeAccess,
  33579. NodeShaderStage: NodeShaderStage,
  33580. NodeType: NodeType,
  33581. NodeUpdateType: NodeUpdateType,
  33582. OnBeforeMaterialUpdate: OnBeforeMaterialUpdate,
  33583. OnBeforeObjectUpdate: OnBeforeObjectUpdate,
  33584. OnMaterialUpdate: OnMaterialUpdate,
  33585. OnObjectUpdate: OnObjectUpdate,
  33586. PCFShadowFilter: PCFShadowFilter,
  33587. PCFSoftShadowFilter: PCFSoftShadowFilter,
  33588. PI: PI,
  33589. PI2: PI2,
  33590. PointShadowFilter: PointShadowFilter,
  33591. Return: Return,
  33592. Schlick_to_F0: Schlick_to_F0,
  33593. ScriptableNodeResources: ScriptableNodeResources,
  33594. ShaderNode: ShaderNode,
  33595. Stack: Stack,
  33596. Switch: Switch,
  33597. TBNViewMatrix: TBNViewMatrix,
  33598. TWO_PI: TWO_PI,
  33599. VSMShadowFilter: VSMShadowFilter,
  33600. V_GGX_SmithCorrelated: V_GGX_SmithCorrelated,
  33601. Var: Var,
  33602. VarIntent: VarIntent,
  33603. abs: abs,
  33604. acesFilmicToneMapping: acesFilmicToneMapping,
  33605. acos: acos,
  33606. add: add,
  33607. addMethodChaining: addMethodChaining,
  33608. addNodeElement: addNodeElement,
  33609. agxToneMapping: agxToneMapping,
  33610. all: all,
  33611. alphaT: alphaT,
  33612. and: and,
  33613. anisotropy: anisotropy,
  33614. anisotropyB: anisotropyB,
  33615. anisotropyT: anisotropyT,
  33616. any: any,
  33617. append: append,
  33618. array: array,
  33619. arrayBuffer: arrayBuffer,
  33620. asin: asin,
  33621. assign: assign,
  33622. atan: atan,
  33623. atan2: atan2,
  33624. atomicAdd: atomicAdd,
  33625. atomicAnd: atomicAnd,
  33626. atomicFunc: atomicFunc,
  33627. atomicLoad: atomicLoad,
  33628. atomicMax: atomicMax,
  33629. atomicMin: atomicMin,
  33630. atomicOr: atomicOr,
  33631. atomicStore: atomicStore,
  33632. atomicSub: atomicSub,
  33633. atomicXor: atomicXor,
  33634. attenuationColor: attenuationColor,
  33635. attenuationDistance: attenuationDistance,
  33636. attribute: attribute,
  33637. attributeArray: attributeArray,
  33638. backgroundBlurriness: backgroundBlurriness,
  33639. backgroundIntensity: backgroundIntensity,
  33640. backgroundRotation: backgroundRotation,
  33641. batch: batch,
  33642. bentNormalView: bentNormalView,
  33643. billboarding: billboarding,
  33644. bitAnd: bitAnd,
  33645. bitNot: bitNot,
  33646. bitOr: bitOr,
  33647. bitXor: bitXor,
  33648. bitangentGeometry: bitangentGeometry,
  33649. bitangentLocal: bitangentLocal,
  33650. bitangentView: bitangentView,
  33651. bitangentWorld: bitangentWorld,
  33652. bitcast: bitcast,
  33653. blendBurn: blendBurn,
  33654. blendColor: blendColor,
  33655. blendDodge: blendDodge,
  33656. blendOverlay: blendOverlay,
  33657. blendScreen: blendScreen,
  33658. blur: blur,
  33659. bool: bool,
  33660. buffer: buffer,
  33661. bufferAttribute: bufferAttribute,
  33662. builtin: builtin,
  33663. builtinAOContext: builtinAOContext,
  33664. builtinShadowContext: builtinShadowContext,
  33665. bumpMap: bumpMap,
  33666. burn: burn,
  33667. bvec2: bvec2,
  33668. bvec3: bvec3,
  33669. bvec4: bvec4,
  33670. bypass: bypass,
  33671. cache: cache,
  33672. call: call,
  33673. cameraFar: cameraFar,
  33674. cameraIndex: cameraIndex,
  33675. cameraNear: cameraNear,
  33676. cameraNormalMatrix: cameraNormalMatrix,
  33677. cameraPosition: cameraPosition,
  33678. cameraProjectionMatrix: cameraProjectionMatrix,
  33679. cameraProjectionMatrixInverse: cameraProjectionMatrixInverse,
  33680. cameraViewMatrix: cameraViewMatrix,
  33681. cameraViewport: cameraViewport,
  33682. cameraWorldMatrix: cameraWorldMatrix,
  33683. cbrt: cbrt,
  33684. cdl: cdl,
  33685. ceil: ceil,
  33686. checker: checker,
  33687. cineonToneMapping: cineonToneMapping,
  33688. clamp: clamp,
  33689. clearcoat: clearcoat,
  33690. clearcoatNormalView: clearcoatNormalView,
  33691. clearcoatRoughness: clearcoatRoughness,
  33692. code: code,
  33693. color: color,
  33694. colorSpaceToWorking: colorSpaceToWorking,
  33695. colorToDirection: colorToDirection,
  33696. compute: compute,
  33697. computeKernel: computeKernel,
  33698. computeSkinning: computeSkinning,
  33699. context: context,
  33700. convert: convert,
  33701. convertColorSpace: convertColorSpace,
  33702. convertToTexture: convertToTexture,
  33703. cos: cos,
  33704. countLeadingZeros: countLeadingZeros,
  33705. countOneBits: countOneBits,
  33706. countTrailingZeros: countTrailingZeros,
  33707. cross: cross,
  33708. cubeTexture: cubeTexture,
  33709. cubeTextureBase: cubeTextureBase,
  33710. dFdx: dFdx,
  33711. dFdy: dFdy,
  33712. dashSize: dashSize,
  33713. debug: debug,
  33714. decrement: decrement,
  33715. decrementBefore: decrementBefore,
  33716. defaultBuildStages: defaultBuildStages,
  33717. defaultShaderStages: defaultShaderStages,
  33718. defined: defined,
  33719. degrees: degrees,
  33720. deltaTime: deltaTime,
  33721. densityFog: densityFog,
  33722. densityFogFactor: densityFogFactor,
  33723. depth: depth,
  33724. depthPass: depthPass,
  33725. determinant: determinant,
  33726. difference: difference,
  33727. diffuseColor: diffuseColor,
  33728. diffuseContribution: diffuseContribution,
  33729. directPointLight: directPointLight,
  33730. directionToColor: directionToColor,
  33731. directionToFaceDirection: directionToFaceDirection,
  33732. dispersion: dispersion,
  33733. disposeShadowMaterial: disposeShadowMaterial,
  33734. distance: distance,
  33735. div: div,
  33736. dodge: dodge,
  33737. dot: dot,
  33738. drawIndex: drawIndex,
  33739. dynamicBufferAttribute: dynamicBufferAttribute,
  33740. element: element,
  33741. emissive: emissive,
  33742. equal: equal,
  33743. equals: equals,
  33744. equirectUV: equirectUV,
  33745. exp: exp,
  33746. exp2: exp2,
  33747. expression: expression,
  33748. faceDirection: faceDirection,
  33749. faceForward: faceForward,
  33750. faceforward: faceforward,
  33751. float: float,
  33752. floatBitsToInt: floatBitsToInt,
  33753. floatBitsToUint: floatBitsToUint,
  33754. floor: floor,
  33755. fog: fog,
  33756. fract: fract,
  33757. frameGroup: frameGroup,
  33758. frameId: frameId,
  33759. frontFacing: frontFacing,
  33760. fwidth: fwidth,
  33761. gain: gain,
  33762. gapSize: gapSize,
  33763. getConstNodeType: getConstNodeType,
  33764. getCurrentStack: getCurrentStack,
  33765. getDirection: getDirection,
  33766. getDistanceAttenuation: getDistanceAttenuation,
  33767. getGeometryRoughness: getGeometryRoughness,
  33768. getNormalFromDepth: getNormalFromDepth,
  33769. getParallaxCorrectNormal: getParallaxCorrectNormal,
  33770. getRoughness: getRoughness,
  33771. getScreenPosition: getScreenPosition,
  33772. getShIrradianceAt: getShIrradianceAt,
  33773. getShadowMaterial: getShadowMaterial,
  33774. getShadowRenderObjectFunction: getShadowRenderObjectFunction,
  33775. getTextureIndex: getTextureIndex,
  33776. getViewPosition: getViewPosition,
  33777. ggxConvolution: ggxConvolution,
  33778. globalId: globalId,
  33779. glsl: glsl,
  33780. glslFn: glslFn,
  33781. grayscale: grayscale,
  33782. greaterThan: greaterThan,
  33783. greaterThanEqual: greaterThanEqual,
  33784. hash: hash,
  33785. highpModelNormalViewMatrix: highpModelNormalViewMatrix,
  33786. highpModelViewMatrix: highpModelViewMatrix,
  33787. hue: hue,
  33788. increment: increment,
  33789. incrementBefore: incrementBefore,
  33790. inspector: inspector,
  33791. instance: instance,
  33792. instanceIndex: instanceIndex,
  33793. instancedArray: instancedArray,
  33794. instancedBufferAttribute: instancedBufferAttribute,
  33795. instancedDynamicBufferAttribute: instancedDynamicBufferAttribute,
  33796. instancedMesh: instancedMesh,
  33797. int: int,
  33798. intBitsToFloat: intBitsToFloat,
  33799. interleavedGradientNoise: interleavedGradientNoise,
  33800. inverse: inverse,
  33801. inverseSqrt: inverseSqrt,
  33802. inversesqrt: inversesqrt,
  33803. invocationLocalIndex: invocationLocalIndex,
  33804. invocationSubgroupIndex: invocationSubgroupIndex,
  33805. ior: ior,
  33806. iridescence: iridescence,
  33807. iridescenceIOR: iridescenceIOR,
  33808. iridescenceThickness: iridescenceThickness,
  33809. isolate: isolate,
  33810. ivec2: ivec2,
  33811. ivec3: ivec3,
  33812. ivec4: ivec4,
  33813. js: js,
  33814. label: label,
  33815. length: length,
  33816. lengthSq: lengthSq,
  33817. lessThan: lessThan,
  33818. lessThanEqual: lessThanEqual,
  33819. lightPosition: lightPosition,
  33820. lightProjectionUV: lightProjectionUV,
  33821. lightShadowMatrix: lightShadowMatrix,
  33822. lightTargetDirection: lightTargetDirection,
  33823. lightTargetPosition: lightTargetPosition,
  33824. lightViewPosition: lightViewPosition,
  33825. lightingContext: lightingContext,
  33826. lights: lights,
  33827. linearDepth: linearDepth,
  33828. linearToneMapping: linearToneMapping,
  33829. localId: localId,
  33830. log: log,
  33831. log2: log2,
  33832. logarithmicDepthToViewZ: logarithmicDepthToViewZ,
  33833. luminance: luminance,
  33834. mat2: mat2,
  33835. mat3: mat3,
  33836. mat4: mat4,
  33837. matcapUV: matcapUV,
  33838. materialAO: materialAO,
  33839. materialAlphaTest: materialAlphaTest,
  33840. materialAnisotropy: materialAnisotropy,
  33841. materialAnisotropyVector: materialAnisotropyVector,
  33842. materialAttenuationColor: materialAttenuationColor,
  33843. materialAttenuationDistance: materialAttenuationDistance,
  33844. materialClearcoat: materialClearcoat,
  33845. materialClearcoatNormal: materialClearcoatNormal,
  33846. materialClearcoatRoughness: materialClearcoatRoughness,
  33847. materialColor: materialColor,
  33848. materialDispersion: materialDispersion,
  33849. materialEmissive: materialEmissive,
  33850. materialEnvIntensity: materialEnvIntensity,
  33851. materialEnvRotation: materialEnvRotation,
  33852. materialIOR: materialIOR,
  33853. materialIridescence: materialIridescence,
  33854. materialIridescenceIOR: materialIridescenceIOR,
  33855. materialIridescenceThickness: materialIridescenceThickness,
  33856. materialLightMap: materialLightMap,
  33857. materialLineDashOffset: materialLineDashOffset,
  33858. materialLineDashSize: materialLineDashSize,
  33859. materialLineGapSize: materialLineGapSize,
  33860. materialLineScale: materialLineScale,
  33861. materialLineWidth: materialLineWidth,
  33862. materialMetalness: materialMetalness,
  33863. materialNormal: materialNormal,
  33864. materialOpacity: materialOpacity,
  33865. materialPointSize: materialPointSize,
  33866. materialReference: materialReference,
  33867. materialReflectivity: materialReflectivity,
  33868. materialRefractionRatio: materialRefractionRatio,
  33869. materialRotation: materialRotation,
  33870. materialRoughness: materialRoughness,
  33871. materialSheen: materialSheen,
  33872. materialSheenRoughness: materialSheenRoughness,
  33873. materialShininess: materialShininess,
  33874. materialSpecular: materialSpecular,
  33875. materialSpecularColor: materialSpecularColor,
  33876. materialSpecularIntensity: materialSpecularIntensity,
  33877. materialSpecularStrength: materialSpecularStrength,
  33878. materialThickness: materialThickness,
  33879. materialTransmission: materialTransmission,
  33880. max: max$1,
  33881. maxMipLevel: maxMipLevel,
  33882. mediumpModelViewMatrix: mediumpModelViewMatrix,
  33883. metalness: metalness,
  33884. min: min$1,
  33885. mix: mix,
  33886. mixElement: mixElement,
  33887. mod: mod,
  33888. modInt: modInt,
  33889. modelDirection: modelDirection,
  33890. modelNormalMatrix: modelNormalMatrix,
  33891. modelPosition: modelPosition,
  33892. modelRadius: modelRadius,
  33893. modelScale: modelScale,
  33894. modelViewMatrix: modelViewMatrix,
  33895. modelViewPosition: modelViewPosition,
  33896. modelViewProjection: modelViewProjection,
  33897. modelWorldMatrix: modelWorldMatrix,
  33898. modelWorldMatrixInverse: modelWorldMatrixInverse,
  33899. morphReference: morphReference,
  33900. mrt: mrt,
  33901. mul: mul,
  33902. mx_aastep: mx_aastep,
  33903. mx_add: mx_add,
  33904. mx_atan2: mx_atan2,
  33905. mx_cell_noise_float: mx_cell_noise_float,
  33906. mx_contrast: mx_contrast,
  33907. mx_divide: mx_divide,
  33908. mx_fractal_noise_float: mx_fractal_noise_float,
  33909. mx_fractal_noise_vec2: mx_fractal_noise_vec2,
  33910. mx_fractal_noise_vec3: mx_fractal_noise_vec3,
  33911. mx_fractal_noise_vec4: mx_fractal_noise_vec4,
  33912. mx_frame: mx_frame,
  33913. mx_heighttonormal: mx_heighttonormal,
  33914. mx_hsvtorgb: mx_hsvtorgb,
  33915. mx_ifequal: mx_ifequal,
  33916. mx_ifgreater: mx_ifgreater,
  33917. mx_ifgreatereq: mx_ifgreatereq,
  33918. mx_invert: mx_invert,
  33919. mx_modulo: mx_modulo,
  33920. mx_multiply: mx_multiply,
  33921. mx_noise_float: mx_noise_float,
  33922. mx_noise_vec3: mx_noise_vec3,
  33923. mx_noise_vec4: mx_noise_vec4,
  33924. mx_place2d: mx_place2d,
  33925. mx_power: mx_power,
  33926. mx_ramp4: mx_ramp4,
  33927. mx_ramplr: mx_ramplr,
  33928. mx_ramptb: mx_ramptb,
  33929. mx_rgbtohsv: mx_rgbtohsv,
  33930. mx_rotate2d: mx_rotate2d,
  33931. mx_rotate3d: mx_rotate3d,
  33932. mx_safepower: mx_safepower,
  33933. mx_separate: mx_separate,
  33934. mx_splitlr: mx_splitlr,
  33935. mx_splittb: mx_splittb,
  33936. mx_srgb_texture_to_lin_rec709: mx_srgb_texture_to_lin_rec709,
  33937. mx_subtract: mx_subtract,
  33938. mx_timer: mx_timer,
  33939. mx_transform_uv: mx_transform_uv,
  33940. mx_unifiednoise2d: mx_unifiednoise2d,
  33941. mx_unifiednoise3d: mx_unifiednoise3d,
  33942. mx_worley_noise_float: mx_worley_noise_float,
  33943. mx_worley_noise_vec2: mx_worley_noise_vec2,
  33944. mx_worley_noise_vec3: mx_worley_noise_vec3,
  33945. negate: negate,
  33946. neutralToneMapping: neutralToneMapping,
  33947. nodeArray: nodeArray,
  33948. nodeImmutable: nodeImmutable,
  33949. nodeObject: nodeObject,
  33950. nodeObjectIntent: nodeObjectIntent,
  33951. nodeObjects: nodeObjects,
  33952. nodeProxy: nodeProxy,
  33953. nodeProxyIntent: nodeProxyIntent,
  33954. normalFlat: normalFlat,
  33955. normalGeometry: normalGeometry,
  33956. normalLocal: normalLocal,
  33957. normalMap: normalMap,
  33958. normalView: normalView,
  33959. normalViewGeometry: normalViewGeometry,
  33960. normalWorld: normalWorld,
  33961. normalWorldGeometry: normalWorldGeometry,
  33962. normalize: normalize,
  33963. not: not,
  33964. notEqual: notEqual,
  33965. numWorkgroups: numWorkgroups,
  33966. objectDirection: objectDirection,
  33967. objectGroup: objectGroup,
  33968. objectPosition: objectPosition,
  33969. objectRadius: objectRadius,
  33970. objectScale: objectScale,
  33971. objectViewPosition: objectViewPosition,
  33972. objectWorldMatrix: objectWorldMatrix,
  33973. oneMinus: oneMinus,
  33974. or: or,
  33975. orthographicDepthToViewZ: orthographicDepthToViewZ,
  33976. oscSawtooth: oscSawtooth,
  33977. oscSine: oscSine,
  33978. oscSquare: oscSquare,
  33979. oscTriangle: oscTriangle,
  33980. output: output,
  33981. outputStruct: outputStruct,
  33982. overlay: overlay,
  33983. overloadingFn: overloadingFn,
  33984. packHalf2x16: packHalf2x16,
  33985. packSnorm2x16: packSnorm2x16,
  33986. packUnorm2x16: packUnorm2x16,
  33987. parabola: parabola,
  33988. parallaxDirection: parallaxDirection,
  33989. parallaxUV: parallaxUV,
  33990. parameter: parameter,
  33991. pass: pass,
  33992. passTexture: passTexture,
  33993. pcurve: pcurve,
  33994. perspectiveDepthToViewZ: perspectiveDepthToViewZ,
  33995. pmremTexture: pmremTexture,
  33996. pointShadow: pointShadow,
  33997. pointUV: pointUV,
  33998. pointWidth: pointWidth,
  33999. positionGeometry: positionGeometry,
  34000. positionLocal: positionLocal,
  34001. positionPrevious: positionPrevious,
  34002. positionView: positionView,
  34003. positionViewDirection: positionViewDirection,
  34004. positionWorld: positionWorld,
  34005. positionWorldDirection: positionWorldDirection,
  34006. posterize: posterize,
  34007. pow: pow,
  34008. pow2: pow2,
  34009. pow3: pow3,
  34010. pow4: pow4,
  34011. premultiplyAlpha: premultiplyAlpha,
  34012. property: property,
  34013. quadBroadcast: quadBroadcast,
  34014. quadSwapDiagonal: quadSwapDiagonal,
  34015. quadSwapX: quadSwapX,
  34016. quadSwapY: quadSwapY,
  34017. radians: radians,
  34018. rand: rand,
  34019. range: range,
  34020. rangeFog: rangeFog,
  34021. rangeFogFactor: rangeFogFactor,
  34022. reciprocal: reciprocal,
  34023. reference: reference,
  34024. referenceBuffer: referenceBuffer,
  34025. reflect: reflect,
  34026. reflectVector: reflectVector,
  34027. reflectView: reflectView,
  34028. reflector: reflector,
  34029. refract: refract,
  34030. refractVector: refractVector,
  34031. refractView: refractView,
  34032. reinhardToneMapping: reinhardToneMapping,
  34033. remap: remap,
  34034. remapClamp: remapClamp,
  34035. renderGroup: renderGroup,
  34036. renderOutput: renderOutput,
  34037. rendererReference: rendererReference,
  34038. replaceDefaultUV: replaceDefaultUV,
  34039. rotate: rotate,
  34040. rotateUV: rotateUV,
  34041. roughness: roughness,
  34042. round: round,
  34043. rtt: rtt,
  34044. sRGBTransferEOTF: sRGBTransferEOTF,
  34045. sRGBTransferOETF: sRGBTransferOETF,
  34046. sample: sample,
  34047. sampler: sampler,
  34048. samplerComparison: samplerComparison,
  34049. saturate: saturate,
  34050. saturation: saturation,
  34051. screen: screen,
  34052. screenCoordinate: screenCoordinate,
  34053. screenDPR: screenDPR,
  34054. screenSize: screenSize,
  34055. screenUV: screenUV,
  34056. scriptable: scriptable,
  34057. scriptableValue: scriptableValue,
  34058. select: select,
  34059. setCurrentStack: setCurrentStack,
  34060. setName: setName,
  34061. shaderStages: shaderStages,
  34062. shadow: shadow,
  34063. shadowPositionWorld: shadowPositionWorld,
  34064. shapeCircle: shapeCircle,
  34065. sharedUniformGroup: sharedUniformGroup,
  34066. sheen: sheen,
  34067. sheenRoughness: sheenRoughness,
  34068. shiftLeft: shiftLeft,
  34069. shiftRight: shiftRight,
  34070. shininess: shininess,
  34071. sign: sign,
  34072. sin: sin,
  34073. sinc: sinc,
  34074. skinning: skinning,
  34075. smoothstep: smoothstep,
  34076. smoothstepElement: smoothstepElement,
  34077. specularColor: specularColor,
  34078. specularColorBlended: specularColorBlended,
  34079. specularF90: specularF90,
  34080. spherizeUV: spherizeUV,
  34081. split: split,
  34082. spritesheetUV: spritesheetUV,
  34083. sqrt: sqrt,
  34084. stack: stack,
  34085. step: step,
  34086. stepElement: stepElement,
  34087. storage: storage,
  34088. storageBarrier: storageBarrier,
  34089. storageObject: storageObject,
  34090. storageTexture: storageTexture,
  34091. string: string,
  34092. struct: struct,
  34093. sub: sub,
  34094. subBuild: subBuild,
  34095. subgroupAdd: subgroupAdd,
  34096. subgroupAll: subgroupAll,
  34097. subgroupAnd: subgroupAnd,
  34098. subgroupAny: subgroupAny,
  34099. subgroupBallot: subgroupBallot,
  34100. subgroupBroadcast: subgroupBroadcast,
  34101. subgroupBroadcastFirst: subgroupBroadcastFirst,
  34102. subgroupElect: subgroupElect,
  34103. subgroupExclusiveAdd: subgroupExclusiveAdd,
  34104. subgroupExclusiveMul: subgroupExclusiveMul,
  34105. subgroupInclusiveAdd: subgroupInclusiveAdd,
  34106. subgroupInclusiveMul: subgroupInclusiveMul,
  34107. subgroupIndex: subgroupIndex,
  34108. subgroupMax: subgroupMax,
  34109. subgroupMin: subgroupMin,
  34110. subgroupMul: subgroupMul,
  34111. subgroupOr: subgroupOr,
  34112. subgroupShuffle: subgroupShuffle,
  34113. subgroupShuffleDown: subgroupShuffleDown,
  34114. subgroupShuffleUp: subgroupShuffleUp,
  34115. subgroupShuffleXor: subgroupShuffleXor,
  34116. subgroupSize: subgroupSize,
  34117. subgroupXor: subgroupXor,
  34118. tan: tan,
  34119. tangentGeometry: tangentGeometry,
  34120. tangentLocal: tangentLocal,
  34121. tangentView: tangentView,
  34122. tangentWorld: tangentWorld,
  34123. texture: texture,
  34124. texture3D: texture3D,
  34125. texture3DLevel: texture3DLevel,
  34126. texture3DLoad: texture3DLoad,
  34127. textureBarrier: textureBarrier,
  34128. textureBicubic: textureBicubic,
  34129. textureBicubicLevel: textureBicubicLevel,
  34130. textureCubeUV: textureCubeUV,
  34131. textureLevel: textureLevel,
  34132. textureLoad: textureLoad,
  34133. textureSize: textureSize,
  34134. textureStore: textureStore,
  34135. thickness: thickness,
  34136. time: time,
  34137. toneMapping: toneMapping,
  34138. toneMappingExposure: toneMappingExposure,
  34139. toonOutlinePass: toonOutlinePass,
  34140. transformDirection: transformDirection,
  34141. transformNormal: transformNormal,
  34142. transformNormalToView: transformNormalToView,
  34143. transformedClearcoatNormalView: transformedClearcoatNormalView,
  34144. transformedNormalView: transformedNormalView,
  34145. transformedNormalWorld: transformedNormalWorld,
  34146. transmission: transmission,
  34147. transpose: transpose,
  34148. triNoise3D: triNoise3D,
  34149. triplanarTexture: triplanarTexture,
  34150. triplanarTextures: triplanarTextures,
  34151. trunc: trunc,
  34152. uint: uint,
  34153. uintBitsToFloat: uintBitsToFloat,
  34154. uniform: uniform,
  34155. uniformArray: uniformArray,
  34156. uniformCubeTexture: uniformCubeTexture,
  34157. uniformFlow: uniformFlow,
  34158. uniformGroup: uniformGroup,
  34159. uniformTexture: uniformTexture,
  34160. unpackHalf2x16: unpackHalf2x16,
  34161. unpackNormal: unpackNormal,
  34162. unpackSnorm2x16: unpackSnorm2x16,
  34163. unpackUnorm2x16: unpackUnorm2x16,
  34164. unpremultiplyAlpha: unpremultiplyAlpha,
  34165. userData: userData,
  34166. uv: uv$1,
  34167. uvec2: uvec2,
  34168. uvec3: uvec3,
  34169. uvec4: uvec4,
  34170. varying: varying,
  34171. varyingProperty: varyingProperty,
  34172. vec2: vec2,
  34173. vec3: vec3,
  34174. vec4: vec4,
  34175. vectorComponents: vectorComponents,
  34176. velocity: velocity,
  34177. vertexColor: vertexColor,
  34178. vertexIndex: vertexIndex,
  34179. vertexStage: vertexStage,
  34180. vibrance: vibrance,
  34181. viewZToLogarithmicDepth: viewZToLogarithmicDepth,
  34182. viewZToOrthographicDepth: viewZToOrthographicDepth,
  34183. viewZToPerspectiveDepth: viewZToPerspectiveDepth,
  34184. viewport: viewport,
  34185. viewportCoordinate: viewportCoordinate,
  34186. viewportDepthTexture: viewportDepthTexture,
  34187. viewportLinearDepth: viewportLinearDepth,
  34188. viewportMipTexture: viewportMipTexture,
  34189. viewportResolution: viewportResolution,
  34190. viewportSafeUV: viewportSafeUV,
  34191. viewportSharedTexture: viewportSharedTexture,
  34192. viewportSize: viewportSize,
  34193. viewportTexture: viewportTexture,
  34194. viewportUV: viewportUV,
  34195. vogelDiskSample: vogelDiskSample,
  34196. wgsl: wgsl,
  34197. wgslFn: wgslFn,
  34198. workgroupArray: workgroupArray,
  34199. workgroupBarrier: workgroupBarrier,
  34200. workgroupId: workgroupId,
  34201. workingToColorSpace: workingToColorSpace,
  34202. xor: xor
  34203. });
  34204. const _clearColor = /*@__PURE__*/ new Color4();
  34205. /**
  34206. * This renderer module manages the background.
  34207. *
  34208. * @private
  34209. * @augments DataMap
  34210. */
  34211. class Background extends DataMap {
  34212. /**
  34213. * Constructs a new background management component.
  34214. *
  34215. * @param {Renderer} renderer - The renderer.
  34216. * @param {Nodes} nodes - Renderer component for managing nodes related logic.
  34217. */
  34218. constructor( renderer, nodes ) {
  34219. super();
  34220. /**
  34221. * The renderer.
  34222. *
  34223. * @type {Renderer}
  34224. */
  34225. this.renderer = renderer;
  34226. /**
  34227. * Renderer component for managing nodes related logic.
  34228. *
  34229. * @type {Nodes}
  34230. */
  34231. this.nodes = nodes;
  34232. }
  34233. /**
  34234. * Updates the background for the given scene. Depending on how `Scene.background`
  34235. * or `Scene.backgroundNode` are configured, this method might configure a simple clear
  34236. * or add a mesh to the render list for rendering the background as a textured plane
  34237. * or skybox.
  34238. *
  34239. * @param {Scene} scene - The scene.
  34240. * @param {RenderList} renderList - The current render list.
  34241. * @param {RenderContext} renderContext - The current render context.
  34242. */
  34243. update( scene, renderList, renderContext ) {
  34244. const renderer = this.renderer;
  34245. const background = this.nodes.getBackgroundNode( scene ) || scene.background;
  34246. let forceClear = false;
  34247. if ( background === null ) {
  34248. // no background settings, use clear color configuration from the renderer
  34249. renderer._clearColor.getRGB( _clearColor );
  34250. _clearColor.a = renderer._clearColor.a;
  34251. } else if ( background.isColor === true ) {
  34252. // background is an opaque color
  34253. background.getRGB( _clearColor );
  34254. _clearColor.a = 1;
  34255. forceClear = true;
  34256. } else if ( background.isNode === true ) {
  34257. const sceneData = this.get( scene );
  34258. const backgroundNode = background;
  34259. _clearColor.copy( renderer._clearColor );
  34260. let backgroundMesh = sceneData.backgroundMesh;
  34261. if ( backgroundMesh === undefined ) {
  34262. const backgroundMeshNode = vec4( backgroundNode ).mul( backgroundIntensity ).context( {
  34263. // @TODO: Add Texture2D support using node context
  34264. getUV: () => backgroundRotation.mul( normalWorldGeometry ),
  34265. getTextureLevel: () => backgroundBlurriness
  34266. } );
  34267. // when using orthographic cameras, we must scale the skybox sphere
  34268. // up to exceed the dimensions of the camera's viewing box.
  34269. const isOrtho = cameraProjectionMatrix.element( 3 ).element( 3 ).equal( 1.0 );
  34270. // calculate the orthographic scale
  34271. // projectionMatrix[1][1] is (1 / top). Invert it to get the height and multiply by 3.0
  34272. // (an arbitrary safety factor) to ensure the skybox is large enough to cover the corners
  34273. // of the rectangular screen
  34274. const orthoScale = div( 1.0, cameraProjectionMatrix.element( 1 ).element( 1 ) ).mul( 3.0 );
  34275. // compute vertex position
  34276. const modifiedPosition = isOrtho.select( positionLocal.mul( orthoScale ), positionLocal );
  34277. let viewProj = cameraProjectionMatrix.mul( modelViewMatrix.mul( vec4( modifiedPosition, 1.0 ) ) );
  34278. // force background to far plane so it does not occlude objects
  34279. viewProj = viewProj.setZ( viewProj.w );
  34280. const nodeMaterial = new NodeMaterial();
  34281. nodeMaterial.name = 'Background.material';
  34282. nodeMaterial.side = BackSide;
  34283. nodeMaterial.depthTest = false;
  34284. nodeMaterial.depthWrite = false;
  34285. nodeMaterial.allowOverride = false;
  34286. nodeMaterial.fog = false;
  34287. nodeMaterial.lights = false;
  34288. nodeMaterial.vertexNode = viewProj;
  34289. nodeMaterial.colorNode = backgroundMeshNode;
  34290. sceneData.backgroundMeshNode = backgroundMeshNode;
  34291. sceneData.backgroundMesh = backgroundMesh = new Mesh( new SphereGeometry( 1, 32, 32 ), nodeMaterial );
  34292. backgroundMesh.frustumCulled = false;
  34293. backgroundMesh.name = 'Background.mesh';
  34294. backgroundMesh.onBeforeRender = function ( renderer, scene, camera ) {
  34295. this.matrixWorld.copyPosition( camera.matrixWorld );
  34296. };
  34297. function onBackgroundDispose() {
  34298. background.removeEventListener( 'dispose', onBackgroundDispose );
  34299. backgroundMesh.material.dispose();
  34300. backgroundMesh.geometry.dispose();
  34301. }
  34302. background.addEventListener( 'dispose', onBackgroundDispose );
  34303. }
  34304. const backgroundCacheKey = backgroundNode.getCacheKey();
  34305. if ( sceneData.backgroundCacheKey !== backgroundCacheKey ) {
  34306. sceneData.backgroundMeshNode.node = vec4( backgroundNode ).mul( backgroundIntensity );
  34307. sceneData.backgroundMeshNode.needsUpdate = true;
  34308. backgroundMesh.material.needsUpdate = true;
  34309. sceneData.backgroundCacheKey = backgroundCacheKey;
  34310. }
  34311. renderList.unshift( backgroundMesh, backgroundMesh.geometry, backgroundMesh.material, 0, 0, null, null );
  34312. } else {
  34313. error( 'Renderer: Unsupported background configuration.', background );
  34314. }
  34315. //
  34316. const environmentBlendMode = renderer.xr.getEnvironmentBlendMode();
  34317. if ( environmentBlendMode === 'additive' ) {
  34318. _clearColor.set( 0, 0, 0, 1 );
  34319. } else if ( environmentBlendMode === 'alpha-blend' ) {
  34320. _clearColor.set( 0, 0, 0, 0 );
  34321. }
  34322. //
  34323. if ( renderer.autoClear === true || forceClear === true ) {
  34324. const clearColorValue = renderContext.clearColorValue;
  34325. clearColorValue.r = _clearColor.r;
  34326. clearColorValue.g = _clearColor.g;
  34327. clearColorValue.b = _clearColor.b;
  34328. clearColorValue.a = _clearColor.a;
  34329. // premultiply alpha
  34330. if ( renderer.backend.isWebGLBackend === true || renderer.alpha === true ) {
  34331. clearColorValue.r *= clearColorValue.a;
  34332. clearColorValue.g *= clearColorValue.a;
  34333. clearColorValue.b *= clearColorValue.a;
  34334. }
  34335. //
  34336. renderContext.depthClearValue = renderer._clearDepth;
  34337. renderContext.stencilClearValue = renderer._clearStencil;
  34338. renderContext.clearColor = renderer.autoClearColor === true;
  34339. renderContext.clearDepth = renderer.autoClearDepth === true;
  34340. renderContext.clearStencil = renderer.autoClearStencil === true;
  34341. } else {
  34342. renderContext.clearColor = false;
  34343. renderContext.clearDepth = false;
  34344. renderContext.clearStencil = false;
  34345. }
  34346. }
  34347. }
  34348. let _id$7 = 0;
  34349. /**
  34350. * A bind group represents a collection of bindings and thus a collection
  34351. * or resources. Bind groups are assigned to pipelines to provide them
  34352. * with the required resources (like uniform buffers or textures).
  34353. *
  34354. * @private
  34355. */
  34356. class BindGroup {
  34357. /**
  34358. * Constructs a new bind group.
  34359. *
  34360. * @param {string} name - The bind group's name.
  34361. * @param {Array<Binding>} bindings - An array of bindings.
  34362. * @param {number} index - The group index.
  34363. * @param {Array<Binding>} bindingsReference - An array of reference bindings.
  34364. */
  34365. constructor( name = '', bindings = [], index = 0, bindingsReference = [] ) {
  34366. /**
  34367. * The bind group's name.
  34368. *
  34369. * @type {string}
  34370. */
  34371. this.name = name;
  34372. /**
  34373. * An array of bindings.
  34374. *
  34375. * @type {Array<Binding>}
  34376. */
  34377. this.bindings = bindings;
  34378. /**
  34379. * The group index.
  34380. *
  34381. * @type {number}
  34382. */
  34383. this.index = index;
  34384. /**
  34385. * An array of reference bindings.
  34386. *
  34387. * @type {Array<Binding>}
  34388. */
  34389. this.bindingsReference = bindingsReference;
  34390. /**
  34391. * The group's ID.
  34392. *
  34393. * @type {number}
  34394. */
  34395. this.id = _id$7 ++;
  34396. }
  34397. }
  34398. /**
  34399. * This module represents the state of a node builder after it was
  34400. * used to build the nodes for a render object. The state holds the
  34401. * results of the build for further processing in the renderer.
  34402. *
  34403. * Render objects with identical cache keys share the same node builder state.
  34404. *
  34405. * @private
  34406. */
  34407. class NodeBuilderState {
  34408. /**
  34409. * Constructs a new node builder state.
  34410. *
  34411. * @param {string} vertexShader - The native vertex shader code.
  34412. * @param {string} fragmentShader - The native fragment shader code.
  34413. * @param {string} computeShader - The native compute shader code.
  34414. * @param {Array<NodeAttribute>} nodeAttributes - An array of node attributes.
  34415. * @param {Array<BindGroup>} bindings - An array of bind groups.
  34416. * @param {Array<Node>} updateNodes - An array of nodes that implement their `update()` method.
  34417. * @param {Array<Node>} updateBeforeNodes - An array of nodes that implement their `updateBefore()` method.
  34418. * @param {Array<Node>} updateAfterNodes - An array of nodes that implement their `updateAfter()` method.
  34419. * @param {NodeMaterialObserver} observer - A node material observer.
  34420. * @param {Array<Object>} transforms - An array with transform attribute objects. Only relevant when using compute shaders with WebGL 2.
  34421. */
  34422. constructor( vertexShader, fragmentShader, computeShader, nodeAttributes, bindings, updateNodes, updateBeforeNodes, updateAfterNodes, observer, transforms = [] ) {
  34423. /**
  34424. * The native vertex shader code.
  34425. *
  34426. * @type {string}
  34427. */
  34428. this.vertexShader = vertexShader;
  34429. /**
  34430. * The native fragment shader code.
  34431. *
  34432. * @type {string}
  34433. */
  34434. this.fragmentShader = fragmentShader;
  34435. /**
  34436. * The native compute shader code.
  34437. *
  34438. * @type {string}
  34439. */
  34440. this.computeShader = computeShader;
  34441. /**
  34442. * An array with transform attribute objects.
  34443. * Only relevant when using compute shaders with WebGL 2.
  34444. *
  34445. * @type {Array<Object>}
  34446. */
  34447. this.transforms = transforms;
  34448. /**
  34449. * An array of node attributes representing
  34450. * the attributes of the shaders.
  34451. *
  34452. * @type {Array<NodeAttribute>}
  34453. */
  34454. this.nodeAttributes = nodeAttributes;
  34455. /**
  34456. * An array of bind groups representing the uniform or storage
  34457. * buffers, texture or samplers of the shader.
  34458. *
  34459. * @type {Array<BindGroup>}
  34460. */
  34461. this.bindings = bindings;
  34462. /**
  34463. * An array of nodes that implement their `update()` method.
  34464. *
  34465. * @type {Array<Node>}
  34466. */
  34467. this.updateNodes = updateNodes;
  34468. /**
  34469. * An array of nodes that implement their `updateBefore()` method.
  34470. *
  34471. * @type {Array<Node>}
  34472. */
  34473. this.updateBeforeNodes = updateBeforeNodes;
  34474. /**
  34475. * An array of nodes that implement their `updateAfter()` method.
  34476. *
  34477. * @type {Array<Node>}
  34478. */
  34479. this.updateAfterNodes = updateAfterNodes;
  34480. /**
  34481. * A node material observer.
  34482. *
  34483. * @type {NodeMaterialObserver}
  34484. */
  34485. this.observer = observer;
  34486. /**
  34487. * How often this state is used by render objects.
  34488. *
  34489. * @type {number}
  34490. */
  34491. this.usedTimes = 0;
  34492. }
  34493. /**
  34494. * This method is used to create a array of bind groups based
  34495. * on the existing bind groups of this state. Shared groups are
  34496. * not cloned.
  34497. *
  34498. * @return {Array<BindGroup>} A array of bind groups.
  34499. */
  34500. createBindings() {
  34501. const bindings = [];
  34502. for ( const instanceGroup of this.bindings ) {
  34503. const shared = instanceGroup.bindings[ 0 ].groupNode.shared; // All bindings in the group must have the same groupNode.
  34504. if ( shared !== true ) {
  34505. const bindingsGroup = new BindGroup( instanceGroup.name, [], instanceGroup.index, instanceGroup.bindingsReference );
  34506. bindings.push( bindingsGroup );
  34507. for ( const instanceBinding of instanceGroup.bindings ) {
  34508. bindingsGroup.bindings.push( instanceBinding.clone() );
  34509. }
  34510. } else {
  34511. bindings.push( instanceGroup );
  34512. }
  34513. }
  34514. return bindings;
  34515. }
  34516. }
  34517. /**
  34518. * {@link NodeBuilder} is going to create instances of this class during the build process
  34519. * of nodes. They represent the final shader attributes that are going to be generated
  34520. * by the builder. Arrays of node attributes is maintained in {@link NodeBuilder#attributes}
  34521. * and {@link NodeBuilder#bufferAttributes} for this purpose.
  34522. */
  34523. class NodeAttribute {
  34524. /**
  34525. * Constructs a new node attribute.
  34526. *
  34527. * @param {string} name - The name of the attribute.
  34528. * @param {string} type - The type of the attribute.
  34529. * @param {?Node} node - An optional reference to the node.
  34530. */
  34531. constructor( name, type, node = null ) {
  34532. /**
  34533. * This flag can be used for type testing.
  34534. *
  34535. * @type {boolean}
  34536. * @readonly
  34537. * @default true
  34538. */
  34539. this.isNodeAttribute = true;
  34540. /**
  34541. * The name of the attribute.
  34542. *
  34543. * @type {string}
  34544. */
  34545. this.name = name;
  34546. /**
  34547. * The type of the attribute.
  34548. *
  34549. * @type {string}
  34550. */
  34551. this.type = type;
  34552. /**
  34553. * An optional reference to the node.
  34554. *
  34555. * @type {?Node}
  34556. * @default null
  34557. */
  34558. this.node = node;
  34559. }
  34560. }
  34561. /**
  34562. * {@link NodeBuilder} is going to create instances of this class during the build process
  34563. * of nodes. They represent the final shader uniforms that are going to be generated
  34564. * by the builder. A dictionary of node uniforms is maintained in {@link NodeBuilder#uniforms}
  34565. * for this purpose.
  34566. */
  34567. class NodeUniform {
  34568. /**
  34569. * Constructs a new node uniform.
  34570. *
  34571. * @param {string} name - The name of the uniform.
  34572. * @param {string} type - The type of the uniform.
  34573. * @param {UniformNode} node - An reference to the node.
  34574. */
  34575. constructor( name, type, node ) {
  34576. /**
  34577. * This flag can be used for type testing.
  34578. *
  34579. * @type {boolean}
  34580. * @readonly
  34581. * @default true
  34582. */
  34583. this.isNodeUniform = true;
  34584. /**
  34585. * The name of the uniform.
  34586. *
  34587. * @type {string}
  34588. */
  34589. this.name = name;
  34590. /**
  34591. * The type of the uniform.
  34592. *
  34593. * @type {string}
  34594. */
  34595. this.type = type;
  34596. /**
  34597. * An reference to the node.
  34598. *
  34599. * @type {UniformNode}
  34600. */
  34601. this.node = node;
  34602. }
  34603. /**
  34604. * The value of the uniform node.
  34605. *
  34606. * @type {any}
  34607. */
  34608. get value() {
  34609. return this.node.value;
  34610. }
  34611. set value( val ) {
  34612. this.node.value = val;
  34613. }
  34614. /**
  34615. * The id of the uniform node.
  34616. *
  34617. * @type {number}
  34618. */
  34619. get id() {
  34620. return this.node.id;
  34621. }
  34622. /**
  34623. * The uniform node's group.
  34624. *
  34625. * @type {UniformGroupNode}
  34626. */
  34627. get groupNode() {
  34628. return this.node.groupNode;
  34629. }
  34630. }
  34631. /**
  34632. * {@link NodeBuilder} is going to create instances of this class during the build process
  34633. * of nodes. They represent the final shader variables that are going to be generated
  34634. * by the builder. A dictionary of node variables is maintained in {@link NodeBuilder#vars} for
  34635. * this purpose.
  34636. */
  34637. class NodeVar {
  34638. /**
  34639. * Constructs a new node variable.
  34640. *
  34641. * @param {string} name - The name of the variable.
  34642. * @param {string} type - The type of the variable.
  34643. * @param {boolean} [readOnly=false] - The read-only flag.
  34644. * @param {?number} [count=null] - The size.
  34645. */
  34646. constructor( name, type, readOnly = false, count = null ) {
  34647. /**
  34648. * This flag can be used for type testing.
  34649. *
  34650. * @type {boolean}
  34651. * @readonly
  34652. * @default true
  34653. */
  34654. this.isNodeVar = true;
  34655. /**
  34656. * The name of the variable.
  34657. *
  34658. * @type {string}
  34659. */
  34660. this.name = name;
  34661. /**
  34662. * The type of the variable.
  34663. *
  34664. * @type {string}
  34665. */
  34666. this.type = type;
  34667. /**
  34668. * The read-only flag.
  34669. *
  34670. * @type {boolean}
  34671. */
  34672. this.readOnly = readOnly;
  34673. /**
  34674. * The size.
  34675. *
  34676. * @type {?number}
  34677. */
  34678. this.count = count;
  34679. }
  34680. }
  34681. /**
  34682. * {@link NodeBuilder} is going to create instances of this class during the build process
  34683. * of nodes. They represent the final shader varyings that are going to be generated
  34684. * by the builder. An array of node varyings is maintained in {@link NodeBuilder#varyings} for
  34685. * this purpose.
  34686. *
  34687. * @augments NodeVar
  34688. */
  34689. class NodeVarying extends NodeVar {
  34690. /**
  34691. * Constructs a new node varying.
  34692. *
  34693. * @param {string} name - The name of the varying.
  34694. * @param {string} type - The type of the varying.
  34695. * @param {?string} interpolationType - The interpolation type of the varying.
  34696. * @param {?string} interpolationSampling - The interpolation sampling type of the varying.
  34697. */
  34698. constructor( name, type, interpolationType = null, interpolationSampling = null ) {
  34699. super( name, type );
  34700. /**
  34701. * Whether this varying requires interpolation or not. This property can be used
  34702. * to check if the varying can be optimized for a variable.
  34703. *
  34704. * @type {boolean}
  34705. * @default false
  34706. */
  34707. this.needsInterpolation = false;
  34708. /**
  34709. * This flag can be used for type testing.
  34710. *
  34711. * @type {boolean}
  34712. * @readonly
  34713. * @default true
  34714. */
  34715. this.isNodeVarying = true;
  34716. /**
  34717. * The interpolation type of the varying data.
  34718. *
  34719. * @type {?string}
  34720. * @default null
  34721. */
  34722. this.interpolationType = interpolationType;
  34723. /**
  34724. * The interpolation sampling type of varying data.
  34725. *
  34726. * @type {?string}
  34727. * @default null
  34728. */
  34729. this.interpolationSampling = interpolationSampling;
  34730. }
  34731. }
  34732. /**
  34733. * {@link NodeBuilder} is going to create instances of this class during the build process
  34734. * of nodes. They represent user-defined, native shader code portions that are going to be
  34735. * injected by the builder. A dictionary of node codes is maintained in {@link NodeBuilder#codes}
  34736. * for this purpose.
  34737. */
  34738. class NodeCode {
  34739. /**
  34740. * Constructs a new code node.
  34741. *
  34742. * @param {string} name - The name of the code.
  34743. * @param {string} type - The node type.
  34744. * @param {string} [code=''] - The native shader code.
  34745. */
  34746. constructor( name, type, code = '' ) {
  34747. /**
  34748. * The name of the code.
  34749. *
  34750. * @type {string}
  34751. */
  34752. this.name = name;
  34753. /**
  34754. * The node type.
  34755. *
  34756. * @type {string}
  34757. */
  34758. this.type = type;
  34759. /**
  34760. * The native shader code.
  34761. *
  34762. * @type {string}
  34763. * @default ''
  34764. */
  34765. this.code = code;
  34766. Object.defineProperty( this, 'isNodeCode', { value: true } );
  34767. }
  34768. }
  34769. let _id$6 = 0;
  34770. /**
  34771. * This utility class is used in {@link NodeBuilder} as an internal
  34772. * cache data structure for node data.
  34773. */
  34774. class NodeCache {
  34775. /**
  34776. * Constructs a new node cache.
  34777. *
  34778. * @param {?NodeCache} parent - A reference to a parent cache.
  34779. */
  34780. constructor( parent = null ) {
  34781. /**
  34782. * The id of the cache.
  34783. *
  34784. * @type {number}
  34785. * @readonly
  34786. */
  34787. this.id = _id$6 ++;
  34788. /**
  34789. * A weak map for managing node data.
  34790. *
  34791. * @type {WeakMap<Node, Object>}
  34792. */
  34793. this.nodesData = new WeakMap();
  34794. /**
  34795. * Reference to a parent node cache.
  34796. *
  34797. * @type {?NodeCache}
  34798. * @default null
  34799. */
  34800. this.parent = parent;
  34801. }
  34802. /**
  34803. * Returns the data for the given node.
  34804. *
  34805. * @param {Node} node - The node.
  34806. * @return {?Object} The data for the node.
  34807. */
  34808. getData( node ) {
  34809. let data = this.nodesData.get( node );
  34810. if ( data === undefined && this.parent !== null ) {
  34811. data = this.parent.getData( node );
  34812. }
  34813. return data;
  34814. }
  34815. /**
  34816. * Sets the data for a given node.
  34817. *
  34818. * @param {Node} node - The node.
  34819. * @param {Object} data - The data that should be cached.
  34820. */
  34821. setData( node, data ) {
  34822. this.nodesData.set( node, data );
  34823. }
  34824. }
  34825. class StructType {
  34826. constructor( name, members ) {
  34827. this.name = name;
  34828. this.members = members;
  34829. this.output = false;
  34830. }
  34831. }
  34832. /**
  34833. * Abstract base class for uniforms.
  34834. *
  34835. * @abstract
  34836. * @private
  34837. */
  34838. class Uniform {
  34839. /**
  34840. * Constructs a new uniform.
  34841. *
  34842. * @param {string} name - The uniform's name.
  34843. * @param {any} value - The uniform's value.
  34844. */
  34845. constructor( name, value ) {
  34846. /**
  34847. * The uniform's name.
  34848. *
  34849. * @type {string}
  34850. */
  34851. this.name = name;
  34852. /**
  34853. * The uniform's value.
  34854. *
  34855. * @type {any}
  34856. */
  34857. this.value = value;
  34858. /**
  34859. * Used to build the uniform buffer according to the STD140 layout.
  34860. * Derived uniforms will set this property to a data type specific
  34861. * value.
  34862. *
  34863. * @type {number}
  34864. */
  34865. this.boundary = 0;
  34866. /**
  34867. * The item size. Derived uniforms will set this property to a data
  34868. * type specific value.
  34869. *
  34870. * @type {number}
  34871. */
  34872. this.itemSize = 0;
  34873. /**
  34874. * This property is set by {@link UniformsGroup} and marks
  34875. * the start position in the uniform buffer.
  34876. *
  34877. * @type {number}
  34878. */
  34879. this.offset = 0;
  34880. }
  34881. /**
  34882. * Sets the uniform's value.
  34883. *
  34884. * @param {any} value - The value to set.
  34885. */
  34886. setValue( value ) {
  34887. this.value = value;
  34888. }
  34889. /**
  34890. * Returns the uniform's value.
  34891. *
  34892. * @return {any} The value.
  34893. */
  34894. getValue() {
  34895. return this.value;
  34896. }
  34897. }
  34898. /**
  34899. * Represents a Number uniform.
  34900. *
  34901. * @private
  34902. * @augments Uniform
  34903. */
  34904. class NumberUniform extends Uniform {
  34905. /**
  34906. * Constructs a new Number uniform.
  34907. *
  34908. * @param {string} name - The uniform's name.
  34909. * @param {number} value - The uniform's value.
  34910. */
  34911. constructor( name, value = 0 ) {
  34912. super( name, value );
  34913. /**
  34914. * This flag can be used for type testing.
  34915. *
  34916. * @type {boolean}
  34917. * @readonly
  34918. * @default true
  34919. */
  34920. this.isNumberUniform = true;
  34921. this.boundary = 4;
  34922. this.itemSize = 1;
  34923. }
  34924. }
  34925. /**
  34926. * Represents a Vector2 uniform.
  34927. *
  34928. * @private
  34929. * @augments Uniform
  34930. */
  34931. class Vector2Uniform extends Uniform {
  34932. /**
  34933. * Constructs a new Number uniform.
  34934. *
  34935. * @param {string} name - The uniform's name.
  34936. * @param {Vector2} value - The uniform's value.
  34937. */
  34938. constructor( name, value = new Vector2() ) {
  34939. super( name, value );
  34940. /**
  34941. * This flag can be used for type testing.
  34942. *
  34943. * @type {boolean}
  34944. * @readonly
  34945. * @default true
  34946. */
  34947. this.isVector2Uniform = true;
  34948. this.boundary = 8;
  34949. this.itemSize = 2;
  34950. }
  34951. }
  34952. /**
  34953. * Represents a Vector3 uniform.
  34954. *
  34955. * @private
  34956. * @augments Uniform
  34957. */
  34958. class Vector3Uniform extends Uniform {
  34959. /**
  34960. * Constructs a new Number uniform.
  34961. *
  34962. * @param {string} name - The uniform's name.
  34963. * @param {Vector3} value - The uniform's value.
  34964. */
  34965. constructor( name, value = new Vector3() ) {
  34966. super( name, value );
  34967. /**
  34968. * This flag can be used for type testing.
  34969. *
  34970. * @type {boolean}
  34971. * @readonly
  34972. * @default true
  34973. */
  34974. this.isVector3Uniform = true;
  34975. this.boundary = 16;
  34976. this.itemSize = 3;
  34977. }
  34978. }
  34979. /**
  34980. * Represents a Vector4 uniform.
  34981. *
  34982. * @private
  34983. * @augments Uniform
  34984. */
  34985. class Vector4Uniform extends Uniform {
  34986. /**
  34987. * Constructs a new Number uniform.
  34988. *
  34989. * @param {string} name - The uniform's name.
  34990. * @param {Vector4} value - The uniform's value.
  34991. */
  34992. constructor( name, value = new Vector4() ) {
  34993. super( name, value );
  34994. /**
  34995. * This flag can be used for type testing.
  34996. *
  34997. * @type {boolean}
  34998. * @readonly
  34999. * @default true
  35000. */
  35001. this.isVector4Uniform = true;
  35002. this.boundary = 16;
  35003. this.itemSize = 4;
  35004. }
  35005. }
  35006. /**
  35007. * Represents a Color uniform.
  35008. *
  35009. * @private
  35010. * @augments Uniform
  35011. */
  35012. class ColorUniform extends Uniform {
  35013. /**
  35014. * Constructs a new Number uniform.
  35015. *
  35016. * @param {string} name - The uniform's name.
  35017. * @param {Color} value - The uniform's value.
  35018. */
  35019. constructor( name, value = new Color() ) {
  35020. super( name, value );
  35021. /**
  35022. * This flag can be used for type testing.
  35023. *
  35024. * @type {boolean}
  35025. * @readonly
  35026. * @default true
  35027. */
  35028. this.isColorUniform = true;
  35029. this.boundary = 16;
  35030. this.itemSize = 3;
  35031. }
  35032. }
  35033. /**
  35034. * Represents a Matrix2 uniform.
  35035. *
  35036. * @private
  35037. * @augments Uniform
  35038. */
  35039. class Matrix2Uniform extends Uniform {
  35040. /**
  35041. * Constructs a new Number uniform.
  35042. *
  35043. * @param {string} name - The uniform's name.
  35044. * @param {Matrix2} value - The uniform's value.
  35045. */
  35046. constructor( name, value = new Matrix2() ) {
  35047. super( name, value );
  35048. /**
  35049. * This flag can be used for type testing.
  35050. *
  35051. * @type {boolean}
  35052. * @readonly
  35053. * @default true
  35054. */
  35055. this.isMatrix2Uniform = true;
  35056. this.boundary = 8;
  35057. this.itemSize = 4;
  35058. }
  35059. }
  35060. /**
  35061. * Represents a Matrix3 uniform.
  35062. *
  35063. * @private
  35064. * @augments Uniform
  35065. */
  35066. class Matrix3Uniform extends Uniform {
  35067. /**
  35068. * Constructs a new Number uniform.
  35069. *
  35070. * @param {string} name - The uniform's name.
  35071. * @param {Matrix3} value - The uniform's value.
  35072. */
  35073. constructor( name, value = new Matrix3() ) {
  35074. super( name, value );
  35075. /**
  35076. * This flag can be used for type testing.
  35077. *
  35078. * @type {boolean}
  35079. * @readonly
  35080. * @default true
  35081. */
  35082. this.isMatrix3Uniform = true;
  35083. this.boundary = 48;
  35084. this.itemSize = 12;
  35085. }
  35086. }
  35087. /**
  35088. * Represents a Matrix4 uniform.
  35089. *
  35090. * @private
  35091. * @augments Uniform
  35092. */
  35093. class Matrix4Uniform extends Uniform {
  35094. /**
  35095. * Constructs a new Number uniform.
  35096. *
  35097. * @param {string} name - The uniform's name.
  35098. * @param {Matrix4} value - The uniform's value.
  35099. */
  35100. constructor( name, value = new Matrix4() ) {
  35101. super( name, value );
  35102. /**
  35103. * This flag can be used for type testing.
  35104. *
  35105. * @type {boolean}
  35106. * @readonly
  35107. * @default true
  35108. */
  35109. this.isMatrix4Uniform = true;
  35110. this.boundary = 64;
  35111. this.itemSize = 16;
  35112. }
  35113. }
  35114. /**
  35115. * A special form of Number uniform binding type.
  35116. * It's value is managed by a node object.
  35117. *
  35118. * @private
  35119. * @augments NumberUniform
  35120. */
  35121. class NumberNodeUniform extends NumberUniform {
  35122. /**
  35123. * Constructs a new node-based Number uniform.
  35124. *
  35125. * @param {NodeUniform} nodeUniform - The node uniform.
  35126. */
  35127. constructor( nodeUniform ) {
  35128. super( nodeUniform.name, nodeUniform.value );
  35129. /**
  35130. * The node uniform.
  35131. *
  35132. * @type {NodeUniform}
  35133. */
  35134. this.nodeUniform = nodeUniform;
  35135. }
  35136. /**
  35137. * Overwritten to return the value of the node uniform.
  35138. *
  35139. * @return {number} The value.
  35140. */
  35141. getValue() {
  35142. return this.nodeUniform.value;
  35143. }
  35144. /**
  35145. * Returns the node uniform data type.
  35146. *
  35147. * @return {string} The data type.
  35148. */
  35149. getType() {
  35150. return this.nodeUniform.type;
  35151. }
  35152. }
  35153. /**
  35154. * A special form of Vector2 uniform binding type.
  35155. * It's value is managed by a node object.
  35156. *
  35157. * @private
  35158. * @augments Vector2Uniform
  35159. */
  35160. class Vector2NodeUniform extends Vector2Uniform {
  35161. /**
  35162. * Constructs a new node-based Vector2 uniform.
  35163. *
  35164. * @param {NodeUniform} nodeUniform - The node uniform.
  35165. */
  35166. constructor( nodeUniform ) {
  35167. super( nodeUniform.name, nodeUniform.value );
  35168. /**
  35169. * The node uniform.
  35170. *
  35171. * @type {NodeUniform}
  35172. */
  35173. this.nodeUniform = nodeUniform;
  35174. }
  35175. /**
  35176. * Overwritten to return the value of the node uniform.
  35177. *
  35178. * @return {Vector2} The value.
  35179. */
  35180. getValue() {
  35181. return this.nodeUniform.value;
  35182. }
  35183. /**
  35184. * Returns the node uniform data type.
  35185. *
  35186. * @return {string} The data type.
  35187. */
  35188. getType() {
  35189. return this.nodeUniform.type;
  35190. }
  35191. }
  35192. /**
  35193. * A special form of Vector3 uniform binding type.
  35194. * It's value is managed by a node object.
  35195. *
  35196. * @private
  35197. * @augments Vector3Uniform
  35198. */
  35199. class Vector3NodeUniform extends Vector3Uniform {
  35200. /**
  35201. * Constructs a new node-based Vector3 uniform.
  35202. *
  35203. * @param {NodeUniform} nodeUniform - The node uniform.
  35204. */
  35205. constructor( nodeUniform ) {
  35206. super( nodeUniform.name, nodeUniform.value );
  35207. /**
  35208. * The node uniform.
  35209. *
  35210. * @type {NodeUniform}
  35211. */
  35212. this.nodeUniform = nodeUniform;
  35213. }
  35214. /**
  35215. * Overwritten to return the value of the node uniform.
  35216. *
  35217. * @return {Vector3} The value.
  35218. */
  35219. getValue() {
  35220. return this.nodeUniform.value;
  35221. }
  35222. /**
  35223. * Returns the node uniform data type.
  35224. *
  35225. * @return {string} The data type.
  35226. */
  35227. getType() {
  35228. return this.nodeUniform.type;
  35229. }
  35230. }
  35231. /**
  35232. * A special form of Vector4 uniform binding type.
  35233. * It's value is managed by a node object.
  35234. *
  35235. * @private
  35236. * @augments Vector4Uniform
  35237. */
  35238. class Vector4NodeUniform extends Vector4Uniform {
  35239. /**
  35240. * Constructs a new node-based Vector4 uniform.
  35241. *
  35242. * @param {NodeUniform} nodeUniform - The node uniform.
  35243. */
  35244. constructor( nodeUniform ) {
  35245. super( nodeUniform.name, nodeUniform.value );
  35246. /**
  35247. * The node uniform.
  35248. *
  35249. * @type {NodeUniform}
  35250. */
  35251. this.nodeUniform = nodeUniform;
  35252. }
  35253. /**
  35254. * Overwritten to return the value of the node uniform.
  35255. *
  35256. * @return {Vector4} The value.
  35257. */
  35258. getValue() {
  35259. return this.nodeUniform.value;
  35260. }
  35261. /**
  35262. * Returns the node uniform data type.
  35263. *
  35264. * @return {string} The data type.
  35265. */
  35266. getType() {
  35267. return this.nodeUniform.type;
  35268. }
  35269. }
  35270. /**
  35271. * A special form of Color uniform binding type.
  35272. * It's value is managed by a node object.
  35273. *
  35274. * @private
  35275. * @augments ColorUniform
  35276. */
  35277. class ColorNodeUniform extends ColorUniform {
  35278. /**
  35279. * Constructs a new node-based Color uniform.
  35280. *
  35281. * @param {NodeUniform} nodeUniform - The node uniform.
  35282. */
  35283. constructor( nodeUniform ) {
  35284. super( nodeUniform.name, nodeUniform.value );
  35285. /**
  35286. * The node uniform.
  35287. *
  35288. * @type {NodeUniform}
  35289. */
  35290. this.nodeUniform = nodeUniform;
  35291. }
  35292. /**
  35293. * Overwritten to return the value of the node uniform.
  35294. *
  35295. * @return {Color} The value.
  35296. */
  35297. getValue() {
  35298. return this.nodeUniform.value;
  35299. }
  35300. /**
  35301. * Returns the node uniform data type.
  35302. *
  35303. * @return {string} The data type.
  35304. */
  35305. getType() {
  35306. return this.nodeUniform.type;
  35307. }
  35308. }
  35309. /**
  35310. * A special form of Matrix2 uniform binding type.
  35311. * It's value is managed by a node object.
  35312. *
  35313. * @private
  35314. * @augments Matrix2Uniform
  35315. */
  35316. class Matrix2NodeUniform extends Matrix2Uniform {
  35317. /**
  35318. * Constructs a new node-based Matrix2 uniform.
  35319. *
  35320. * @param {NodeUniform} nodeUniform - The node uniform.
  35321. */
  35322. constructor( nodeUniform ) {
  35323. super( nodeUniform.name, nodeUniform.value );
  35324. /**
  35325. * The node uniform.
  35326. *
  35327. * @type {NodeUniform}
  35328. */
  35329. this.nodeUniform = nodeUniform;
  35330. }
  35331. /**
  35332. * Overwritten to return the value of the node uniform.
  35333. *
  35334. * @return {Matrix2} The value.
  35335. */
  35336. getValue() {
  35337. return this.nodeUniform.value;
  35338. }
  35339. /**
  35340. * Returns the node uniform data type.
  35341. *
  35342. * @return {string} The data type.
  35343. */
  35344. getType() {
  35345. return this.nodeUniform.type;
  35346. }
  35347. }
  35348. /**
  35349. * A special form of Matrix3 uniform binding type.
  35350. * It's value is managed by a node object.
  35351. *
  35352. * @private
  35353. * @augments Matrix3Uniform
  35354. */
  35355. class Matrix3NodeUniform extends Matrix3Uniform {
  35356. /**
  35357. * Constructs a new node-based Matrix3 uniform.
  35358. *
  35359. * @param {NodeUniform} nodeUniform - The node uniform.
  35360. */
  35361. constructor( nodeUniform ) {
  35362. super( nodeUniform.name, nodeUniform.value );
  35363. /**
  35364. * The node uniform.
  35365. *
  35366. * @type {NodeUniform}
  35367. */
  35368. this.nodeUniform = nodeUniform;
  35369. }
  35370. /**
  35371. * Overwritten to return the value of the node uniform.
  35372. *
  35373. * @return {Matrix3} The value.
  35374. */
  35375. getValue() {
  35376. return this.nodeUniform.value;
  35377. }
  35378. /**
  35379. * Returns the node uniform data type.
  35380. *
  35381. * @return {string} The data type.
  35382. */
  35383. getType() {
  35384. return this.nodeUniform.type;
  35385. }
  35386. }
  35387. /**
  35388. * A special form of Matrix4 uniform binding type.
  35389. * It's value is managed by a node object.
  35390. *
  35391. * @private
  35392. * @augments Matrix4Uniform
  35393. */
  35394. class Matrix4NodeUniform extends Matrix4Uniform {
  35395. /**
  35396. * Constructs a new node-based Matrix4 uniform.
  35397. *
  35398. * @param {NodeUniform} nodeUniform - The node uniform.
  35399. */
  35400. constructor( nodeUniform ) {
  35401. super( nodeUniform.name, nodeUniform.value );
  35402. /**
  35403. * The node uniform.
  35404. *
  35405. * @type {NodeUniform}
  35406. */
  35407. this.nodeUniform = nodeUniform;
  35408. }
  35409. /**
  35410. * Overwritten to return the value of the node uniform.
  35411. *
  35412. * @return {Matrix4} The value.
  35413. */
  35414. getValue() {
  35415. return this.nodeUniform.value;
  35416. }
  35417. /**
  35418. * Returns the node uniform data type.
  35419. *
  35420. * @return {string} The data type.
  35421. */
  35422. getType() {
  35423. return this.nodeUniform.type;
  35424. }
  35425. }
  35426. let _id$5 = 0;
  35427. const sharedNodeData = new WeakMap();
  35428. const rendererCache = new WeakMap();
  35429. const typeFromArray = new Map( [
  35430. [ Int8Array, 'int' ],
  35431. [ Int16Array, 'int' ],
  35432. [ Int32Array, 'int' ],
  35433. [ Uint8Array, 'uint' ],
  35434. [ Uint16Array, 'uint' ],
  35435. [ Uint32Array, 'uint' ],
  35436. [ Float32Array, 'float' ]
  35437. ] );
  35438. const toFloat = ( value ) => {
  35439. if ( /e/g.test( value ) ) {
  35440. return String( value ).replace( /\+/g, '' );
  35441. } else {
  35442. value = Number( value );
  35443. return value + ( value % 1 ? '' : '.0' );
  35444. }
  35445. };
  35446. /**
  35447. * Base class for builders which generate a shader program based
  35448. * on a 3D object and its node material definition.
  35449. */
  35450. class NodeBuilder {
  35451. /**
  35452. * Constructs a new node builder.
  35453. *
  35454. * @param {Object3D} object - The 3D object.
  35455. * @param {Renderer} renderer - The current renderer.
  35456. * @param {NodeParser} parser - A reference to a node parser.
  35457. */
  35458. constructor( object, renderer, parser ) {
  35459. /**
  35460. * The 3D object.
  35461. *
  35462. * @type {Object3D}
  35463. */
  35464. this.object = object;
  35465. /**
  35466. * The material of the 3D object.
  35467. *
  35468. * @type {?Material}
  35469. */
  35470. this.material = ( object && object.material ) || null;
  35471. /**
  35472. * The geometry of the 3D object.
  35473. *
  35474. * @type {?BufferGeometry}
  35475. */
  35476. this.geometry = ( object && object.geometry ) || null;
  35477. /**
  35478. * The current renderer.
  35479. *
  35480. * @type {Renderer}
  35481. */
  35482. this.renderer = renderer;
  35483. /**
  35484. * A reference to a node parser.
  35485. *
  35486. * @type {NodeParser}
  35487. */
  35488. this.parser = parser;
  35489. /**
  35490. * The scene the 3D object belongs to.
  35491. *
  35492. * @type {?Scene}
  35493. * @default null
  35494. */
  35495. this.scene = null;
  35496. /**
  35497. * The camera the 3D object is rendered with.
  35498. *
  35499. * @type {?Camera}
  35500. * @default null
  35501. */
  35502. this.camera = null;
  35503. /**
  35504. * A list of all nodes the builder is processing
  35505. * for this 3D object.
  35506. *
  35507. * @type {Array<Node>}
  35508. */
  35509. this.nodes = [];
  35510. /**
  35511. * A list of all sequential nodes.
  35512. *
  35513. * @type {Array<Node>}
  35514. */
  35515. this.sequentialNodes = [];
  35516. /**
  35517. * A list of all nodes which {@link Node#update} method should be executed.
  35518. *
  35519. * @type {Array<Node>}
  35520. */
  35521. this.updateNodes = [];
  35522. /**
  35523. * A list of all nodes which {@link Node#updateBefore} method should be executed.
  35524. *
  35525. * @type {Array<Node>}
  35526. */
  35527. this.updateBeforeNodes = [];
  35528. /**
  35529. * A list of all nodes which {@link Node#updateAfter} method should be executed.
  35530. *
  35531. * @type {Array<Node>}
  35532. */
  35533. this.updateAfterNodes = [];
  35534. /**
  35535. * A dictionary that assigns each node to a unique hash.
  35536. *
  35537. * @type {Object<number,Node>}
  35538. */
  35539. this.hashNodes = {};
  35540. /**
  35541. * A reference to a node material observer.
  35542. *
  35543. * @type {?NodeMaterialObserver}
  35544. * @default null
  35545. */
  35546. this.observer = null;
  35547. /**
  35548. * A reference to the current lights node.
  35549. *
  35550. * @type {?LightsNode}
  35551. * @default null
  35552. */
  35553. this.lightsNode = null;
  35554. /**
  35555. * A reference to the current environment node.
  35556. *
  35557. * @type {?Node}
  35558. * @default null
  35559. */
  35560. this.environmentNode = null;
  35561. /**
  35562. * A reference to the current fog node.
  35563. *
  35564. * @type {?Node}
  35565. * @default null
  35566. */
  35567. this.fogNode = null;
  35568. /**
  35569. * The current clipping context.
  35570. *
  35571. * @type {?ClippingContext}
  35572. */
  35573. this.clippingContext = null;
  35574. /**
  35575. * The generated vertex shader.
  35576. *
  35577. * @type {?string}
  35578. */
  35579. this.vertexShader = null;
  35580. /**
  35581. * The generated fragment shader.
  35582. *
  35583. * @type {?string}
  35584. */
  35585. this.fragmentShader = null;
  35586. /**
  35587. * The generated compute shader.
  35588. *
  35589. * @type {?string}
  35590. */
  35591. this.computeShader = null;
  35592. /**
  35593. * Nodes used in the primary flow of code generation.
  35594. *
  35595. * @type {Object<string,Array<Node>>}
  35596. */
  35597. this.flowNodes = { vertex: [], fragment: [], compute: [] };
  35598. /**
  35599. * Nodes code from `.flowNodes`.
  35600. *
  35601. * @type {Object<string,string>}
  35602. */
  35603. this.flowCode = { vertex: '', fragment: '', compute: '' };
  35604. /**
  35605. * This dictionary holds the node uniforms of the builder.
  35606. * The uniforms are maintained in an array for each shader stage.
  35607. *
  35608. * @type {Object}
  35609. */
  35610. this.uniforms = { vertex: [], fragment: [], compute: [], index: 0 };
  35611. /**
  35612. * This dictionary holds the output structs of the builder.
  35613. * The structs are maintained in an array for each shader stage.
  35614. *
  35615. * @type {Object}
  35616. */
  35617. this.structs = { vertex: [], fragment: [], compute: [], index: 0 };
  35618. /**
  35619. * This dictionary holds the types of the builder.
  35620. *
  35621. * @type {Object}
  35622. */
  35623. this.types = { vertex: [], fragment: [], compute: [], index: 0 };
  35624. /**
  35625. * This dictionary holds the bindings for each shader stage.
  35626. *
  35627. * @type {Object}
  35628. */
  35629. this.bindings = { vertex: {}, fragment: {}, compute: {} };
  35630. /**
  35631. * This dictionary maintains the binding indices per bind group.
  35632. *
  35633. * @type {Object}
  35634. */
  35635. this.bindingsIndexes = {};
  35636. /**
  35637. * Reference to the array of bind groups.
  35638. *
  35639. * @type {?Array<BindGroup>}
  35640. */
  35641. this.bindGroups = null;
  35642. /**
  35643. * This array holds the node attributes of this builder
  35644. * created via {@link AttributeNode}.
  35645. *
  35646. * @type {Array<NodeAttribute>}
  35647. */
  35648. this.attributes = [];
  35649. /**
  35650. * This array holds the node attributes of this builder
  35651. * created via {@link BufferAttributeNode}.
  35652. *
  35653. * @type {Array<NodeAttribute>}
  35654. */
  35655. this.bufferAttributes = [];
  35656. /**
  35657. * This array holds the node varyings of this builder.
  35658. *
  35659. * @type {Array<NodeVarying>}
  35660. */
  35661. this.varyings = [];
  35662. /**
  35663. * This dictionary holds the (native) node codes of this builder.
  35664. * The codes are maintained in an array for each shader stage.
  35665. *
  35666. * @type {Object<string,Array<NodeCode>>}
  35667. */
  35668. this.codes = {};
  35669. /**
  35670. * This dictionary holds the node variables of this builder.
  35671. * The variables are maintained in an array for each shader stage.
  35672. * This dictionary is also used to count the number of variables
  35673. * according to their type (const, vars).
  35674. *
  35675. * @type {Object<string,Array<NodeVar>|number>}
  35676. */
  35677. this.vars = {};
  35678. /**
  35679. * This dictionary holds the declarations for each shader stage.
  35680. *
  35681. * @type {Object}
  35682. */
  35683. this.declarations = {};
  35684. /**
  35685. * Current code flow.
  35686. * All code generated in this stack will be stored in `.flow`.
  35687. *
  35688. * @type {{code: string}}
  35689. */
  35690. this.flow = { code: '' };
  35691. /**
  35692. * A chain of nodes.
  35693. * Used to check recursive calls in node-graph.
  35694. *
  35695. * @type {Array<Node>}
  35696. */
  35697. this.chaining = [];
  35698. /**
  35699. * The current stack.
  35700. * This reflects the current process in the code block hierarchy,
  35701. * it is useful to know if the current process is inside a conditional for example.
  35702. *
  35703. * @type {StackNode}
  35704. */
  35705. this.stack = stack();
  35706. /**
  35707. * List of stack nodes.
  35708. * The current stack hierarchy is stored in an array.
  35709. *
  35710. * @type {Array<StackNode>}
  35711. */
  35712. this.stacks = [];
  35713. /**
  35714. * A tab value. Used for shader string generation.
  35715. *
  35716. * @type {string}
  35717. * @default '\t'
  35718. */
  35719. this.tab = '\t';
  35720. /**
  35721. * Reference to the current function node.
  35722. *
  35723. * @type {?FunctionNode}
  35724. * @default null
  35725. */
  35726. this.currentFunctionNode = null;
  35727. /**
  35728. * The builder's context.
  35729. *
  35730. * @type {Object}
  35731. */
  35732. this.context = {
  35733. material: this.material
  35734. };
  35735. /**
  35736. * The builder's cache.
  35737. *
  35738. * @type {NodeCache}
  35739. */
  35740. this.cache = new NodeCache();
  35741. /**
  35742. * Since the {@link NodeBuilder#cache} might be temporarily
  35743. * overwritten by other caches, this member retains the reference
  35744. * to the builder's own cache.
  35745. *
  35746. * @type {NodeCache}
  35747. * @default this.cache
  35748. */
  35749. this.globalCache = this.cache;
  35750. this.flowsData = new WeakMap();
  35751. /**
  35752. * The current shader stage.
  35753. *
  35754. * @type {?('vertex'|'fragment'|'compute'|'any')}
  35755. */
  35756. this.shaderStage = null;
  35757. /**
  35758. * The current build stage.
  35759. *
  35760. * @type {?('setup'|'analyze'|'generate')}
  35761. */
  35762. this.buildStage = null;
  35763. /**
  35764. * The sub-build layers.
  35765. *
  35766. * @type {Array<SubBuildNode>}
  35767. * @default []
  35768. */
  35769. this.subBuildLayers = [];
  35770. /**
  35771. * The active stack nodes.
  35772. *
  35773. * @type {Array<StackNode>}
  35774. */
  35775. this.activeStacks = [];
  35776. /**
  35777. * The current sub-build TSL function(Fn).
  35778. *
  35779. * @type {?string}
  35780. * @default null
  35781. */
  35782. this.subBuildFn = null;
  35783. /**
  35784. * The current TSL function(Fn) call node.
  35785. *
  35786. * @type {?Node}
  35787. * @default null
  35788. */
  35789. this.fnCall = null;
  35790. Object.defineProperty( this, 'id', { value: _id$5 ++ } );
  35791. }
  35792. /**
  35793. * Whether the material is opaque or not.
  35794. *
  35795. * @return {boolean} Whether the material is opaque or not.
  35796. */
  35797. isOpaque() {
  35798. const material = this.material;
  35799. return material.transparent === false && material.blending === NormalBlending && material.alphaToCoverage === false;
  35800. }
  35801. /**
  35802. * Returns the bind groups of the current renderer.
  35803. *
  35804. * @return {ChainMap} The cache.
  35805. */
  35806. getBindGroupsCache() {
  35807. let bindGroupsCache = rendererCache.get( this.renderer );
  35808. if ( bindGroupsCache === undefined ) {
  35809. bindGroupsCache = new ChainMap();
  35810. rendererCache.set( this.renderer, bindGroupsCache );
  35811. }
  35812. return bindGroupsCache;
  35813. }
  35814. /**
  35815. * Factory method for creating an instance of {@link RenderTarget} with the given
  35816. * dimensions and options.
  35817. *
  35818. * @param {number} width - The width of the render target.
  35819. * @param {number} height - The height of the render target.
  35820. * @param {Object} options - The options of the render target.
  35821. * @return {RenderTarget} The render target.
  35822. */
  35823. createRenderTarget( width, height, options ) {
  35824. return new RenderTarget( width, height, options );
  35825. }
  35826. /**
  35827. * Factory method for creating an instance of {@link CubeRenderTarget} with the given
  35828. * dimensions and options.
  35829. *
  35830. * @param {number} size - The size of the cube render target.
  35831. * @param {Object} options - The options of the cube render target.
  35832. * @return {CubeRenderTarget} The cube render target.
  35833. */
  35834. createCubeRenderTarget( size, options ) {
  35835. return new CubeRenderTarget( size, options );
  35836. }
  35837. /**
  35838. * Whether the given node is included in the internal array of nodes or not.
  35839. *
  35840. * @param {Node} node - The node to test.
  35841. * @return {boolean} Whether the given node is included in the internal array of nodes or not.
  35842. */
  35843. includes( node ) {
  35844. return this.nodes.includes( node );
  35845. }
  35846. /**
  35847. * Returns the output struct name which is required by
  35848. * {@link OutputStructNode}.
  35849. *
  35850. * @abstract
  35851. * @return {string} The name of the output struct.
  35852. */
  35853. getOutputStructName() {}
  35854. /**
  35855. * Returns a bind group for the given group name and binding.
  35856. *
  35857. * @private
  35858. * @param {string} groupName - The group name.
  35859. * @param {Array<NodeUniformsGroup>} bindings - List of bindings.
  35860. * @return {BindGroup} The bind group
  35861. */
  35862. _getBindGroup( groupName, bindings ) {
  35863. const bindGroupsCache = this.getBindGroupsCache();
  35864. //
  35865. const bindingsArray = [];
  35866. let sharedGroup = true;
  35867. for ( const binding of bindings ) {
  35868. bindingsArray.push( binding );
  35869. sharedGroup = sharedGroup && binding.groupNode.shared !== true;
  35870. }
  35871. //
  35872. let bindGroup;
  35873. if ( sharedGroup ) {
  35874. bindGroup = bindGroupsCache.get( bindingsArray );
  35875. if ( bindGroup === undefined ) {
  35876. bindGroup = new BindGroup( groupName, bindingsArray, this.bindingsIndexes[ groupName ].group, bindingsArray );
  35877. bindGroupsCache.set( bindingsArray, bindGroup );
  35878. }
  35879. } else {
  35880. bindGroup = new BindGroup( groupName, bindingsArray, this.bindingsIndexes[ groupName ].group, bindingsArray );
  35881. }
  35882. return bindGroup;
  35883. }
  35884. /**
  35885. * Returns an array of node uniform groups for the given group name and shader stage.
  35886. *
  35887. * @param {string} groupName - The group name.
  35888. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  35889. * @return {Array<NodeUniformsGroup>} The array of node uniform groups.
  35890. */
  35891. getBindGroupArray( groupName, shaderStage ) {
  35892. const bindings = this.bindings[ shaderStage ];
  35893. let bindGroup = bindings[ groupName ];
  35894. if ( bindGroup === undefined ) {
  35895. if ( this.bindingsIndexes[ groupName ] === undefined ) {
  35896. this.bindingsIndexes[ groupName ] = { binding: 0, group: Object.keys( this.bindingsIndexes ).length };
  35897. }
  35898. bindings[ groupName ] = bindGroup = [];
  35899. }
  35900. return bindGroup;
  35901. }
  35902. /**
  35903. * Returns a list bindings of all shader stages separated by groups.
  35904. *
  35905. * @return {Array<BindGroup>} The list of bindings.
  35906. */
  35907. getBindings() {
  35908. let bindingsGroups = this.bindGroups;
  35909. if ( bindingsGroups === null ) {
  35910. const groups = {};
  35911. const bindings = this.bindings;
  35912. for ( const shaderStage of shaderStages ) {
  35913. for ( const groupName in bindings[ shaderStage ] ) {
  35914. const uniforms = bindings[ shaderStage ][ groupName ];
  35915. const groupUniforms = groups[ groupName ] || ( groups[ groupName ] = [] );
  35916. groupUniforms.push( ...uniforms );
  35917. }
  35918. }
  35919. bindingsGroups = [];
  35920. for ( const groupName in groups ) {
  35921. const group = groups[ groupName ];
  35922. const bindingsGroup = this._getBindGroup( groupName, group );
  35923. bindingsGroups.push( bindingsGroup );
  35924. }
  35925. this.bindGroups = bindingsGroups;
  35926. }
  35927. return bindingsGroups;
  35928. }
  35929. /**
  35930. * Sorts the bind groups and updates {@link NodeBuilder#bindingsIndexes}.
  35931. */
  35932. sortBindingGroups() {
  35933. const bindingsGroups = this.getBindings();
  35934. bindingsGroups.sort( ( a, b ) => ( a.bindings[ 0 ].groupNode.order - b.bindings[ 0 ].groupNode.order ) );
  35935. for ( let i = 0; i < bindingsGroups.length; i ++ ) {
  35936. const bindingGroup = bindingsGroups[ i ];
  35937. this.bindingsIndexes[ bindingGroup.name ].group = i;
  35938. bindingGroup.index = i;
  35939. }
  35940. }
  35941. /**
  35942. * The builder maintains each node in a hash-based dictionary.
  35943. * This method sets the given node (value) with the given hash (key) into this dictionary.
  35944. *
  35945. * @param {Node} node - The node to add.
  35946. * @param {number} hash - The hash of the node.
  35947. */
  35948. setHashNode( node, hash ) {
  35949. this.hashNodes[ hash ] = node;
  35950. }
  35951. /**
  35952. * Adds a node to this builder.
  35953. *
  35954. * @param {Node} node - The node to add.
  35955. */
  35956. addNode( node ) {
  35957. if ( this.nodes.includes( node ) === false ) {
  35958. this.nodes.push( node );
  35959. this.setHashNode( node, node.getHash( this ) );
  35960. }
  35961. }
  35962. /**
  35963. * It is used to add Nodes that will be used as FRAME and RENDER events,
  35964. * and need to follow a certain sequence in the calls to work correctly.
  35965. * This function should be called after 'setup()' in the 'build()' process to ensure that the child nodes are processed first.
  35966. *
  35967. * @param {Node} node - The node to add.
  35968. */
  35969. addSequentialNode( node ) {
  35970. if ( this.sequentialNodes.includes( node ) === false ) {
  35971. this.sequentialNodes.push( node );
  35972. }
  35973. }
  35974. /**
  35975. * Checks the update types of nodes
  35976. */
  35977. buildUpdateNodes() {
  35978. for ( const node of this.nodes ) {
  35979. const updateType = node.getUpdateType();
  35980. if ( updateType !== NodeUpdateType.NONE ) {
  35981. this.updateNodes.push( node );
  35982. }
  35983. }
  35984. for ( const node of this.sequentialNodes ) {
  35985. const updateBeforeType = node.getUpdateBeforeType();
  35986. const updateAfterType = node.getUpdateAfterType();
  35987. if ( updateBeforeType !== NodeUpdateType.NONE ) {
  35988. this.updateBeforeNodes.push( node );
  35989. }
  35990. if ( updateAfterType !== NodeUpdateType.NONE ) {
  35991. this.updateAfterNodes.push( node );
  35992. }
  35993. }
  35994. }
  35995. /**
  35996. * A reference the current node which is the
  35997. * last node in the chain of nodes.
  35998. *
  35999. * @type {Node}
  36000. */
  36001. get currentNode() {
  36002. return this.chaining[ this.chaining.length - 1 ];
  36003. }
  36004. /**
  36005. * Whether the given texture is filtered or not.
  36006. *
  36007. * @param {Texture} texture - The texture to check.
  36008. * @return {boolean} Whether the given texture is filtered or not.
  36009. */
  36010. isFilteredTexture( texture ) {
  36011. return ( texture.magFilter === LinearFilter || texture.magFilter === LinearMipmapNearestFilter || texture.magFilter === NearestMipmapLinearFilter || texture.magFilter === LinearMipmapLinearFilter ||
  36012. texture.minFilter === LinearFilter || texture.minFilter === LinearMipmapNearestFilter || texture.minFilter === NearestMipmapLinearFilter || texture.minFilter === LinearMipmapLinearFilter );
  36013. }
  36014. /**
  36015. * Adds the given node to the internal node chain.
  36016. * This is used to check recursive calls in node-graph.
  36017. *
  36018. * @param {Node} node - The node to add.
  36019. */
  36020. addChain( node ) {
  36021. /*
  36022. if ( this.chaining.indexOf( node ) !== - 1 ) {
  36023. warn( 'Recursive node: ', node );
  36024. }
  36025. */
  36026. this.chaining.push( node );
  36027. }
  36028. /**
  36029. * Removes the given node from the internal node chain.
  36030. *
  36031. * @param {Node} node - The node to remove.
  36032. */
  36033. removeChain( node ) {
  36034. const lastChain = this.chaining.pop();
  36035. if ( lastChain !== node ) {
  36036. throw new Error( 'NodeBuilder: Invalid node chaining!' );
  36037. }
  36038. }
  36039. /**
  36040. * Returns the native shader method name for a given generic name. E.g.
  36041. * the method name `textureDimensions` matches the WGSL name but must be
  36042. * resolved to `textureSize` in GLSL.
  36043. *
  36044. * @abstract
  36045. * @param {string} method - The method name to resolve.
  36046. * @return {string} The resolved method name.
  36047. */
  36048. getMethod( method ) {
  36049. return method;
  36050. }
  36051. /**
  36052. * Returns the native snippet for a ternary operation. E.g. GLSL would output
  36053. * a ternary op as `cond ? x : y` whereas WGSL would output it as `select(y, x, cond)`
  36054. *
  36055. * @abstract
  36056. * @param {string} condSnippet - The condition determining which expression gets resolved.
  36057. * @param {string} ifSnippet - The expression to resolve to if the condition is true.
  36058. * @param {string} elseSnippet - The expression to resolve to if the condition is false.
  36059. * @return {string} The resolved method name.
  36060. */
  36061. getTernary( /* condSnippet, ifSnippet, elseSnippet*/ ) {
  36062. return null;
  36063. }
  36064. /**
  36065. * Returns a node for the given hash, see {@link NodeBuilder#setHashNode}.
  36066. *
  36067. * @param {number} hash - The hash of the node.
  36068. * @return {Node} The found node.
  36069. */
  36070. getNodeFromHash( hash ) {
  36071. return this.hashNodes[ hash ];
  36072. }
  36073. /**
  36074. * Adds the Node to a target flow so that it can generate code in the 'generate' process.
  36075. *
  36076. * @param {('vertex'|'fragment'|'compute')} shaderStage - The shader stage.
  36077. * @param {Node} node - The node to add.
  36078. * @return {Node} The node.
  36079. */
  36080. addFlow( shaderStage, node ) {
  36081. this.flowNodes[ shaderStage ].push( node );
  36082. return node;
  36083. }
  36084. /**
  36085. * Sets builder's context.
  36086. *
  36087. * @param {Object} context - The context to set.
  36088. */
  36089. setContext( context ) {
  36090. this.context = context;
  36091. }
  36092. /**
  36093. * Returns the builder's current context.
  36094. *
  36095. * @return {Object} The builder's current context.
  36096. */
  36097. getContext() {
  36098. return this.context;
  36099. }
  36100. /**
  36101. * Adds context data to the builder's current context.
  36102. *
  36103. * @param {Object} context - The context to add.
  36104. * @return {Object} The previous context.
  36105. */
  36106. addContext( context ) {
  36107. const previousContext = this.getContext();
  36108. this.setContext( { ...this.context, ...context } );
  36109. return previousContext;
  36110. }
  36111. /**
  36112. * Gets a context used in shader construction that can be shared across different materials.
  36113. * This is necessary since the renderer cache can reuse shaders generated in one material and use them in another.
  36114. *
  36115. * @return {Object} The builder's current context without material.
  36116. */
  36117. getSharedContext() {
  36118. const context = { ...this.context };
  36119. delete context.material;
  36120. delete context.getUV;
  36121. delete context.getOutput;
  36122. delete context.getTextureLevel;
  36123. delete context.getAO;
  36124. delete context.getShadow;
  36125. return context;
  36126. }
  36127. /**
  36128. * Sets builder's cache.
  36129. *
  36130. * @param {NodeCache} cache - The cache to set.
  36131. */
  36132. setCache( cache ) {
  36133. this.cache = cache;
  36134. }
  36135. /**
  36136. * Returns the builder's current cache.
  36137. *
  36138. * @return {NodeCache} The builder's current cache.
  36139. */
  36140. getCache() {
  36141. return this.cache;
  36142. }
  36143. /**
  36144. * Returns a cache for the given node.
  36145. *
  36146. * @param {Node} node - The node.
  36147. * @param {boolean} [parent=true] - Whether this node refers to a shared parent cache or not.
  36148. * @return {NodeCache} The cache.
  36149. */
  36150. getCacheFromNode( node, parent = true ) {
  36151. const data = this.getDataFromNode( node );
  36152. if ( data.cache === undefined ) data.cache = new NodeCache( parent ? this.getCache() : null );
  36153. return data.cache;
  36154. }
  36155. /**
  36156. * Whether the requested feature is available or not.
  36157. *
  36158. * @abstract
  36159. * @param {string} name - The requested feature.
  36160. * @return {boolean} Whether the requested feature is supported or not.
  36161. */
  36162. isAvailable( /*name*/ ) {
  36163. return false;
  36164. }
  36165. /**
  36166. * Returns the vertexIndex input variable as a native shader string.
  36167. *
  36168. * @abstract
  36169. * @return {string} The instanceIndex shader string.
  36170. */
  36171. getVertexIndex() {
  36172. warn( 'Abstract function.' );
  36173. }
  36174. /**
  36175. * Contextually returns either the vertex stage instance index builtin
  36176. * or the linearized index of an compute invocation within a grid of workgroups.
  36177. *
  36178. * @abstract
  36179. * @return {string} The instanceIndex shader string.
  36180. */
  36181. getInstanceIndex() {
  36182. warn( 'Abstract function.' );
  36183. }
  36184. /**
  36185. * Returns the drawIndex input variable as a native shader string.
  36186. * Only relevant for WebGL and its `WEBGL_multi_draw` extension.
  36187. *
  36188. * @abstract
  36189. * @return {?string} The drawIndex shader string.
  36190. */
  36191. getDrawIndex() {
  36192. warn( 'Abstract function.' );
  36193. }
  36194. /**
  36195. * Returns the frontFacing input variable as a native shader string.
  36196. *
  36197. * @abstract
  36198. * @return {string} The frontFacing shader string.
  36199. */
  36200. getFrontFacing() {
  36201. warn( 'Abstract function.' );
  36202. }
  36203. /**
  36204. * Returns the fragCoord input variable as a native shader string.
  36205. *
  36206. * @abstract
  36207. * @return {string} The fragCoord shader string.
  36208. */
  36209. getFragCoord() {
  36210. warn( 'Abstract function.' );
  36211. }
  36212. /**
  36213. * Whether to flip texture data along its vertical axis or not. WebGL needs
  36214. * this method evaluate to `true`, WebGPU to `false`.
  36215. *
  36216. * @abstract
  36217. * @return {boolean} Whether to flip texture data along its vertical axis or not.
  36218. */
  36219. isFlipY() {
  36220. return false;
  36221. }
  36222. /**
  36223. * Calling this method increases the usage count for the given node by one.
  36224. *
  36225. * @param {Node} node - The node to increase the usage count for.
  36226. * @return {number} The updated usage count.
  36227. */
  36228. increaseUsage( node ) {
  36229. const nodeData = this.getDataFromNode( node );
  36230. nodeData.usageCount = nodeData.usageCount === undefined ? 1 : nodeData.usageCount + 1;
  36231. return nodeData.usageCount;
  36232. }
  36233. /**
  36234. * Generates a texture sample shader string for the given texture data.
  36235. *
  36236. * @abstract
  36237. * @param {Texture} texture - The texture.
  36238. * @param {string} textureProperty - The texture property name.
  36239. * @param {string} uvSnippet - Snippet defining the texture coordinates.
  36240. * @return {string} The generated shader string.
  36241. */
  36242. generateTexture( /* texture, textureProperty, uvSnippet */ ) {
  36243. warn( 'Abstract function.' );
  36244. }
  36245. /**
  36246. * Generates a texture LOD shader string for the given texture data.
  36247. *
  36248. * @abstract
  36249. * @param {Texture} texture - The texture.
  36250. * @param {string} textureProperty - The texture property name.
  36251. * @param {string} uvSnippet - Snippet defining the texture coordinates.
  36252. * @param {?string} depthSnippet - Snippet defining the 0-based texture array index to sample.
  36253. * @param {string} levelSnippet - Snippet defining the mip level.
  36254. * @return {string} The generated shader string.
  36255. */
  36256. generateTextureLod( /* texture, textureProperty, uvSnippet, depthSnippet, levelSnippet */ ) {
  36257. warn( 'Abstract function.' );
  36258. }
  36259. /**
  36260. * Generates the array declaration string.
  36261. *
  36262. * @param {string} type - The type.
  36263. * @param {?number} [count] - The count.
  36264. * @return {string} The generated value as a shader string.
  36265. */
  36266. generateArrayDeclaration( type, count ) {
  36267. return this.getType( type ) + '[ ' + count + ' ]';
  36268. }
  36269. /**
  36270. * Generates the array shader string for the given type and value.
  36271. *
  36272. * @param {string} type - The type.
  36273. * @param {?number} [count] - The count.
  36274. * @param {?Array<Node>} [values=null] - The default values.
  36275. * @return {string} The generated value as a shader string.
  36276. */
  36277. generateArray( type, count, values = null ) {
  36278. let snippet = this.generateArrayDeclaration( type, count ) + '( ';
  36279. for ( let i = 0; i < count; i ++ ) {
  36280. const value = values ? values[ i ] : null;
  36281. if ( value !== null ) {
  36282. snippet += value.build( this, type );
  36283. } else {
  36284. snippet += this.generateConst( type );
  36285. }
  36286. if ( i < count - 1 ) snippet += ', ';
  36287. }
  36288. snippet += ' )';
  36289. return snippet;
  36290. }
  36291. /**
  36292. * Generates the struct shader string.
  36293. *
  36294. * @param {string} type - The type.
  36295. * @param {Array<Object>} [membersLayout] - The count.
  36296. * @param {?Array<Node>} [values=null] - The default values.
  36297. * @return {string} The generated value as a shader string.
  36298. */
  36299. generateStruct( type, membersLayout, values = null ) {
  36300. const snippets = [];
  36301. for ( const member of membersLayout ) {
  36302. const { name, type } = member;
  36303. if ( values && values[ name ] && values[ name ].isNode ) {
  36304. snippets.push( values[ name ].build( this, type ) );
  36305. } else {
  36306. snippets.push( this.generateConst( type ) );
  36307. }
  36308. }
  36309. return type + '( ' + snippets.join( ', ' ) + ' )';
  36310. }
  36311. /**
  36312. * Generates the shader string for the given type and value.
  36313. *
  36314. * @param {string} type - The type.
  36315. * @param {?any} [value=null] - The value.
  36316. * @return {string} The generated value as a shader string.
  36317. */
  36318. generateConst( type, value = null ) {
  36319. if ( value === null ) {
  36320. if ( type === 'float' || type === 'int' || type === 'uint' ) value = 0;
  36321. else if ( type === 'bool' ) value = false;
  36322. else if ( type === 'color' ) value = new Color();
  36323. else if ( type === 'vec2' || type === 'uvec2' || type === 'ivec2' ) value = new Vector2();
  36324. else if ( type === 'vec3' || type === 'uvec3' || type === 'ivec3' ) value = new Vector3();
  36325. else if ( type === 'vec4' || type === 'uvec4' || type === 'ivec4' ) value = new Vector4();
  36326. }
  36327. if ( type === 'float' ) return toFloat( value );
  36328. if ( type === 'int' ) return `${ Math.round( value ) }`;
  36329. if ( type === 'uint' ) return value >= 0 ? `${ Math.round( value ) }u` : '0u';
  36330. if ( type === 'bool' ) return value ? 'true' : 'false';
  36331. if ( type === 'color' ) return `${ this.getType( 'vec3' ) }( ${ toFloat( value.r ) }, ${ toFloat( value.g ) }, ${ toFloat( value.b ) } )`;
  36332. const typeLength = this.getTypeLength( type );
  36333. const componentType = this.getComponentType( type );
  36334. const generateConst = value => this.generateConst( componentType, value );
  36335. if ( typeLength === 2 ) {
  36336. return `${ this.getType( type ) }( ${ generateConst( value.x ) }, ${ generateConst( value.y ) } )`;
  36337. } else if ( typeLength === 3 ) {
  36338. return `${ this.getType( type ) }( ${ generateConst( value.x ) }, ${ generateConst( value.y ) }, ${ generateConst( value.z ) } )`;
  36339. } else if ( typeLength === 4 && type !== 'mat2' ) {
  36340. return `${ this.getType( type ) }( ${ generateConst( value.x ) }, ${ generateConst( value.y ) }, ${ generateConst( value.z ) }, ${ generateConst( value.w ) } )`;
  36341. } else if ( typeLength >= 4 && value && ( value.isMatrix2 || value.isMatrix3 || value.isMatrix4 ) ) {
  36342. return `${ this.getType( type ) }( ${ value.elements.map( generateConst ).join( ', ' ) } )`;
  36343. } else if ( typeLength > 4 ) {
  36344. return `${ this.getType( type ) }()`;
  36345. }
  36346. throw new Error( `NodeBuilder: Type '${type}' not found in generate constant attempt.` );
  36347. }
  36348. /**
  36349. * It might be necessary to convert certain data types to different ones
  36350. * so this method can be used to hide the conversion.
  36351. *
  36352. * @param {string} type - The type.
  36353. * @return {string} The updated type.
  36354. */
  36355. getType( type ) {
  36356. if ( type === 'color' ) return 'vec3';
  36357. return type;
  36358. }
  36359. /**
  36360. * Whether the given attribute name is defined in the geometry or not.
  36361. *
  36362. * @param {string} name - The attribute name.
  36363. * @return {boolean} Whether the given attribute name is defined in the geometry.
  36364. */
  36365. hasGeometryAttribute( name ) {
  36366. return this.geometry && this.geometry.getAttribute( name ) !== undefined;
  36367. }
  36368. /**
  36369. * Returns a node attribute for the given name and type.
  36370. *
  36371. * @param {string} name - The attribute's name.
  36372. * @param {string} type - The attribute's type.
  36373. * @return {NodeAttribute} The node attribute.
  36374. */
  36375. getAttribute( name, type ) {
  36376. const attributes = this.attributes;
  36377. // find attribute
  36378. for ( const attribute of attributes ) {
  36379. if ( attribute.name === name ) {
  36380. return attribute;
  36381. }
  36382. }
  36383. // create a new if no exist
  36384. const attribute = new NodeAttribute( name, type );
  36385. this.registerDeclaration( attribute );
  36386. attributes.push( attribute );
  36387. return attribute;
  36388. }
  36389. /**
  36390. * Returns for the given node and shader stage the property name for the shader.
  36391. *
  36392. * @param {Node} node - The node.
  36393. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  36394. * @return {string} The property name.
  36395. */
  36396. getPropertyName( node/*, shaderStage*/ ) {
  36397. return node.name;
  36398. }
  36399. /**
  36400. * Whether the given type is a vector type or not.
  36401. *
  36402. * @param {string} type - The type to check.
  36403. * @return {boolean} Whether the given type is a vector type or not.
  36404. */
  36405. isVector( type ) {
  36406. return /vec\d/.test( type );
  36407. }
  36408. /**
  36409. * Whether the given type is a matrix type or not.
  36410. *
  36411. * @param {string} type - The type to check.
  36412. * @return {boolean} Whether the given type is a matrix type or not.
  36413. */
  36414. isMatrix( type ) {
  36415. return /mat\d/.test( type );
  36416. }
  36417. /**
  36418. * Whether the given type is a reference type or not.
  36419. *
  36420. * @param {string} type - The type to check.
  36421. * @return {boolean} Whether the given type is a reference type or not.
  36422. */
  36423. isReference( type ) {
  36424. return type === 'void' || type === 'property' || type === 'sampler' || type === 'samplerComparison' || type === 'texture' || type === 'cubeTexture' || type === 'storageTexture' || type === 'depthTexture' || type === 'texture3D';
  36425. }
  36426. /**
  36427. * Checks if the given texture requires a manual conversion to the working color space.
  36428. *
  36429. * @abstract
  36430. * @param {Texture} texture - The texture to check.
  36431. * @return {boolean} Whether the given texture requires a conversion to working color space or not.
  36432. */
  36433. needsToWorkingColorSpace( /*texture*/ ) {
  36434. return false;
  36435. }
  36436. /**
  36437. * Returns the component type of a given texture.
  36438. *
  36439. * @param {Texture} texture - The texture.
  36440. * @return {string} The component type.
  36441. */
  36442. getComponentTypeFromTexture( texture ) {
  36443. const type = texture.type;
  36444. if ( texture.isDataTexture ) {
  36445. if ( type === IntType ) return 'int';
  36446. if ( type === UnsignedIntType ) return 'uint';
  36447. }
  36448. return 'float';
  36449. }
  36450. /**
  36451. * Returns the element type for a given type.
  36452. *
  36453. * @param {string} type - The type.
  36454. * @return {string} The element type.
  36455. */
  36456. getElementType( type ) {
  36457. if ( type === 'mat2' ) return 'vec2';
  36458. if ( type === 'mat3' ) return 'vec3';
  36459. if ( type === 'mat4' ) return 'vec4';
  36460. return this.getComponentType( type );
  36461. }
  36462. /**
  36463. * Returns the component type for a given type.
  36464. *
  36465. * @param {string} type - The type.
  36466. * @return {string} The component type.
  36467. */
  36468. getComponentType( type ) {
  36469. type = this.getVectorType( type );
  36470. if ( type === 'float' || type === 'bool' || type === 'int' || type === 'uint' ) return type;
  36471. const componentType = /(b|i|u|)(vec|mat)([2-4])/.exec( type );
  36472. if ( componentType === null ) return null;
  36473. if ( componentType[ 1 ] === 'b' ) return 'bool';
  36474. if ( componentType[ 1 ] === 'i' ) return 'int';
  36475. if ( componentType[ 1 ] === 'u' ) return 'uint';
  36476. return 'float';
  36477. }
  36478. /**
  36479. * Returns the vector type for a given type.
  36480. *
  36481. * @param {string} type - The type.
  36482. * @return {string} The vector type.
  36483. */
  36484. getVectorType( type ) {
  36485. if ( type === 'color' ) return 'vec3';
  36486. if ( type === 'texture' || type === 'cubeTexture' || type === 'storageTexture' || type === 'texture3D' ) return 'vec4';
  36487. return type;
  36488. }
  36489. /**
  36490. * Returns the data type for the given the length and component type.
  36491. *
  36492. * @param {number} length - The length.
  36493. * @param {string} [componentType='float'] - The component type.
  36494. * @return {string} The type.
  36495. */
  36496. getTypeFromLength( length, componentType = 'float' ) {
  36497. if ( length === 1 ) return componentType;
  36498. let baseType = getTypeFromLength( length );
  36499. const prefix = componentType === 'float' ? '' : componentType[ 0 ];
  36500. // fix edge case for mat2x2 being same size as vec4
  36501. if ( /mat2/.test( componentType ) === true ) {
  36502. baseType = baseType.replace( 'vec', 'mat' );
  36503. }
  36504. return prefix + baseType;
  36505. }
  36506. /**
  36507. * Returns the type for a given typed array.
  36508. *
  36509. * @param {TypedArray} array - The typed array.
  36510. * @return {string} The type.
  36511. */
  36512. getTypeFromArray( array ) {
  36513. return typeFromArray.get( array.constructor );
  36514. }
  36515. /**
  36516. * Returns the type is an integer type.
  36517. *
  36518. * @param {string} type - The type.
  36519. * @return {boolean} Whether the type is an integer type or not.
  36520. */
  36521. isInteger( type ) {
  36522. return /int|uint|(i|u)vec/.test( type );
  36523. }
  36524. /**
  36525. * Returns the type for a given buffer attribute.
  36526. *
  36527. * @param {BufferAttribute} attribute - The buffer attribute.
  36528. * @return {string} The type.
  36529. */
  36530. getTypeFromAttribute( attribute ) {
  36531. let dataAttribute = attribute;
  36532. if ( attribute.isInterleavedBufferAttribute ) dataAttribute = attribute.data;
  36533. const array = dataAttribute.array;
  36534. const itemSize = attribute.itemSize;
  36535. const normalized = attribute.normalized;
  36536. let arrayType;
  36537. if ( ! ( attribute instanceof Float16BufferAttribute ) && normalized !== true ) {
  36538. arrayType = this.getTypeFromArray( array );
  36539. }
  36540. return this.getTypeFromLength( itemSize, arrayType );
  36541. }
  36542. /**
  36543. * Returns the length for the given data type.
  36544. *
  36545. * @param {string} type - The data type.
  36546. * @return {number} The length.
  36547. */
  36548. getTypeLength( type ) {
  36549. const vecType = this.getVectorType( type );
  36550. const vecNum = /vec([2-4])/.exec( vecType );
  36551. if ( vecNum !== null ) return Number( vecNum[ 1 ] );
  36552. if ( vecType === 'float' || vecType === 'bool' || vecType === 'int' || vecType === 'uint' ) return 1;
  36553. if ( /mat2/.test( type ) === true ) return 4;
  36554. if ( /mat3/.test( type ) === true ) return 9;
  36555. if ( /mat4/.test( type ) === true ) return 16;
  36556. return 0;
  36557. }
  36558. /**
  36559. * Returns the vector type for a given matrix type.
  36560. *
  36561. * @param {string} type - The matrix type.
  36562. * @return {string} The vector type.
  36563. */
  36564. getVectorFromMatrix( type ) {
  36565. return type.replace( 'mat', 'vec' );
  36566. }
  36567. /**
  36568. * For a given type this method changes the component type to the
  36569. * given value. E.g. `vec4` should be changed to the new component type
  36570. * `uint` which results in `uvec4`.
  36571. *
  36572. * @param {string} type - The type.
  36573. * @param {string} newComponentType - The new component type.
  36574. * @return {string} The new type.
  36575. */
  36576. changeComponentType( type, newComponentType ) {
  36577. return this.getTypeFromLength( this.getTypeLength( type ), newComponentType );
  36578. }
  36579. /**
  36580. * Returns the integer type pendant for the given type.
  36581. *
  36582. * @param {string} type - The type.
  36583. * @return {string} The integer type.
  36584. */
  36585. getIntegerType( type ) {
  36586. const componentType = this.getComponentType( type );
  36587. if ( componentType === 'int' || componentType === 'uint' ) return type;
  36588. return this.changeComponentType( type, 'int' );
  36589. }
  36590. /**
  36591. * Adds an active stack to the internal stack.
  36592. *
  36593. * @param {StackNode} stack - The stack node to add.
  36594. */
  36595. setActiveStack( stack ) {
  36596. this.activeStacks.push( stack );
  36597. }
  36598. /**
  36599. * Removes the active stack from the internal stack.
  36600. *
  36601. * @param {StackNode} stack - The stack node to remove.
  36602. */
  36603. removeActiveStack( stack ) {
  36604. if ( this.activeStacks[ this.activeStacks.length - 1 ] === stack ) {
  36605. this.activeStacks.pop();
  36606. } else {
  36607. throw new Error( 'NodeBuilder: Invalid active stack removal.' );
  36608. }
  36609. }
  36610. /**
  36611. * Returns the active stack.
  36612. *
  36613. * @return {StackNode} The active stack.
  36614. */
  36615. getActiveStack() {
  36616. return this.activeStacks[ this.activeStacks.length - 1 ];
  36617. }
  36618. /**
  36619. * Returns the base stack.
  36620. *
  36621. * @return {StackNode} The base stack.
  36622. */
  36623. getBaseStack() {
  36624. return this.activeStacks[ 0 ];
  36625. }
  36626. /**
  36627. * Adds a stack node to the internal stack.
  36628. *
  36629. * @return {StackNode} The added stack node.
  36630. */
  36631. addStack() {
  36632. this.stack = stack( this.stack );
  36633. const previousStack = getCurrentStack();
  36634. this.stacks.push( previousStack );
  36635. setCurrentStack( this.stack );
  36636. return this.stack;
  36637. }
  36638. /**
  36639. * Removes the last stack node from the internal stack.
  36640. *
  36641. * @return {StackNode} The removed stack node.
  36642. */
  36643. removeStack() {
  36644. const lastStack = this.stack;
  36645. for ( const node of lastStack.nodes ) {
  36646. const nodeData = this.getDataFromNode( node );
  36647. nodeData.stack = lastStack;
  36648. }
  36649. this.stack = lastStack.parent;
  36650. setCurrentStack( this.stacks.pop() );
  36651. return lastStack;
  36652. }
  36653. /**
  36654. * The builder maintains (cached) data for each node during the building process. This method
  36655. * can be used to get these data for a specific shader stage and cache.
  36656. *
  36657. * @param {Node} node - The node to get the data for.
  36658. * @param {('vertex'|'fragment'|'compute'|'any')} [shaderStage=this.shaderStage] - The shader stage.
  36659. * @param {?NodeCache} cache - An optional cache.
  36660. * @return {Object} The node data.
  36661. */
  36662. getDataFromNode( node, shaderStage = this.shaderStage, cache = null ) {
  36663. cache = cache === null ? ( node.isGlobal( this ) ? this.globalCache : this.cache ) : cache;
  36664. let nodeData = cache.getData( node );
  36665. if ( nodeData === undefined ) {
  36666. nodeData = {};
  36667. cache.setData( node, nodeData );
  36668. }
  36669. if ( nodeData[ shaderStage ] === undefined ) nodeData[ shaderStage ] = {};
  36670. //
  36671. let data = nodeData[ shaderStage ];
  36672. const subBuilds = nodeData.any ? nodeData.any.subBuilds : null;
  36673. const subBuild = this.getClosestSubBuild( subBuilds );
  36674. if ( subBuild ) {
  36675. if ( data.subBuildsCache === undefined ) data.subBuildsCache = {};
  36676. data = data.subBuildsCache[ subBuild ] || ( data.subBuildsCache[ subBuild ] = {} );
  36677. data.subBuilds = subBuilds;
  36678. }
  36679. return data;
  36680. }
  36681. /**
  36682. * Returns the properties for the given node and shader stage.
  36683. *
  36684. * Properties are typically used within a build stage to reference a node's
  36685. * child node or nodes manually assigned to the properties in a separate build stage.
  36686. * A typical usage pattern for defining nodes manually would be assigning dependency nodes
  36687. * to the current node's properties in the setup stage and building those properties in the generate stage.
  36688. *
  36689. * @param {Node} node - The node to get the properties for.
  36690. * @param {('vertex'|'fragment'|'compute'|'any')} [shaderStage='any'] - The shader stage.
  36691. * @return {Object} The node properties.
  36692. */
  36693. getNodeProperties( node, shaderStage = 'any' ) {
  36694. const nodeData = this.getDataFromNode( node, shaderStage );
  36695. return nodeData.properties || ( nodeData.properties = { outputNode: null } );
  36696. }
  36697. /**
  36698. * Returns an instance of {@link NodeAttribute} for the given buffer attribute node.
  36699. *
  36700. * @param {BufferAttributeNode} node - The buffer attribute node.
  36701. * @param {string} type - The node type.
  36702. * @return {NodeAttribute} The node attribute.
  36703. */
  36704. getBufferAttributeFromNode( node, type ) {
  36705. const nodeData = this.getDataFromNode( node, 'vertex' );
  36706. let bufferAttribute = nodeData.bufferAttribute;
  36707. if ( bufferAttribute === undefined ) {
  36708. const index = this.uniforms.index ++;
  36709. bufferAttribute = new NodeAttribute( 'nodeAttribute' + index, type, node );
  36710. this.bufferAttributes.push( bufferAttribute );
  36711. nodeData.bufferAttribute = bufferAttribute;
  36712. }
  36713. return bufferAttribute;
  36714. }
  36715. /**
  36716. * Returns an instance of {@link StructType} for the given struct name and shader stage
  36717. * or null if not found.
  36718. *
  36719. * @param {string} name - The name of the struct.
  36720. * @param {('vertex'|'fragment'|'compute'|'any')} [shaderStage=this.shaderStage] - The shader stage.
  36721. * @return {?StructType} The struct type or null if not found.
  36722. */
  36723. getStructTypeNode( name, shaderStage = this.shaderStage ) {
  36724. return this.types[ shaderStage ][ name ] || null;
  36725. }
  36726. /**
  36727. * Returns an instance of {@link StructType} for the given output struct node.
  36728. *
  36729. * @param {OutputStructNode} node - The output struct node.
  36730. * @param {Array<Object>} membersLayout - The output struct types.
  36731. * @param {?string} [name=null] - The name of the struct.
  36732. * @param {('vertex'|'fragment'|'compute'|'any')} [shaderStage=this.shaderStage] - The shader stage.
  36733. * @return {StructType} The struct type attribute.
  36734. */
  36735. getStructTypeFromNode( node, membersLayout, name = null, shaderStage = this.shaderStage ) {
  36736. const nodeData = this.getDataFromNode( node, shaderStage, this.globalCache );
  36737. let structType = nodeData.structType;
  36738. if ( structType === undefined ) {
  36739. const index = this.structs.index ++;
  36740. if ( name === null ) name = 'StructType' + index;
  36741. structType = new StructType( name, membersLayout );
  36742. this.structs[ shaderStage ].push( structType );
  36743. this.types[ shaderStage ][ name ] = node;
  36744. nodeData.structType = structType;
  36745. }
  36746. return structType;
  36747. }
  36748. /**
  36749. * Returns an instance of {@link StructType} for the given output struct node.
  36750. *
  36751. * @param {OutputStructNode} node - The output struct node.
  36752. * @param {Array<Object>} membersLayout - The output struct types.
  36753. * @return {StructType} The struct type attribute.
  36754. */
  36755. getOutputStructTypeFromNode( node, membersLayout ) {
  36756. const structType = this.getStructTypeFromNode( node, membersLayout, 'OutputType', 'fragment' );
  36757. structType.output = true;
  36758. return structType;
  36759. }
  36760. /**
  36761. * Returns an instance of {@link NodeUniform} for the given uniform node.
  36762. *
  36763. * @param {UniformNode} node - The uniform node.
  36764. * @param {string} type - The uniform type.
  36765. * @param {('vertex'|'fragment'|'compute'|'any')} [shaderStage=this.shaderStage] - The shader stage.
  36766. * @param {?string} name - The name of the uniform.
  36767. * @return {NodeUniform} The node uniform.
  36768. */
  36769. getUniformFromNode( node, type, shaderStage = this.shaderStage, name = null ) {
  36770. const nodeData = this.getDataFromNode( node, shaderStage, this.globalCache );
  36771. let nodeUniform = nodeData.uniform;
  36772. if ( nodeUniform === undefined ) {
  36773. const index = this.uniforms.index ++;
  36774. nodeUniform = new NodeUniform( name || ( 'nodeUniform' + index ), type, node );
  36775. this.uniforms[ shaderStage ].push( nodeUniform );
  36776. this.registerDeclaration( nodeUniform );
  36777. nodeData.uniform = nodeUniform;
  36778. }
  36779. return nodeUniform;
  36780. }
  36781. /**
  36782. * Returns an instance of {@link NodeVar} for the given variable node.
  36783. *
  36784. * @param {VarNode} node - The variable node.
  36785. * @param {?string} name - The variable's name.
  36786. * @param {string} [type=node.getNodeType( this )] - The variable's type.
  36787. * @param {('vertex'|'fragment'|'compute'|'any')} [shaderStage=this.shaderStage] - The shader stage.
  36788. * @param {boolean} [readOnly=false] - Whether the variable is read-only or not.
  36789. *
  36790. * @return {NodeVar} The node variable.
  36791. */
  36792. getVarFromNode( node, name = null, type = node.getNodeType( this ), shaderStage = this.shaderStage, readOnly = false ) {
  36793. const nodeData = this.getDataFromNode( node, shaderStage );
  36794. const subBuildVariable = this.getSubBuildProperty( 'variable', nodeData.subBuilds );
  36795. let nodeVar = nodeData[ subBuildVariable ];
  36796. if ( nodeVar === undefined ) {
  36797. const idNS = readOnly ? '_const' : '_var';
  36798. const vars = this.vars[ shaderStage ] || ( this.vars[ shaderStage ] = [] );
  36799. const id = this.vars[ idNS ] || ( this.vars[ idNS ] = 0 );
  36800. if ( name === null ) {
  36801. name = ( readOnly ? 'nodeConst' : 'nodeVar' ) + id;
  36802. this.vars[ idNS ] ++;
  36803. }
  36804. //
  36805. if ( subBuildVariable !== 'variable' ) {
  36806. name = this.getSubBuildProperty( name, nodeData.subBuilds );
  36807. }
  36808. //
  36809. const count = node.getArrayCount( this );
  36810. nodeVar = new NodeVar( name, type, readOnly, count );
  36811. if ( ! readOnly ) {
  36812. vars.push( nodeVar );
  36813. }
  36814. this.registerDeclaration( nodeVar );
  36815. nodeData[ subBuildVariable ] = nodeVar;
  36816. }
  36817. return nodeVar;
  36818. }
  36819. /**
  36820. * Returns whether a Node or its flow is deterministic, useful for use in `const`.
  36821. *
  36822. * @param {Node} node - The varying node.
  36823. * @return {boolean} Returns true if deterministic.
  36824. */
  36825. isDeterministic( node ) {
  36826. if ( node.isMathNode ) {
  36827. return this.isDeterministic( node.aNode ) &&
  36828. ( node.bNode ? this.isDeterministic( node.bNode ) : true ) &&
  36829. ( node.cNode ? this.isDeterministic( node.cNode ) : true );
  36830. } else if ( node.isOperatorNode ) {
  36831. return this.isDeterministic( node.aNode ) &&
  36832. ( node.bNode ? this.isDeterministic( node.bNode ) : true );
  36833. } else if ( node.isArrayNode ) {
  36834. if ( node.values !== null ) {
  36835. for ( const n of node.values ) {
  36836. if ( ! this.isDeterministic( n ) ) {
  36837. return false;
  36838. }
  36839. }
  36840. }
  36841. return true;
  36842. } else if ( node.isConstNode ) {
  36843. return true;
  36844. }
  36845. return false;
  36846. }
  36847. /**
  36848. * Returns an instance of {@link NodeVarying} for the given varying node.
  36849. *
  36850. * @param {(VaryingNode|PropertyNode)} node - The varying node.
  36851. * @param {?string} name - The varying's name.
  36852. * @param {string} [type=node.getNodeType( this )] - The varying's type.
  36853. * @param {?string} interpolationType - The interpolation type of the varying.
  36854. * @param {?string} interpolationSampling - The interpolation sampling type of the varying.
  36855. * @return {NodeVar} The node varying.
  36856. */
  36857. getVaryingFromNode( node, name = null, type = node.getNodeType( this ), interpolationType = null, interpolationSampling = null ) {
  36858. const nodeData = this.getDataFromNode( node, 'any' );
  36859. const subBuildVarying = this.getSubBuildProperty( 'varying', nodeData.subBuilds );
  36860. let nodeVarying = nodeData[ subBuildVarying ];
  36861. if ( nodeVarying === undefined ) {
  36862. const varyings = this.varyings;
  36863. const index = varyings.length;
  36864. if ( name === null ) name = 'nodeVarying' + index;
  36865. //
  36866. if ( subBuildVarying !== 'varying' ) {
  36867. name = this.getSubBuildProperty( name, nodeData.subBuilds );
  36868. }
  36869. //
  36870. nodeVarying = new NodeVarying( name, type, interpolationType, interpolationSampling );
  36871. varyings.push( nodeVarying );
  36872. this.registerDeclaration( nodeVarying );
  36873. nodeData[ subBuildVarying ] = nodeVarying;
  36874. }
  36875. return nodeVarying;
  36876. }
  36877. /**
  36878. * Registers a node declaration in the current shader stage.
  36879. *
  36880. * @param {Object} node - The node to be registered.
  36881. */
  36882. registerDeclaration( node ) {
  36883. const shaderStage = this.shaderStage;
  36884. const declarations = this.declarations[ shaderStage ] || ( this.declarations[ shaderStage ] = {} );
  36885. const property = this.getPropertyName( node );
  36886. let index = 1;
  36887. let name = property;
  36888. // Automatically renames the property if the name is already in use.
  36889. while ( declarations[ name ] !== undefined ) {
  36890. name = property + '_' + index ++;
  36891. }
  36892. if ( index > 1 ) {
  36893. node.name = name;
  36894. warn( `TSL: Declaration name '${ property }' of '${ node.type }' already in use. Renamed to '${ name }'.` );
  36895. }
  36896. declarations[ name ] = node;
  36897. }
  36898. /**
  36899. * Returns an instance of {@link NodeCode} for the given code node.
  36900. *
  36901. * @param {CodeNode} node - The code node.
  36902. * @param {string} type - The node type.
  36903. * @param {('vertex'|'fragment'|'compute'|'any')} [shaderStage=this.shaderStage] - The shader stage.
  36904. * @return {NodeCode} The node code.
  36905. */
  36906. getCodeFromNode( node, type, shaderStage = this.shaderStage ) {
  36907. const nodeData = this.getDataFromNode( node );
  36908. let nodeCode = nodeData.code;
  36909. if ( nodeCode === undefined ) {
  36910. const codes = this.codes[ shaderStage ] || ( this.codes[ shaderStage ] = [] );
  36911. const index = codes.length;
  36912. nodeCode = new NodeCode( 'nodeCode' + index, type );
  36913. codes.push( nodeCode );
  36914. nodeData.code = nodeCode;
  36915. }
  36916. return nodeCode;
  36917. }
  36918. /**
  36919. * Adds a code flow based on the code-block hierarchy.
  36920. * This is used so that code-blocks like If,Else create their variables locally if the Node
  36921. * is only used inside one of these conditionals in the current shader stage.
  36922. *
  36923. * @param {Node} node - The node to add.
  36924. * @param {Node} nodeBlock - Node-based code-block. Usually 'ConditionalNode'.
  36925. */
  36926. addFlowCodeHierarchy( node, nodeBlock ) {
  36927. const { flowCodes, flowCodeBlock } = this.getDataFromNode( node );
  36928. let needsFlowCode = true;
  36929. let nodeBlockHierarchy = nodeBlock;
  36930. while ( nodeBlockHierarchy ) {
  36931. if ( flowCodeBlock.get( nodeBlockHierarchy ) === true ) {
  36932. needsFlowCode = false;
  36933. break;
  36934. }
  36935. nodeBlockHierarchy = this.getDataFromNode( nodeBlockHierarchy ).parentNodeBlock;
  36936. }
  36937. if ( needsFlowCode ) {
  36938. for ( const flowCode of flowCodes ) {
  36939. this.addLineFlowCode( flowCode );
  36940. }
  36941. }
  36942. }
  36943. /**
  36944. * Add a inline-code to the current flow code-block.
  36945. *
  36946. * @param {Node} node - The node to add.
  36947. * @param {string} code - The code to add.
  36948. * @param {Node} nodeBlock - Current ConditionalNode
  36949. */
  36950. addLineFlowCodeBlock( node, code, nodeBlock ) {
  36951. const nodeData = this.getDataFromNode( node );
  36952. const flowCodes = nodeData.flowCodes || ( nodeData.flowCodes = [] );
  36953. const codeBlock = nodeData.flowCodeBlock || ( nodeData.flowCodeBlock = new WeakMap() );
  36954. flowCodes.push( code );
  36955. codeBlock.set( nodeBlock, true );
  36956. }
  36957. /**
  36958. * Add a inline-code to the current flow.
  36959. *
  36960. * @param {string} code - The code to add.
  36961. * @param {?Node} [node= null] - Optional Node, can help the system understand if the Node is part of a code-block.
  36962. * @return {NodeBuilder} A reference to this node builder.
  36963. */
  36964. addLineFlowCode( code, node = null ) {
  36965. if ( code === '' ) return this;
  36966. if ( node !== null && this.context.nodeBlock ) {
  36967. this.addLineFlowCodeBlock( node, code, this.context.nodeBlock );
  36968. }
  36969. code = this.tab + code;
  36970. if ( ! /;\s*$/.test( code ) ) {
  36971. code = code + ';\n';
  36972. }
  36973. this.flow.code += code;
  36974. return this;
  36975. }
  36976. /**
  36977. * Adds a code to the current code flow.
  36978. *
  36979. * @param {string} code - Shader code.
  36980. * @return {NodeBuilder} A reference to this node builder.
  36981. */
  36982. addFlowCode( code ) {
  36983. this.flow.code += code;
  36984. return this;
  36985. }
  36986. /**
  36987. * Add tab in the code that will be generated so that other snippets respect the current tabulation.
  36988. * Typically used in codes with If,Else.
  36989. *
  36990. * @return {NodeBuilder} A reference to this node builder.
  36991. */
  36992. addFlowTab() {
  36993. this.tab += '\t';
  36994. return this;
  36995. }
  36996. /**
  36997. * Removes a tab.
  36998. *
  36999. * @return {NodeBuilder} A reference to this node builder.
  37000. */
  37001. removeFlowTab() {
  37002. this.tab = this.tab.slice( 0, -1 );
  37003. return this;
  37004. }
  37005. /**
  37006. * Gets the current flow data based on a Node.
  37007. *
  37008. * @param {Node} node - Node that the flow was started.
  37009. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  37010. * @return {Object} The flow data.
  37011. */
  37012. getFlowData( node/*, shaderStage*/ ) {
  37013. return this.flowsData.get( node );
  37014. }
  37015. /**
  37016. * Executes the node flow based on a root node to generate the final shader code.
  37017. *
  37018. * @param {Node} node - The node to execute.
  37019. * @return {Object} The code flow.
  37020. */
  37021. flowNode( node ) {
  37022. const output = node.getNodeType( this );
  37023. const flowData = this.flowChildNode( node, output );
  37024. this.flowsData.set( node, flowData );
  37025. return flowData;
  37026. }
  37027. /**
  37028. * Includes a node in the current function node.
  37029. *
  37030. * @param {Node} node - The node to include.
  37031. * @returns {void}
  37032. */
  37033. addInclude( node ) {
  37034. if ( this.currentFunctionNode !== null ) {
  37035. this.currentFunctionNode.includes.push( node );
  37036. }
  37037. }
  37038. /**
  37039. * Returns the native shader operator name for a given generic name.
  37040. * It is a similar type of method like {@link NodeBuilder#getMethod}.
  37041. *
  37042. * @param {ShaderNodeInternal} shaderNode - The shader node to build the function node with.
  37043. * @return {FunctionNode} The build function node.
  37044. */
  37045. buildFunctionNode( shaderNode ) {
  37046. const fn = new FunctionNode();
  37047. const previous = this.currentFunctionNode;
  37048. this.currentFunctionNode = fn;
  37049. fn.code = this.buildFunctionCode( shaderNode );
  37050. this.currentFunctionNode = previous;
  37051. return fn;
  37052. }
  37053. /**
  37054. * Generates a code flow based on a TSL function: Fn().
  37055. *
  37056. * @param {ShaderNodeInternal} shaderNode - A function code will be generated based on the input.
  37057. * @return {Object}
  37058. */
  37059. flowShaderNode( shaderNode ) {
  37060. const layout = shaderNode.layout;
  37061. const inputs = {
  37062. [ Symbol.iterator ]() {
  37063. let index = 0;
  37064. const values = Object.values( this );
  37065. return {
  37066. next: () => ( {
  37067. value: values[ index ],
  37068. done: index ++ >= values.length
  37069. } )
  37070. };
  37071. }
  37072. };
  37073. for ( const input of layout.inputs ) {
  37074. inputs[ input.name ] = new ParameterNode( input.type, input.name );
  37075. }
  37076. //
  37077. shaderNode.layout = null;
  37078. const callNode = shaderNode.call( inputs );
  37079. const flowData = this.flowStagesNode( callNode, layout.type );
  37080. shaderNode.layout = layout;
  37081. return flowData;
  37082. }
  37083. /**
  37084. * Executes the node in a specific build stage.
  37085. *
  37086. * This function can be used to arbitrarily execute the specified build stage
  37087. * outside of the standard build process. For instance, if a node's type depends
  37088. * on properties created by the 'setup' stage, then flowBuildStage(node, 'setup')
  37089. * can be used to execute the setup build stage and access its generated nodes
  37090. * before the standard build process begins.
  37091. *
  37092. * @param {Node} node - The node to execute.
  37093. * @param {string} buildStage - The build stage to execute the node in.
  37094. * @param {?(Node|string)} [output=null] - Expected output type. For example 'vec3'.
  37095. * @return {?(Node|string)} The result of the node build.
  37096. */
  37097. flowBuildStage( node, buildStage, output = null ) {
  37098. const previousBuildStage = this.getBuildStage();
  37099. this.setBuildStage( buildStage );
  37100. const result = node.build( this, output );
  37101. this.setBuildStage( previousBuildStage );
  37102. return result;
  37103. }
  37104. /**
  37105. * Runs the node flow through all the steps of creation, 'setup', 'analyze', 'generate'.
  37106. *
  37107. * @param {Node} node - The node to execute.
  37108. * @param {?string} output - Expected output type. For example 'vec3'.
  37109. * @return {Object}
  37110. */
  37111. flowStagesNode( node, output = null ) {
  37112. const previousFlow = this.flow;
  37113. const previousVars = this.vars;
  37114. const previousDeclarations = this.declarations;
  37115. const previousCache = this.cache;
  37116. const previousBuildStage = this.buildStage;
  37117. const previousStack = this.stack;
  37118. const flow = {
  37119. code: ''
  37120. };
  37121. this.flow = flow;
  37122. this.vars = {};
  37123. this.declarations = {};
  37124. this.cache = new NodeCache();
  37125. this.stack = stack();
  37126. for ( const buildStage of defaultBuildStages ) {
  37127. this.setBuildStage( buildStage );
  37128. flow.result = node.build( this, output );
  37129. }
  37130. flow.vars = this.getVars( this.shaderStage );
  37131. this.flow = previousFlow;
  37132. this.vars = previousVars;
  37133. this.declarations = previousDeclarations;
  37134. this.cache = previousCache;
  37135. this.stack = previousStack;
  37136. this.setBuildStage( previousBuildStage );
  37137. return flow;
  37138. }
  37139. /**
  37140. * Returns the native shader operator name for a given generic name.
  37141. * It is a similar type of method like {@link NodeBuilder#getMethod}.
  37142. *
  37143. * @abstract
  37144. * @param {string} op - The operator name to resolve.
  37145. * @return {?string} The resolved operator name.
  37146. */
  37147. getFunctionOperator( /* op */ ) {
  37148. return null;
  37149. }
  37150. /**
  37151. * Builds the given shader node.
  37152. *
  37153. * @abstract
  37154. * @param {ShaderNodeInternal} shaderNode - The shader node.
  37155. * @return {string} The function code.
  37156. */
  37157. buildFunctionCode( /* shaderNode */ ) {
  37158. warn( 'Abstract function.' );
  37159. }
  37160. /**
  37161. * Generates a code flow based on a child Node.
  37162. *
  37163. * @param {Node} node - The node to execute.
  37164. * @param {?string} output - Expected output type. For example 'vec3'.
  37165. * @return {Object} The code flow.
  37166. */
  37167. flowChildNode( node, output = null ) {
  37168. const previousFlow = this.flow;
  37169. const flow = {
  37170. code: ''
  37171. };
  37172. this.flow = flow;
  37173. flow.result = node.build( this, output );
  37174. this.flow = previousFlow;
  37175. return flow;
  37176. }
  37177. /**
  37178. * Executes a flow of code in a different stage.
  37179. *
  37180. * Some nodes like `varying()` have the ability to compute code in vertex-stage and
  37181. * return the value in fragment-stage even if it is being executed in an input fragment.
  37182. *
  37183. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  37184. * @param {Node} node - The node to execute.
  37185. * @param {?string} output - Expected output type. For example 'vec3'.
  37186. * @param {?string} propertyName - The property name to assign the result.
  37187. * @return {?(Object|Node)} The code flow or node.build() result.
  37188. */
  37189. flowNodeFromShaderStage( shaderStage, node, output = null, propertyName = null ) {
  37190. const previousTab = this.tab;
  37191. const previousCache = this.cache;
  37192. const previousShaderStage = this.shaderStage;
  37193. const previousContext = this.context;
  37194. this.setShaderStage( shaderStage );
  37195. const context = { ...this.context };
  37196. delete context.nodeBlock;
  37197. this.cache = this.globalCache;
  37198. this.tab = '\t';
  37199. this.context = context;
  37200. let result = null;
  37201. if ( this.buildStage === 'generate' ) {
  37202. const flowData = this.flowChildNode( node, output );
  37203. if ( propertyName !== null ) {
  37204. flowData.code += `${ this.tab + propertyName } = ${ flowData.result };\n`;
  37205. }
  37206. this.flowCode[ shaderStage ] = this.flowCode[ shaderStage ] + flowData.code;
  37207. result = flowData;
  37208. } else {
  37209. result = node.build( this );
  37210. }
  37211. this.setShaderStage( previousShaderStage );
  37212. this.cache = previousCache;
  37213. this.tab = previousTab;
  37214. this.context = previousContext;
  37215. return result;
  37216. }
  37217. /**
  37218. * Returns an array holding all node attributes of this node builder.
  37219. *
  37220. * @return {Array<NodeAttribute>} The node attributes of this builder.
  37221. */
  37222. getAttributesArray() {
  37223. return this.attributes.concat( this.bufferAttributes );
  37224. }
  37225. /**
  37226. * Returns the attribute definitions as a shader string for the given shader stage.
  37227. *
  37228. * @abstract
  37229. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  37230. * @return {string} The attribute code section.
  37231. */
  37232. getAttributes( /*shaderStage*/ ) {
  37233. warn( 'Abstract function.' );
  37234. }
  37235. /**
  37236. * Returns the varying definitions as a shader string for the given shader stage.
  37237. *
  37238. * @abstract
  37239. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  37240. * @return {string} The varying code section.
  37241. */
  37242. getVaryings( /*shaderStage*/ ) {
  37243. warn( 'Abstract function.' );
  37244. }
  37245. /**
  37246. * Returns a single variable definition as a shader string for the given variable type and name.
  37247. *
  37248. * @param {string} type - The variable's type.
  37249. * @param {string} name - The variable's name.
  37250. * @param {?number} [count=null] - The array length.
  37251. * @return {string} The shader string.
  37252. */
  37253. getVar( type, name, count = null ) {
  37254. return `${ count !== null ? this.generateArrayDeclaration( type, count ) : this.getType( type ) } ${ name }`;
  37255. }
  37256. /**
  37257. * Returns the variable definitions as a shader string for the given shader stage.
  37258. *
  37259. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  37260. * @return {string} The variable code section.
  37261. */
  37262. getVars( shaderStage ) {
  37263. let snippet = '';
  37264. const vars = this.vars[ shaderStage ];
  37265. if ( vars !== undefined ) {
  37266. for ( const variable of vars ) {
  37267. snippet += `${ this.getVar( variable.type, variable.name ) }; `;
  37268. }
  37269. }
  37270. return snippet;
  37271. }
  37272. /**
  37273. * Returns the uniform definitions as a shader string for the given shader stage.
  37274. *
  37275. * @abstract
  37276. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  37277. * @return {string} The uniform code section.
  37278. */
  37279. getUniforms( /*shaderStage*/ ) {
  37280. warn( 'Abstract function.' );
  37281. }
  37282. /**
  37283. * Returns the native code definitions as a shader string for the given shader stage.
  37284. *
  37285. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  37286. * @return {string} The native code section.
  37287. */
  37288. getCodes( shaderStage ) {
  37289. const codes = this.codes[ shaderStage ];
  37290. let code = '';
  37291. if ( codes !== undefined ) {
  37292. for ( const nodeCode of codes ) {
  37293. code += nodeCode.code + '\n';
  37294. }
  37295. }
  37296. return code;
  37297. }
  37298. /**
  37299. * Returns the hash of this node builder.
  37300. *
  37301. * @return {string} The hash.
  37302. */
  37303. getHash() {
  37304. return this.vertexShader + this.fragmentShader + this.computeShader;
  37305. }
  37306. /**
  37307. * Sets the current shader stage.
  37308. *
  37309. * @param {?('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage to set.
  37310. */
  37311. setShaderStage( shaderStage ) {
  37312. this.shaderStage = shaderStage;
  37313. }
  37314. /**
  37315. * Returns the current shader stage.
  37316. *
  37317. * @return {?('vertex'|'fragment'|'compute'|'any')} The current shader stage.
  37318. */
  37319. getShaderStage() {
  37320. return this.shaderStage;
  37321. }
  37322. /**
  37323. * Sets the current build stage.
  37324. *
  37325. * @param {?('setup'|'analyze'|'generate')} buildStage - The build stage to set.
  37326. */
  37327. setBuildStage( buildStage ) {
  37328. this.buildStage = buildStage;
  37329. }
  37330. /**
  37331. * Returns the current build stage.
  37332. *
  37333. * @return {?('setup'|'analyze'|'generate')} The current build stage.
  37334. */
  37335. getBuildStage() {
  37336. return this.buildStage;
  37337. }
  37338. /**
  37339. * Controls the code build of the shader stages.
  37340. *
  37341. * @abstract
  37342. */
  37343. buildCode() {
  37344. warn( 'Abstract function.' );
  37345. }
  37346. /**
  37347. * Returns the current sub-build layer.
  37348. *
  37349. * @return {SubBuildNode} The current sub-build layers.
  37350. */
  37351. get subBuild() {
  37352. return this.subBuildLayers[ this.subBuildLayers.length - 1 ] || null;
  37353. }
  37354. /**
  37355. * Adds a sub-build layer to the node builder.
  37356. *
  37357. * @param {SubBuildNode} subBuild - The sub-build layer to add.
  37358. */
  37359. addSubBuild( subBuild ) {
  37360. this.subBuildLayers.push( subBuild );
  37361. }
  37362. /**
  37363. * Removes the last sub-build layer from the node builder.
  37364. *
  37365. * @return {SubBuildNode} The removed sub-build layer.
  37366. */
  37367. removeSubBuild() {
  37368. return this.subBuildLayers.pop();
  37369. }
  37370. /**
  37371. * Returns the closest sub-build layer for the given data.
  37372. *
  37373. * @param {Node|Set<string>|Array<string>} data - The data to get the closest sub-build layer from.
  37374. * @return {?string} The closest sub-build name or null if none found.
  37375. */
  37376. getClosestSubBuild( data ) {
  37377. let subBuilds;
  37378. if ( data && data.isNode ) {
  37379. if ( data.isShaderCallNodeInternal ) {
  37380. subBuilds = data.shaderNode.subBuilds;
  37381. } else if ( data.isStackNode ) {
  37382. subBuilds = [ data.subBuild ];
  37383. } else {
  37384. subBuilds = this.getDataFromNode( data, 'any' ).subBuilds;
  37385. }
  37386. } else if ( data instanceof Set ) {
  37387. subBuilds = [ ...data ];
  37388. } else {
  37389. subBuilds = data;
  37390. }
  37391. if ( ! subBuilds ) return null;
  37392. const subBuildLayers = this.subBuildLayers;
  37393. for ( let i = subBuilds.length - 1; i >= 0; i -- ) {
  37394. const subBuild = subBuilds[ i ];
  37395. if ( subBuildLayers.includes( subBuild ) ) {
  37396. return subBuild;
  37397. }
  37398. }
  37399. return null;
  37400. }
  37401. /**
  37402. * Returns the output node of a sub-build layer.
  37403. *
  37404. * @param {Node} node - The node to get the output from.
  37405. * @return {string} The output node name.
  37406. */
  37407. getSubBuildOutput( node ) {
  37408. return this.getSubBuildProperty( 'outputNode', node );
  37409. }
  37410. /**
  37411. * Returns the sub-build property name for the given property and node.
  37412. *
  37413. * @param {string} [property=''] - The property name.
  37414. * @param {?Node} [node=null] - The node to get the sub-build from.
  37415. * @return {string} The sub-build property name.
  37416. */
  37417. getSubBuildProperty( property = '', node = null ) {
  37418. let subBuild;
  37419. if ( node !== null ) {
  37420. subBuild = this.getClosestSubBuild( node );
  37421. } else {
  37422. subBuild = this.subBuildFn;
  37423. }
  37424. let result;
  37425. if ( subBuild ) {
  37426. result = property ? ( subBuild + '_' + property ) : subBuild;
  37427. } else {
  37428. result = property;
  37429. }
  37430. return result;
  37431. }
  37432. /**
  37433. * Central build method which controls the build for the given object.
  37434. *
  37435. * @return {NodeBuilder} A reference to this node builder.
  37436. */
  37437. build() {
  37438. const { object, material, renderer } = this;
  37439. if ( material !== null ) {
  37440. let nodeMaterial = renderer.library.fromMaterial( material );
  37441. if ( nodeMaterial === null ) {
  37442. error( `NodeMaterial: Material "${ material.type }" is not compatible.` );
  37443. nodeMaterial = new NodeMaterial();
  37444. }
  37445. nodeMaterial.build( this );
  37446. } else {
  37447. this.addFlow( 'compute', object );
  37448. }
  37449. // setup() -> stage 1: create possible new nodes and/or return an output reference node
  37450. // analyze() -> stage 2: analyze nodes to possible optimization and validation
  37451. // generate() -> stage 3: generate shader
  37452. for ( const buildStage of defaultBuildStages ) {
  37453. this.setBuildStage( buildStage );
  37454. if ( this.context.vertex && this.context.vertex.isNode ) {
  37455. this.flowNodeFromShaderStage( 'vertex', this.context.vertex );
  37456. }
  37457. for ( const shaderStage of shaderStages ) {
  37458. this.setShaderStage( shaderStage );
  37459. const flowNodes = this.flowNodes[ shaderStage ];
  37460. for ( const node of flowNodes ) {
  37461. if ( buildStage === 'generate' ) {
  37462. this.flowNode( node );
  37463. } else {
  37464. node.build( this );
  37465. }
  37466. }
  37467. }
  37468. }
  37469. this.setBuildStage( null );
  37470. this.setShaderStage( null );
  37471. // stage 4: build code for a specific output
  37472. this.buildCode();
  37473. this.buildUpdateNodes();
  37474. return this;
  37475. }
  37476. /**
  37477. * Returns shared data object for the given node.
  37478. *
  37479. * @param {Node} node - The node to get shared data from.
  37480. * @return {Object} The shared data.
  37481. */
  37482. getSharedDataFromNode( node ) {
  37483. let data = sharedNodeData.get( node );
  37484. if ( data === undefined ) {
  37485. data = {};
  37486. }
  37487. return data;
  37488. }
  37489. /**
  37490. * Returns a uniform representation which is later used for UBO generation and rendering.
  37491. *
  37492. * @param {NodeUniform} uniformNode - The uniform node.
  37493. * @param {string} type - The requested type.
  37494. * @return {Uniform} The uniform.
  37495. */
  37496. getNodeUniform( uniformNode, type ) {
  37497. const nodeData = this.getSharedDataFromNode( uniformNode );
  37498. let node = nodeData.cache;
  37499. if ( node === undefined ) {
  37500. if ( type === 'float' || type === 'int' || type === 'uint' ) node = new NumberNodeUniform( uniformNode );
  37501. else if ( type === 'vec2' || type === 'ivec2' || type === 'uvec2' ) node = new Vector2NodeUniform( uniformNode );
  37502. else if ( type === 'vec3' || type === 'ivec3' || type === 'uvec3' ) node = new Vector3NodeUniform( uniformNode );
  37503. else if ( type === 'vec4' || type === 'ivec4' || type === 'uvec4' ) node = new Vector4NodeUniform( uniformNode );
  37504. else if ( type === 'color' ) node = new ColorNodeUniform( uniformNode );
  37505. else if ( type === 'mat2' ) node = new Matrix2NodeUniform( uniformNode );
  37506. else if ( type === 'mat3' ) node = new Matrix3NodeUniform( uniformNode );
  37507. else if ( type === 'mat4' ) node = new Matrix4NodeUniform( uniformNode );
  37508. else {
  37509. throw new Error( `Uniform "${ type }" not implemented.` );
  37510. }
  37511. nodeData.cache = node;
  37512. }
  37513. return node;
  37514. }
  37515. /**
  37516. * Formats the given shader snippet from a given type into another one. E.g.
  37517. * this method might be used to convert a simple float string `"1.0"` into a
  37518. * `vec3` representation: `"vec3<f32>( 1.0 )"`.
  37519. *
  37520. * @param {string} snippet - The shader snippet.
  37521. * @param {string} fromType - The source type.
  37522. * @param {string} toType - The target type.
  37523. * @return {string} The updated shader string.
  37524. */
  37525. format( snippet, fromType, toType ) {
  37526. fromType = this.getVectorType( fromType );
  37527. toType = this.getVectorType( toType );
  37528. if ( fromType === toType || toType === null || this.isReference( toType ) ) {
  37529. return snippet;
  37530. }
  37531. const fromTypeLength = this.getTypeLength( fromType );
  37532. const toTypeLength = this.getTypeLength( toType );
  37533. if ( fromTypeLength === 16 && toTypeLength === 9 ) {
  37534. return `${ this.getType( toType ) }( ${ snippet }[ 0 ].xyz, ${ snippet }[ 1 ].xyz, ${ snippet }[ 2 ].xyz )`;
  37535. }
  37536. if ( fromTypeLength === 9 && toTypeLength === 4 ) {
  37537. return `${ this.getType( toType ) }( ${ snippet }[ 0 ].xy, ${ snippet }[ 1 ].xy )`;
  37538. }
  37539. if ( fromTypeLength > 4 ) { // fromType is matrix-like
  37540. // @TODO: ignore for now
  37541. return snippet;
  37542. }
  37543. if ( toTypeLength > 4 || toTypeLength === 0 ) { // toType is matrix-like or unknown
  37544. // @TODO: ignore for now
  37545. return snippet;
  37546. }
  37547. if ( fromTypeLength === toTypeLength ) {
  37548. return `${ this.getType( toType ) }( ${ snippet } )`;
  37549. }
  37550. if ( fromTypeLength > toTypeLength ) {
  37551. snippet = toType === 'bool' ? `all( ${ snippet } )` : `${ snippet }.${ 'xyz'.slice( 0, toTypeLength ) }`;
  37552. return this.format( snippet, this.getTypeFromLength( toTypeLength, this.getComponentType( fromType ) ), toType );
  37553. }
  37554. if ( toTypeLength === 4 && fromTypeLength > 1 ) { // toType is vec4-like
  37555. return `${ this.getType( toType ) }( ${ this.format( snippet, fromType, 'vec3' ) }, 1.0 )`;
  37556. }
  37557. if ( fromTypeLength === 2 ) { // fromType is vec2-like and toType is vec3-like
  37558. return `${ this.getType( toType ) }( ${ this.format( snippet, fromType, 'vec2' ) }, 0.0 )`;
  37559. }
  37560. if ( fromTypeLength === 1 && toTypeLength > 1 && fromType !== this.getComponentType( toType ) ) { // fromType is float-like
  37561. // convert a number value to vector type, e.g:
  37562. // vec3( 1u ) -> vec3( float( 1u ) )
  37563. snippet = `${ this.getType( this.getComponentType( toType ) ) }( ${ snippet } )`;
  37564. }
  37565. return `${ this.getType( toType ) }( ${ snippet } )`; // fromType is float-like
  37566. }
  37567. /**
  37568. * Returns a signature with the engine's current revision.
  37569. *
  37570. * @return {string} The signature.
  37571. */
  37572. getSignature() {
  37573. return `// Three.js r${ REVISION } - Node System\n`;
  37574. }
  37575. }
  37576. /**
  37577. * Management class for updating nodes. The module tracks metrics like
  37578. * the elapsed time, delta time, the render and frame ID to correctly
  37579. * call the node update methods {@link Node#updateBefore}, {@link Node#update}
  37580. * and {@link Node#updateAfter} depending on the node's configuration.
  37581. */
  37582. class NodeFrame {
  37583. /**
  37584. * Constructs a new node fame.
  37585. */
  37586. constructor() {
  37587. /**
  37588. * The elapsed time in seconds.
  37589. *
  37590. * @type {number}
  37591. * @default 0
  37592. */
  37593. this.time = 0;
  37594. /**
  37595. * The delta time in seconds.
  37596. *
  37597. * @type {number}
  37598. * @default 0
  37599. */
  37600. this.deltaTime = 0;
  37601. /**
  37602. * The frame ID.
  37603. *
  37604. * @type {number}
  37605. * @default 0
  37606. */
  37607. this.frameId = 0;
  37608. /**
  37609. * The render ID.
  37610. *
  37611. * @type {number}
  37612. * @default 0
  37613. */
  37614. this.renderId = 0;
  37615. /**
  37616. * Used to control the {@link Node#update} call.
  37617. *
  37618. * @type {WeakMap<Node, Object>}
  37619. */
  37620. this.updateMap = new WeakMap();
  37621. /**
  37622. * Used to control the {@link Node#updateBefore} call.
  37623. *
  37624. * @type {WeakMap<Node, Object>}
  37625. */
  37626. this.updateBeforeMap = new WeakMap();
  37627. /**
  37628. * Used to control the {@link Node#updateAfter} call.
  37629. *
  37630. * @type {WeakMap<Node, Object>}
  37631. */
  37632. this.updateAfterMap = new WeakMap();
  37633. /**
  37634. * A reference to the current renderer.
  37635. *
  37636. * @type {?Renderer}
  37637. * @default null
  37638. */
  37639. this.renderer = null;
  37640. /**
  37641. * A reference to the current material.
  37642. *
  37643. * @type {?Material}
  37644. * @default null
  37645. */
  37646. this.material = null;
  37647. /**
  37648. * A reference to the current camera.
  37649. *
  37650. * @type {?Camera}
  37651. * @default null
  37652. */
  37653. this.camera = null;
  37654. /**
  37655. * A reference to the current 3D object.
  37656. *
  37657. * @type {?Object3D}
  37658. * @default null
  37659. */
  37660. this.object = null;
  37661. /**
  37662. * A reference to the current scene.
  37663. *
  37664. * @type {?Scene}
  37665. * @default null
  37666. */
  37667. this.scene = null;
  37668. }
  37669. /**
  37670. * Returns a dictionary for a given node and update map which
  37671. * is used to correctly call node update methods per frame or render.
  37672. *
  37673. * @private
  37674. * @param {WeakMap<Node, Object>} referenceMap - The reference weak map.
  37675. * @param {Node} nodeRef - The reference to the current node.
  37676. * @return {Object<string,WeakMap<Object, number>>} The dictionary.
  37677. */
  37678. _getMaps( referenceMap, nodeRef ) {
  37679. let maps = referenceMap.get( nodeRef );
  37680. if ( maps === undefined ) {
  37681. maps = {
  37682. renderId: 0,
  37683. frameId: 0,
  37684. };
  37685. referenceMap.set( nodeRef, maps );
  37686. }
  37687. return maps;
  37688. }
  37689. /**
  37690. * This method executes the {@link Node#updateBefore} for the given node.
  37691. * It makes sure {@link Node#updateBeforeType} is honored meaning the update
  37692. * is only executed once per frame, render or object depending on the update
  37693. * type.
  37694. *
  37695. * @param {Node} node - The node that should be updated.
  37696. */
  37697. updateBeforeNode( node ) {
  37698. const updateType = node.getUpdateBeforeType();
  37699. const reference = node.updateReference( this );
  37700. if ( updateType === NodeUpdateType.FRAME ) {
  37701. const nodeUpdateBeforeMap = this._getMaps( this.updateBeforeMap, reference );
  37702. if ( nodeUpdateBeforeMap.frameId !== this.frameId ) {
  37703. const previousFrameId = nodeUpdateBeforeMap.frameId;
  37704. nodeUpdateBeforeMap.frameId = this.frameId;
  37705. if ( node.updateBefore( this ) === false ) {
  37706. nodeUpdateBeforeMap.frameId = previousFrameId;
  37707. }
  37708. }
  37709. } else if ( updateType === NodeUpdateType.RENDER ) {
  37710. const nodeUpdateBeforeMap = this._getMaps( this.updateBeforeMap, reference );
  37711. if ( nodeUpdateBeforeMap.renderId !== this.renderId ) {
  37712. const previousRenderId = nodeUpdateBeforeMap.renderId;
  37713. nodeUpdateBeforeMap.renderId = this.renderId;
  37714. if ( node.updateBefore( this ) === false ) {
  37715. nodeUpdateBeforeMap.renderId = previousRenderId;
  37716. }
  37717. }
  37718. } else if ( updateType === NodeUpdateType.OBJECT ) {
  37719. node.updateBefore( this );
  37720. }
  37721. }
  37722. /**
  37723. * This method executes the {@link Node#updateAfter} for the given node.
  37724. * It makes sure {@link Node#updateAfterType} is honored meaning the update
  37725. * is only executed once per frame, render or object depending on the update
  37726. * type.
  37727. *
  37728. * @param {Node} node - The node that should be updated.
  37729. */
  37730. updateAfterNode( node ) {
  37731. const updateType = node.getUpdateAfterType();
  37732. const reference = node.updateReference( this );
  37733. if ( updateType === NodeUpdateType.FRAME ) {
  37734. const nodeUpdateAfterMap = this._getMaps( this.updateAfterMap, reference );
  37735. if ( nodeUpdateAfterMap.frameId !== this.frameId ) {
  37736. if ( node.updateAfter( this ) !== false ) {
  37737. nodeUpdateAfterMap.frameId = this.frameId;
  37738. }
  37739. }
  37740. } else if ( updateType === NodeUpdateType.RENDER ) {
  37741. const nodeUpdateAfterMap = this._getMaps( this.updateAfterMap, reference );
  37742. if ( nodeUpdateAfterMap.renderId !== this.renderId ) {
  37743. if ( node.updateAfter( this ) !== false ) {
  37744. nodeUpdateAfterMap.renderId = this.renderId;
  37745. }
  37746. }
  37747. } else if ( updateType === NodeUpdateType.OBJECT ) {
  37748. node.updateAfter( this );
  37749. }
  37750. }
  37751. /**
  37752. * This method executes the {@link Node#update} for the given node.
  37753. * It makes sure {@link Node#updateType} is honored meaning the update
  37754. * is only executed once per frame, render or object depending on the update
  37755. * type.
  37756. *
  37757. * @param {Node} node - The node that should be updated.
  37758. */
  37759. updateNode( node ) {
  37760. const updateType = node.getUpdateType();
  37761. const reference = node.updateReference( this );
  37762. if ( updateType === NodeUpdateType.FRAME ) {
  37763. const nodeUpdateMap = this._getMaps( this.updateMap, reference );
  37764. if ( nodeUpdateMap.frameId !== this.frameId ) {
  37765. if ( node.update( this ) !== false ) {
  37766. nodeUpdateMap.frameId = this.frameId;
  37767. }
  37768. }
  37769. } else if ( updateType === NodeUpdateType.RENDER ) {
  37770. const nodeUpdateMap = this._getMaps( this.updateMap, reference );
  37771. if ( nodeUpdateMap.renderId !== this.renderId ) {
  37772. if ( node.update( this ) !== false ) {
  37773. nodeUpdateMap.renderId = this.renderId;
  37774. }
  37775. }
  37776. } else if ( updateType === NodeUpdateType.OBJECT ) {
  37777. node.update( this );
  37778. }
  37779. }
  37780. /**
  37781. * Updates the internal state of the node frame. This method is
  37782. * called by the renderer in its internal animation loop.
  37783. */
  37784. update() {
  37785. this.frameId ++;
  37786. if ( this.lastTime === undefined ) this.lastTime = performance.now();
  37787. this.deltaTime = ( performance.now() - this.lastTime ) / 1000;
  37788. this.lastTime = performance.now();
  37789. this.time += this.deltaTime;
  37790. }
  37791. }
  37792. /**
  37793. * Describes the input of a {@link NodeFunction}.
  37794. */
  37795. class NodeFunctionInput {
  37796. /**
  37797. * Constructs a new node function input.
  37798. *
  37799. * @param {string} type - The input type.
  37800. * @param {string} name - The input name.
  37801. * @param {?number} [count=null] - If the input is an Array, count will be the length.
  37802. * @param {('in'|'out'|'inout')} [qualifier=''] - The parameter qualifier (only relevant for GLSL).
  37803. * @param {boolean} [isConst=false] - Whether the input uses a const qualifier or not (only relevant for GLSL).
  37804. */
  37805. constructor( type, name, count = null, qualifier = '', isConst = false ) {
  37806. /**
  37807. * The input type.
  37808. *
  37809. * @type {string}
  37810. */
  37811. this.type = type;
  37812. /**
  37813. * The input name.
  37814. *
  37815. * @type {string}
  37816. */
  37817. this.name = name;
  37818. /**
  37819. * If the input is an Array, count will be the length.
  37820. *
  37821. * @type {?number}
  37822. * @default null
  37823. */
  37824. this.count = count;
  37825. /**
  37826. *The parameter qualifier (only relevant for GLSL).
  37827. *
  37828. * @type {('in'|'out'|'inout')}
  37829. * @default ''
  37830. */
  37831. this.qualifier = qualifier;
  37832. /**
  37833. * Whether the input uses a const qualifier or not (only relevant for GLSL).
  37834. *
  37835. * @type {boolean}
  37836. * @default false
  37837. */
  37838. this.isConst = isConst;
  37839. }
  37840. }
  37841. NodeFunctionInput.isNodeFunctionInput = true;
  37842. /**
  37843. * Module for representing directional lights as nodes.
  37844. *
  37845. * @augments AnalyticLightNode
  37846. */
  37847. class DirectionalLightNode extends AnalyticLightNode {
  37848. static get type() {
  37849. return 'DirectionalLightNode';
  37850. }
  37851. /**
  37852. * Constructs a new directional light node.
  37853. *
  37854. * @param {?DirectionalLight} [light=null] - The directional light source.
  37855. */
  37856. constructor( light = null ) {
  37857. super( light );
  37858. }
  37859. setupDirect() {
  37860. const lightColor = this.colorNode;
  37861. const lightDirection = lightTargetDirection( this.light );
  37862. return { lightDirection, lightColor };
  37863. }
  37864. }
  37865. const _matrix41 = /*@__PURE__*/ new Matrix4();
  37866. const _matrix42 = /*@__PURE__*/ new Matrix4();
  37867. let _ltcLib = null;
  37868. /**
  37869. * Module for representing rect area lights as nodes.
  37870. *
  37871. * @augments AnalyticLightNode
  37872. */
  37873. class RectAreaLightNode extends AnalyticLightNode {
  37874. static get type() {
  37875. return 'RectAreaLightNode';
  37876. }
  37877. /**
  37878. * Constructs a new rect area light node.
  37879. *
  37880. * @param {?RectAreaLight} [light=null] - The rect area light source.
  37881. */
  37882. constructor( light = null ) {
  37883. super( light );
  37884. /**
  37885. * Uniform node representing the half height of the are light.
  37886. *
  37887. * @type {UniformNode<vec3>}
  37888. */
  37889. this.halfHeight = uniform( new Vector3() ).setGroup( renderGroup );
  37890. /**
  37891. * Uniform node representing the half width of the are light.
  37892. *
  37893. * @type {UniformNode<vec3>}
  37894. */
  37895. this.halfWidth = uniform( new Vector3() ).setGroup( renderGroup );
  37896. /**
  37897. * The `updateType` is set to `NodeUpdateType.RENDER` since the light
  37898. * relies on `viewMatrix` which might vary per render call.
  37899. *
  37900. * @type {string}
  37901. * @default 'render'
  37902. */
  37903. this.updateType = NodeUpdateType.RENDER;
  37904. }
  37905. /**
  37906. * Overwritten to updated rect area light specific uniforms.
  37907. *
  37908. * @param {NodeFrame} frame - A reference to the current node frame.
  37909. */
  37910. update( frame ) {
  37911. super.update( frame );
  37912. const { light } = this;
  37913. const viewMatrix = frame.camera.matrixWorldInverse;
  37914. _matrix42.identity();
  37915. _matrix41.copy( light.matrixWorld );
  37916. _matrix41.premultiply( viewMatrix );
  37917. _matrix42.extractRotation( _matrix41 );
  37918. this.halfWidth.value.set( light.width * 0.5, 0.0, 0.0 );
  37919. this.halfHeight.value.set( 0.0, light.height * 0.5, 0.0 );
  37920. this.halfWidth.value.applyMatrix4( _matrix42 );
  37921. this.halfHeight.value.applyMatrix4( _matrix42 );
  37922. }
  37923. setupDirectRectArea( builder ) {
  37924. let ltc_1, ltc_2;
  37925. if ( builder.isAvailable( 'float32Filterable' ) ) {
  37926. ltc_1 = texture( _ltcLib.LTC_FLOAT_1 );
  37927. ltc_2 = texture( _ltcLib.LTC_FLOAT_2 );
  37928. } else {
  37929. ltc_1 = texture( _ltcLib.LTC_HALF_1 );
  37930. ltc_2 = texture( _ltcLib.LTC_HALF_2 );
  37931. }
  37932. const { colorNode, light } = this;
  37933. const lightPosition = lightViewPosition( light );
  37934. return {
  37935. lightColor: colorNode,
  37936. lightPosition,
  37937. halfWidth: this.halfWidth,
  37938. halfHeight: this.halfHeight,
  37939. ltc_1,
  37940. ltc_2
  37941. };
  37942. }
  37943. /**
  37944. * Used to configure the internal BRDF approximation texture data.
  37945. *
  37946. * @param {RectAreaLightTexturesLib} ltc - The BRDF approximation texture data.
  37947. */
  37948. static setLTC( ltc ) {
  37949. _ltcLib = ltc;
  37950. }
  37951. }
  37952. /**
  37953. * Module for representing spot lights as nodes.
  37954. *
  37955. * @augments AnalyticLightNode
  37956. */
  37957. class SpotLightNode extends AnalyticLightNode {
  37958. static get type() {
  37959. return 'SpotLightNode';
  37960. }
  37961. /**
  37962. * Constructs a new spot light node.
  37963. *
  37964. * @param {?SpotLight} [light=null] - The spot light source.
  37965. */
  37966. constructor( light = null ) {
  37967. super( light );
  37968. /**
  37969. * Uniform node representing the cone cosine.
  37970. *
  37971. * @type {UniformNode<float>}
  37972. */
  37973. this.coneCosNode = uniform( 0 ).setGroup( renderGroup );
  37974. /**
  37975. * Uniform node representing the penumbra cosine.
  37976. *
  37977. * @type {UniformNode<float>}
  37978. */
  37979. this.penumbraCosNode = uniform( 0 ).setGroup( renderGroup );
  37980. /**
  37981. * Uniform node representing the cutoff distance.
  37982. *
  37983. * @type {UniformNode<float>}
  37984. */
  37985. this.cutoffDistanceNode = uniform( 0 ).setGroup( renderGroup );
  37986. /**
  37987. * Uniform node representing the decay exponent.
  37988. *
  37989. * @type {UniformNode<float>}
  37990. */
  37991. this.decayExponentNode = uniform( 0 ).setGroup( renderGroup );
  37992. /**
  37993. * Uniform node representing the light color.
  37994. *
  37995. * @type {UniformNode<Color>}
  37996. */
  37997. this.colorNode = uniform( this.color ).setGroup( renderGroup );
  37998. }
  37999. /**
  38000. * Overwritten to updated spot light specific uniforms.
  38001. *
  38002. * @param {NodeFrame} frame - A reference to the current node frame.
  38003. */
  38004. update( frame ) {
  38005. super.update( frame );
  38006. const { light } = this;
  38007. this.coneCosNode.value = Math.cos( light.angle );
  38008. this.penumbraCosNode.value = Math.cos( light.angle * ( 1 - light.penumbra ) );
  38009. this.cutoffDistanceNode.value = light.distance;
  38010. this.decayExponentNode.value = light.decay;
  38011. }
  38012. /**
  38013. * Computes the spot attenuation for the given angle.
  38014. *
  38015. * @param {NodeBuilder} builder - The node builder.
  38016. * @param {Node<float>} angleCosine - The angle to compute the spot attenuation for.
  38017. * @return {Node<float>} The spot attenuation.
  38018. */
  38019. getSpotAttenuation( builder, angleCosine ) {
  38020. const { coneCosNode, penumbraCosNode } = this;
  38021. return smoothstep( coneCosNode, penumbraCosNode, angleCosine );
  38022. }
  38023. getLightCoord( builder ) {
  38024. const properties = builder.getNodeProperties( this );
  38025. let projectionUV = properties.projectionUV;
  38026. if ( projectionUV === undefined ) {
  38027. projectionUV = lightProjectionUV( this.light, builder.context.positionWorld );
  38028. properties.projectionUV = projectionUV;
  38029. }
  38030. return projectionUV;
  38031. }
  38032. setupDirect( builder ) {
  38033. const { colorNode, cutoffDistanceNode, decayExponentNode, light } = this;
  38034. const lightVector = this.getLightVector( builder );
  38035. const lightDirection = lightVector.normalize();
  38036. const angleCos = lightDirection.dot( lightTargetDirection( light ) );
  38037. const spotAttenuation = this.getSpotAttenuation( builder, angleCos );
  38038. const lightDistance = lightVector.length();
  38039. const lightAttenuation = getDistanceAttenuation( {
  38040. lightDistance,
  38041. cutoffDistance: cutoffDistanceNode,
  38042. decayExponent: decayExponentNode
  38043. } );
  38044. let lightColor = colorNode.mul( spotAttenuation ).mul( lightAttenuation );
  38045. let projected, lightCoord;
  38046. if ( light.colorNode ) {
  38047. lightCoord = this.getLightCoord( builder );
  38048. projected = light.colorNode( lightCoord );
  38049. } else if ( light.map ) {
  38050. lightCoord = this.getLightCoord( builder );
  38051. projected = texture( light.map, lightCoord.xy ).onRenderUpdate( () => light.map );
  38052. }
  38053. if ( projected ) {
  38054. const inSpotLightMap = lightCoord.mul( 2. ).sub( 1. ).abs().lessThan( 1. ).all();
  38055. lightColor = inSpotLightMap.select( lightColor.mul( projected ), lightColor );
  38056. }
  38057. return { lightColor, lightDirection };
  38058. }
  38059. }
  38060. /**
  38061. * An IES version of the default spot light node.
  38062. *
  38063. * @augments SpotLightNode
  38064. */
  38065. class IESSpotLightNode extends SpotLightNode {
  38066. static get type() {
  38067. return 'IESSpotLightNode';
  38068. }
  38069. /**
  38070. * Overwrites the default implementation to compute an IES conform spot attenuation.
  38071. *
  38072. * @param {NodeBuilder} builder - The node builder.
  38073. * @param {Node<float>} angleCosine - The angle to compute the spot attenuation for.
  38074. * @return {Node<float>} The spot attenuation.
  38075. */
  38076. getSpotAttenuation( builder, angleCosine ) {
  38077. const iesMap = this.light.iesMap;
  38078. let spotAttenuation = null;
  38079. if ( iesMap && iesMap.isTexture === true ) {
  38080. const angle = angleCosine.acos().mul( 1.0 / Math.PI );
  38081. spotAttenuation = texture( iesMap, vec2( angle, 0 ), 0 ).r;
  38082. } else {
  38083. spotAttenuation = super.getSpotAttenuation( angleCosine );
  38084. }
  38085. return spotAttenuation;
  38086. }
  38087. }
  38088. const sdBox = /*@__PURE__*/ Fn( ( [ p, b ] ) => {
  38089. const d = p.abs().sub( b );
  38090. return length( max$1( d, 0.0 ) ).add( min$1( max$1( d.x, d.y ), 0.0 ) );
  38091. } );
  38092. /**
  38093. * An implementation of a projector light node.
  38094. *
  38095. * @augments SpotLightNode
  38096. */
  38097. class ProjectorLightNode extends SpotLightNode {
  38098. static get type() {
  38099. return 'ProjectorLightNode';
  38100. }
  38101. update( frame ) {
  38102. super.update( frame );
  38103. const light = this.light;
  38104. this.penumbraCosNode.value = Math.min( Math.cos( light.angle * ( 1 - light.penumbra ) ), .99999 );
  38105. if ( light.aspect === null ) {
  38106. let aspect = 1;
  38107. if ( light.map !== null ) {
  38108. aspect = light.map.width / light.map.height;
  38109. }
  38110. light.shadow.aspect = aspect;
  38111. } else {
  38112. light.shadow.aspect = light.aspect;
  38113. }
  38114. }
  38115. /**
  38116. * Overwrites the default implementation to compute projection attenuation.
  38117. *
  38118. * @param {NodeBuilder} builder - The node builder.
  38119. * @return {Node<float>} The spot attenuation.
  38120. */
  38121. getSpotAttenuation( builder ) {
  38122. const attenuation = float( 0 );
  38123. const penumbraCos = this.penumbraCosNode;
  38124. // compute the fragment's position in the light's clip space
  38125. const spotLightCoord = lightShadowMatrix( this.light ).mul( builder.context.positionWorld || positionWorld );
  38126. // the sign of w determines whether the current fragment is in front or behind the light.
  38127. // to avoid a back-projection, it's important to only compute an attenuation if w is positive
  38128. If( spotLightCoord.w.greaterThan( 0 ), () => {
  38129. const projectionUV = spotLightCoord.xyz.div( spotLightCoord.w );
  38130. const boxDist = sdBox( projectionUV.xy.sub( vec2( 0.5 ) ), vec2( 0.5 ) );
  38131. const angleFactor = div( -1, sub( 1.0, acos( penumbraCos ) ).sub( 1.0 ) );
  38132. attenuation.assign( saturate( boxDist.mul( -2 ).mul( angleFactor ) ) );
  38133. } );
  38134. return attenuation;
  38135. }
  38136. }
  38137. /**
  38138. * Module for representing ambient lights as nodes.
  38139. *
  38140. * @augments AnalyticLightNode
  38141. */
  38142. class AmbientLightNode extends AnalyticLightNode {
  38143. static get type() {
  38144. return 'AmbientLightNode';
  38145. }
  38146. /**
  38147. * Constructs a new ambient light node.
  38148. *
  38149. * @param {?AmbientLight} [light=null] - The ambient light source.
  38150. */
  38151. constructor( light = null ) {
  38152. super( light );
  38153. }
  38154. setup( { context } ) {
  38155. context.irradiance.addAssign( this.colorNode );
  38156. }
  38157. }
  38158. /**
  38159. * Module for representing hemisphere lights as nodes.
  38160. *
  38161. * @augments AnalyticLightNode
  38162. */
  38163. class HemisphereLightNode extends AnalyticLightNode {
  38164. static get type() {
  38165. return 'HemisphereLightNode';
  38166. }
  38167. /**
  38168. * Constructs a new hemisphere light node.
  38169. *
  38170. * @param {?HemisphereLight} [light=null] - The hemisphere light source.
  38171. */
  38172. constructor( light = null ) {
  38173. super( light );
  38174. /**
  38175. * Uniform node representing the light's position.
  38176. *
  38177. * @type {UniformNode<vec3>}
  38178. */
  38179. this.lightPositionNode = lightPosition( light );
  38180. /**
  38181. * A node representing the light's direction.
  38182. *
  38183. * @type {Node<vec3>}
  38184. */
  38185. this.lightDirectionNode = this.lightPositionNode.normalize();
  38186. /**
  38187. * Uniform node representing the light's ground color.
  38188. *
  38189. * @type {UniformNode<vec3>}
  38190. */
  38191. this.groundColorNode = uniform( new Color() ).setGroup( renderGroup );
  38192. }
  38193. /**
  38194. * Overwritten to updated hemisphere light specific uniforms.
  38195. *
  38196. * @param {NodeFrame} frame - A reference to the current node frame.
  38197. */
  38198. update( frame ) {
  38199. const { light } = this;
  38200. super.update( frame );
  38201. this.lightPositionNode.object3d = light;
  38202. this.groundColorNode.value.copy( light.groundColor ).multiplyScalar( light.intensity );
  38203. }
  38204. setup( builder ) {
  38205. const { colorNode, groundColorNode, lightDirectionNode } = this;
  38206. const dotNL = normalWorld.dot( lightDirectionNode );
  38207. const hemiDiffuseWeight = dotNL.mul( 0.5 ).add( 0.5 );
  38208. const irradiance = mix( groundColorNode, colorNode, hemiDiffuseWeight );
  38209. builder.context.irradiance.addAssign( irradiance );
  38210. }
  38211. }
  38212. /**
  38213. * Module for representing light probes as nodes.
  38214. *
  38215. * @augments AnalyticLightNode
  38216. */
  38217. class LightProbeNode extends AnalyticLightNode {
  38218. static get type() {
  38219. return 'LightProbeNode';
  38220. }
  38221. /**
  38222. * Constructs a new light probe node.
  38223. *
  38224. * @param {?LightProbe} [light=null] - The light probe.
  38225. */
  38226. constructor( light = null ) {
  38227. super( light );
  38228. const array = [];
  38229. for ( let i = 0; i < 9; i ++ ) array.push( new Vector3() );
  38230. /**
  38231. * Light probe represented as a uniform of spherical harmonics.
  38232. *
  38233. * @type {UniformArrayNode}
  38234. */
  38235. this.lightProbe = uniformArray( array );
  38236. }
  38237. /**
  38238. * Overwritten to updated light probe specific uniforms.
  38239. *
  38240. * @param {NodeFrame} frame - A reference to the current node frame.
  38241. */
  38242. update( frame ) {
  38243. const { light } = this;
  38244. super.update( frame );
  38245. //
  38246. for ( let i = 0; i < 9; i ++ ) {
  38247. this.lightProbe.array[ i ].copy( light.sh.coefficients[ i ] ).multiplyScalar( light.intensity );
  38248. }
  38249. }
  38250. setup( builder ) {
  38251. const irradiance = getShIrradianceAt( normalWorld, this.lightProbe );
  38252. builder.context.irradiance.addAssign( irradiance );
  38253. }
  38254. }
  38255. /**
  38256. * Base class for node parsers. A derived parser must be implemented
  38257. * for each supported native shader language.
  38258. */
  38259. class NodeParser {
  38260. /**
  38261. * The method parses the given native code an returns a node function.
  38262. *
  38263. * @abstract
  38264. * @param {string} source - The native shader code.
  38265. * @return {NodeFunction} A node function.
  38266. */
  38267. parseFunction( /*source*/ ) {
  38268. warn( 'Abstract function.' );
  38269. }
  38270. }
  38271. /**
  38272. * Base class for node functions. A derived module must be implemented
  38273. * for each supported native shader language. Similar to other `Node*` modules,
  38274. * this class is only relevant during the building process and not used
  38275. * in user-level code.
  38276. */
  38277. class NodeFunction {
  38278. /**
  38279. * Constructs a new node function.
  38280. *
  38281. * @param {string} type - The node type. This type is the return type of the node function.
  38282. * @param {Array<NodeFunctionInput>} inputs - The function's inputs.
  38283. * @param {string} [name=''] - The function's name.
  38284. * @param {string} [precision=''] - The precision qualifier.
  38285. */
  38286. constructor( type, inputs, name = '', precision = '' ) {
  38287. /**
  38288. * The node type. This type is the return type of the node function.
  38289. *
  38290. * @type {string}
  38291. */
  38292. this.type = type;
  38293. /**
  38294. * The function's inputs.
  38295. *
  38296. * @type {Array<NodeFunctionInput>}
  38297. */
  38298. this.inputs = inputs;
  38299. /**
  38300. * The name of the uniform.
  38301. *
  38302. * @type {string}
  38303. * @default ''
  38304. */
  38305. this.name = name;
  38306. /**
  38307. * The precision qualifier.
  38308. *
  38309. * @type {string}
  38310. * @default ''
  38311. */
  38312. this.precision = precision;
  38313. }
  38314. /**
  38315. * This method returns the native code of the node function.
  38316. *
  38317. * @abstract
  38318. * @param {string} name - The function's name.
  38319. * @return {string} A shader code.
  38320. */
  38321. getCode( /*name = this.name*/ ) {
  38322. warn( 'Abstract function.' );
  38323. }
  38324. }
  38325. NodeFunction.isNodeFunction = true;
  38326. const declarationRegexp$1 = /^\s*(highp|mediump|lowp)?\s*([a-z_0-9]+)\s*([a-z_0-9]+)?\s*\(([\s\S]*?)\)/i;
  38327. const propertiesRegexp$1 = /[a-z_0-9]+/ig;
  38328. const pragmaMain = '#pragma main';
  38329. const parse$1 = ( source ) => {
  38330. source = source.trim();
  38331. const pragmaMainIndex = source.indexOf( pragmaMain );
  38332. const mainCode = pragmaMainIndex !== -1 ? source.slice( pragmaMainIndex + pragmaMain.length ) : source;
  38333. const declaration = mainCode.match( declarationRegexp$1 );
  38334. if ( declaration !== null && declaration.length === 5 ) {
  38335. // tokenizer
  38336. const inputsCode = declaration[ 4 ];
  38337. const propsMatches = [];
  38338. let nameMatch = null;
  38339. while ( ( nameMatch = propertiesRegexp$1.exec( inputsCode ) ) !== null ) {
  38340. propsMatches.push( nameMatch );
  38341. }
  38342. // parser
  38343. const inputs = [];
  38344. let i = 0;
  38345. while ( i < propsMatches.length ) {
  38346. const isConst = propsMatches[ i ][ 0 ] === 'const';
  38347. if ( isConst === true ) {
  38348. i ++;
  38349. }
  38350. let qualifier = propsMatches[ i ][ 0 ];
  38351. if ( qualifier === 'in' || qualifier === 'out' || qualifier === 'inout' ) {
  38352. i ++;
  38353. } else {
  38354. qualifier = '';
  38355. }
  38356. const type = propsMatches[ i ++ ][ 0 ];
  38357. let count = Number.parseInt( propsMatches[ i ][ 0 ] );
  38358. if ( Number.isNaN( count ) === false ) i ++;
  38359. else count = null;
  38360. const name = propsMatches[ i ++ ][ 0 ];
  38361. inputs.push( new NodeFunctionInput( type, name, count, qualifier, isConst ) );
  38362. }
  38363. //
  38364. const blockCode = mainCode.substring( declaration[ 0 ].length );
  38365. const name = declaration[ 3 ] !== undefined ? declaration[ 3 ] : '';
  38366. const type = declaration[ 2 ];
  38367. const precision = declaration[ 1 ] !== undefined ? declaration[ 1 ] : '';
  38368. const headerCode = pragmaMainIndex !== -1 ? source.slice( 0, pragmaMainIndex ) : '';
  38369. return {
  38370. type,
  38371. inputs,
  38372. name,
  38373. precision,
  38374. inputsCode,
  38375. blockCode,
  38376. headerCode
  38377. };
  38378. } else {
  38379. throw new Error( 'FunctionNode: Function is not a GLSL code.' );
  38380. }
  38381. };
  38382. /**
  38383. * This class represents a GLSL node function.
  38384. *
  38385. * @augments NodeFunction
  38386. */
  38387. class GLSLNodeFunction extends NodeFunction {
  38388. /**
  38389. * Constructs a new GLSL node function.
  38390. *
  38391. * @param {string} source - The GLSL source.
  38392. */
  38393. constructor( source ) {
  38394. const { type, inputs, name, precision, inputsCode, blockCode, headerCode } = parse$1( source );
  38395. super( type, inputs, name, precision );
  38396. this.inputsCode = inputsCode;
  38397. this.blockCode = blockCode;
  38398. this.headerCode = headerCode;
  38399. }
  38400. /**
  38401. * This method returns the GLSL code of the node function.
  38402. *
  38403. * @param {string} [name=this.name] - The function's name.
  38404. * @return {string} The shader code.
  38405. */
  38406. getCode( name = this.name ) {
  38407. let code;
  38408. const blockCode = this.blockCode;
  38409. if ( blockCode !== '' ) {
  38410. const { type, inputsCode, headerCode, precision } = this;
  38411. let declarationCode = `${ type } ${ name } ( ${ inputsCode.trim() } )`;
  38412. if ( precision !== '' ) {
  38413. declarationCode = `${ precision } ${ declarationCode }`;
  38414. }
  38415. code = headerCode + declarationCode + blockCode;
  38416. } else {
  38417. // interface function
  38418. code = '';
  38419. }
  38420. return code;
  38421. }
  38422. }
  38423. /**
  38424. * A GLSL node parser.
  38425. *
  38426. * @augments NodeParser
  38427. */
  38428. class GLSLNodeParser extends NodeParser {
  38429. /**
  38430. * The method parses the given GLSL code an returns a node function.
  38431. *
  38432. * @param {string} source - The GLSL code.
  38433. * @return {GLSLNodeFunction} A node function.
  38434. */
  38435. parseFunction( source ) {
  38436. return new GLSLNodeFunction( source );
  38437. }
  38438. }
  38439. const _outputNodeMap = new WeakMap();
  38440. const _chainKeys$2 = [];
  38441. const _cacheKeyValues = [];
  38442. /**
  38443. * This renderer module manages node-related objects and is the
  38444. * primary interface between the renderer and the node system.
  38445. *
  38446. * @private
  38447. * @augments DataMap
  38448. */
  38449. class Nodes extends DataMap {
  38450. /**
  38451. * Constructs a new nodes management component.
  38452. *
  38453. * @param {Renderer} renderer - The renderer.
  38454. * @param {Backend} backend - The renderer's backend.
  38455. */
  38456. constructor( renderer, backend ) {
  38457. super();
  38458. /**
  38459. * The renderer.
  38460. *
  38461. * @type {Renderer}
  38462. */
  38463. this.renderer = renderer;
  38464. /**
  38465. * The renderer's backend.
  38466. *
  38467. * @type {Backend}
  38468. */
  38469. this.backend = backend;
  38470. /**
  38471. * The node frame.
  38472. *
  38473. * @type {Renderer}
  38474. */
  38475. this.nodeFrame = new NodeFrame();
  38476. /**
  38477. * A cache for managing node builder states.
  38478. *
  38479. * @type {Map<number,NodeBuilderState>}
  38480. */
  38481. this.nodeBuilderCache = new Map();
  38482. /**
  38483. * A cache for managing data cache key data.
  38484. *
  38485. * @type {ChainMap}
  38486. */
  38487. this.callHashCache = new ChainMap();
  38488. /**
  38489. * A cache for managing node uniforms group data.
  38490. *
  38491. * @type {ChainMap}
  38492. */
  38493. this.groupsData = new ChainMap();
  38494. /**
  38495. * A cache for managing node objects of
  38496. * scene properties like fog or environments.
  38497. *
  38498. * @type {Object<string,WeakMap>}
  38499. */
  38500. this.cacheLib = {};
  38501. }
  38502. /**
  38503. * Returns `true` if the given node uniforms group must be updated or not.
  38504. *
  38505. * @param {NodeUniformsGroup} nodeUniformsGroup - The node uniforms group.
  38506. * @return {boolean} Whether the node uniforms group requires an update or not.
  38507. */
  38508. updateGroup( nodeUniformsGroup ) {
  38509. const groupNode = nodeUniformsGroup.groupNode;
  38510. const name = groupNode.name;
  38511. // objectGroup is always updated
  38512. if ( name === objectGroup.name ) return true;
  38513. // renderGroup is updated once per render/compute call
  38514. if ( name === renderGroup.name ) {
  38515. const uniformsGroupData = this.get( nodeUniformsGroup );
  38516. const renderId = this.nodeFrame.renderId;
  38517. if ( uniformsGroupData.renderId !== renderId ) {
  38518. uniformsGroupData.renderId = renderId;
  38519. return true;
  38520. }
  38521. return false;
  38522. }
  38523. // frameGroup is updated once per frame
  38524. if ( name === frameGroup.name ) {
  38525. const uniformsGroupData = this.get( nodeUniformsGroup );
  38526. const frameId = this.nodeFrame.frameId;
  38527. if ( uniformsGroupData.frameId !== frameId ) {
  38528. uniformsGroupData.frameId = frameId;
  38529. return true;
  38530. }
  38531. return false;
  38532. }
  38533. // other groups are updated just when groupNode.needsUpdate is true
  38534. _chainKeys$2[ 0 ] = groupNode;
  38535. _chainKeys$2[ 1 ] = nodeUniformsGroup;
  38536. let groupData = this.groupsData.get( _chainKeys$2 );
  38537. if ( groupData === undefined ) this.groupsData.set( _chainKeys$2, groupData = {} );
  38538. _chainKeys$2.length = 0;
  38539. if ( groupData.version !== groupNode.version ) {
  38540. groupData.version = groupNode.version;
  38541. return true;
  38542. }
  38543. return false;
  38544. }
  38545. /**
  38546. * Returns the cache key for the given render object.
  38547. *
  38548. * @param {RenderObject} renderObject - The render object.
  38549. * @return {number} The cache key.
  38550. */
  38551. getForRenderCacheKey( renderObject ) {
  38552. return renderObject.initialCacheKey;
  38553. }
  38554. /**
  38555. * Returns a node builder state for the given render object.
  38556. *
  38557. * @param {RenderObject} renderObject - The render object.
  38558. * @return {NodeBuilderState} The node builder state.
  38559. */
  38560. getForRender( renderObject ) {
  38561. const renderObjectData = this.get( renderObject );
  38562. let nodeBuilderState = renderObjectData.nodeBuilderState;
  38563. if ( nodeBuilderState === undefined ) {
  38564. const { nodeBuilderCache } = this;
  38565. const cacheKey = this.getForRenderCacheKey( renderObject );
  38566. nodeBuilderState = nodeBuilderCache.get( cacheKey );
  38567. if ( nodeBuilderState === undefined ) {
  38568. const createNodeBuilder = ( material ) => {
  38569. const nodeBuilder = this.backend.createNodeBuilder( renderObject.object, this.renderer );
  38570. nodeBuilder.scene = renderObject.scene;
  38571. nodeBuilder.material = material;
  38572. nodeBuilder.camera = renderObject.camera;
  38573. nodeBuilder.context.material = material;
  38574. nodeBuilder.lightsNode = renderObject.lightsNode;
  38575. nodeBuilder.environmentNode = this.getEnvironmentNode( renderObject.scene );
  38576. nodeBuilder.fogNode = this.getFogNode( renderObject.scene );
  38577. nodeBuilder.clippingContext = renderObject.clippingContext;
  38578. if ( this.renderer.getOutputRenderTarget() ? this.renderer.getOutputRenderTarget().multiview : false ) {
  38579. nodeBuilder.enableMultiview();
  38580. }
  38581. return nodeBuilder;
  38582. };
  38583. let nodeBuilder = createNodeBuilder( renderObject.material );
  38584. try {
  38585. nodeBuilder.build();
  38586. } catch ( e ) {
  38587. nodeBuilder = createNodeBuilder( new NodeMaterial() );
  38588. nodeBuilder.build();
  38589. error( 'TSL: ' + e );
  38590. }
  38591. nodeBuilderState = this._createNodeBuilderState( nodeBuilder );
  38592. nodeBuilderCache.set( cacheKey, nodeBuilderState );
  38593. }
  38594. nodeBuilderState.usedTimes ++;
  38595. renderObjectData.nodeBuilderState = nodeBuilderState;
  38596. }
  38597. return nodeBuilderState;
  38598. }
  38599. /**
  38600. * Deletes the given object from the internal data map
  38601. *
  38602. * @param {any} object - The object to delete.
  38603. * @return {?Object} The deleted dictionary.
  38604. */
  38605. delete( object ) {
  38606. if ( object.isRenderObject ) {
  38607. const nodeBuilderState = this.get( object ).nodeBuilderState;
  38608. nodeBuilderState.usedTimes --;
  38609. if ( nodeBuilderState.usedTimes === 0 ) {
  38610. this.nodeBuilderCache.delete( this.getForRenderCacheKey( object ) );
  38611. }
  38612. }
  38613. return super.delete( object );
  38614. }
  38615. /**
  38616. * Returns a node builder state for the given compute node.
  38617. *
  38618. * @param {Node} computeNode - The compute node.
  38619. * @return {NodeBuilderState} The node builder state.
  38620. */
  38621. getForCompute( computeNode ) {
  38622. const computeData = this.get( computeNode );
  38623. let nodeBuilderState = computeData.nodeBuilderState;
  38624. if ( nodeBuilderState === undefined ) {
  38625. const nodeBuilder = this.backend.createNodeBuilder( computeNode, this.renderer );
  38626. nodeBuilder.build();
  38627. nodeBuilderState = this._createNodeBuilderState( nodeBuilder );
  38628. computeData.nodeBuilderState = nodeBuilderState;
  38629. }
  38630. return nodeBuilderState;
  38631. }
  38632. /**
  38633. * Creates a node builder state for the given node builder.
  38634. *
  38635. * @private
  38636. * @param {NodeBuilder} nodeBuilder - The node builder.
  38637. * @return {NodeBuilderState} The node builder state.
  38638. */
  38639. _createNodeBuilderState( nodeBuilder ) {
  38640. return new NodeBuilderState(
  38641. nodeBuilder.vertexShader,
  38642. nodeBuilder.fragmentShader,
  38643. nodeBuilder.computeShader,
  38644. nodeBuilder.getAttributesArray(),
  38645. nodeBuilder.getBindings(),
  38646. nodeBuilder.updateNodes,
  38647. nodeBuilder.updateBeforeNodes,
  38648. nodeBuilder.updateAfterNodes,
  38649. nodeBuilder.observer,
  38650. nodeBuilder.transforms
  38651. );
  38652. }
  38653. /**
  38654. * Returns an environment node for the current configured
  38655. * scene environment.
  38656. *
  38657. * @param {Scene} scene - The scene.
  38658. * @return {Node} A node representing the current scene environment.
  38659. */
  38660. getEnvironmentNode( scene ) {
  38661. this.updateEnvironment( scene );
  38662. let environmentNode = null;
  38663. if ( scene.environmentNode && scene.environmentNode.isNode ) {
  38664. environmentNode = scene.environmentNode;
  38665. } else {
  38666. const sceneData = this.get( scene );
  38667. if ( sceneData.environmentNode ) {
  38668. environmentNode = sceneData.environmentNode;
  38669. }
  38670. }
  38671. return environmentNode;
  38672. }
  38673. /**
  38674. * Returns a background node for the current configured
  38675. * scene background.
  38676. *
  38677. * @param {Scene} scene - The scene.
  38678. * @return {Node} A node representing the current scene background.
  38679. */
  38680. getBackgroundNode( scene ) {
  38681. this.updateBackground( scene );
  38682. let backgroundNode = null;
  38683. if ( scene.backgroundNode && scene.backgroundNode.isNode ) {
  38684. backgroundNode = scene.backgroundNode;
  38685. } else {
  38686. const sceneData = this.get( scene );
  38687. if ( sceneData.backgroundNode ) {
  38688. backgroundNode = sceneData.backgroundNode;
  38689. }
  38690. }
  38691. return backgroundNode;
  38692. }
  38693. /**
  38694. * Returns a fog node for the current configured scene fog.
  38695. *
  38696. * @param {Scene} scene - The scene.
  38697. * @return {Node} A node representing the current scene fog.
  38698. */
  38699. getFogNode( scene ) {
  38700. this.updateFog( scene );
  38701. return scene.fogNode || this.get( scene ).fogNode || null;
  38702. }
  38703. /**
  38704. * Returns a cache key for the given scene and lights node.
  38705. * This key is used by `RenderObject` as a part of the dynamic
  38706. * cache key (a key that must be checked every time the render
  38707. * objects is drawn).
  38708. *
  38709. * @param {Scene} scene - The scene.
  38710. * @param {LightsNode} lightsNode - The lights node.
  38711. * @return {number} The cache key.
  38712. */
  38713. getCacheKey( scene, lightsNode ) {
  38714. _chainKeys$2[ 0 ] = scene;
  38715. _chainKeys$2[ 1 ] = lightsNode;
  38716. const callId = this.renderer.info.calls;
  38717. const cacheKeyData = this.callHashCache.get( _chainKeys$2 ) || {};
  38718. if ( cacheKeyData.callId !== callId ) {
  38719. const environmentNode = this.getEnvironmentNode( scene );
  38720. const fogNode = this.getFogNode( scene );
  38721. if ( lightsNode ) _cacheKeyValues.push( lightsNode.getCacheKey( true ) );
  38722. if ( environmentNode ) _cacheKeyValues.push( environmentNode.getCacheKey() );
  38723. if ( fogNode ) _cacheKeyValues.push( fogNode.getCacheKey() );
  38724. _cacheKeyValues.push( this.renderer.getOutputRenderTarget() && this.renderer.getOutputRenderTarget().multiview ? 1 : 0 );
  38725. _cacheKeyValues.push( this.renderer.shadowMap.enabled ? 1 : 0 );
  38726. _cacheKeyValues.push( this.renderer.shadowMap.type );
  38727. cacheKeyData.callId = callId;
  38728. cacheKeyData.cacheKey = hashArray( _cacheKeyValues );
  38729. this.callHashCache.set( _chainKeys$2, cacheKeyData );
  38730. _cacheKeyValues.length = 0;
  38731. }
  38732. _chainKeys$2.length = 0;
  38733. return cacheKeyData.cacheKey;
  38734. }
  38735. /**
  38736. * A boolean that indicates whether tone mapping should be enabled
  38737. * or not.
  38738. *
  38739. * @type {boolean}
  38740. */
  38741. get isToneMappingState() {
  38742. return this.renderer.getRenderTarget() ? false : true;
  38743. }
  38744. /**
  38745. * If a scene background is configured, this method makes sure to
  38746. * represent the background with a corresponding node-based implementation.
  38747. *
  38748. * @param {Scene} scene - The scene.
  38749. */
  38750. updateBackground( scene ) {
  38751. const sceneData = this.get( scene );
  38752. const background = scene.background;
  38753. if ( background ) {
  38754. const forceUpdate = ( scene.backgroundBlurriness === 0 && sceneData.backgroundBlurriness > 0 ) || ( scene.backgroundBlurriness > 0 && sceneData.backgroundBlurriness === 0 );
  38755. if ( sceneData.background !== background || forceUpdate ) {
  38756. const backgroundNode = this.getCacheNode( 'background', background, () => {
  38757. if ( background.isCubeTexture === true || ( background.mapping === EquirectangularReflectionMapping || background.mapping === EquirectangularRefractionMapping || background.mapping === CubeUVReflectionMapping ) ) {
  38758. if ( scene.backgroundBlurriness > 0 || background.mapping === CubeUVReflectionMapping ) {
  38759. return pmremTexture( background );
  38760. } else {
  38761. let envMap;
  38762. if ( background.isCubeTexture === true ) {
  38763. envMap = cubeTexture( background );
  38764. } else {
  38765. envMap = texture( background );
  38766. }
  38767. return cubeMapNode( envMap );
  38768. }
  38769. } else if ( background.isTexture === true ) {
  38770. return texture( background, screenUV.flipY() ).setUpdateMatrix( true );
  38771. } else if ( background.isColor !== true ) {
  38772. error( 'WebGPUNodes: Unsupported background configuration.', background );
  38773. }
  38774. }, forceUpdate );
  38775. sceneData.backgroundNode = backgroundNode;
  38776. sceneData.background = background;
  38777. sceneData.backgroundBlurriness = scene.backgroundBlurriness;
  38778. }
  38779. } else if ( sceneData.backgroundNode ) {
  38780. delete sceneData.backgroundNode;
  38781. delete sceneData.background;
  38782. }
  38783. }
  38784. /**
  38785. * This method is part of the caching of nodes which are used to represents the
  38786. * scene's background, fog or environment.
  38787. *
  38788. * @param {string} type - The type of object to cache.
  38789. * @param {Object} object - The object.
  38790. * @param {Function} callback - A callback that produces a node representation for the given object.
  38791. * @param {boolean} [forceUpdate=false] - Whether an update should be enforced or not.
  38792. * @return {Node} The node representation.
  38793. */
  38794. getCacheNode( type, object, callback, forceUpdate = false ) {
  38795. const nodeCache = this.cacheLib[ type ] || ( this.cacheLib[ type ] = new WeakMap() );
  38796. let node = nodeCache.get( object );
  38797. if ( node === undefined || forceUpdate ) {
  38798. node = callback();
  38799. nodeCache.set( object, node );
  38800. }
  38801. return node;
  38802. }
  38803. /**
  38804. * If a scene fog is configured, this method makes sure to
  38805. * represent the fog with a corresponding node-based implementation.
  38806. *
  38807. * @param {Scene} scene - The scene.
  38808. */
  38809. updateFog( scene ) {
  38810. const sceneData = this.get( scene );
  38811. const sceneFog = scene.fog;
  38812. if ( sceneFog ) {
  38813. if ( sceneData.fog !== sceneFog ) {
  38814. const fogNode = this.getCacheNode( 'fog', sceneFog, () => {
  38815. if ( sceneFog.isFogExp2 ) {
  38816. const color = reference( 'color', 'color', sceneFog ).setGroup( renderGroup );
  38817. const density = reference( 'density', 'float', sceneFog ).setGroup( renderGroup );
  38818. return fog( color, densityFogFactor( density ) );
  38819. } else if ( sceneFog.isFog ) {
  38820. const color = reference( 'color', 'color', sceneFog ).setGroup( renderGroup );
  38821. const near = reference( 'near', 'float', sceneFog ).setGroup( renderGroup );
  38822. const far = reference( 'far', 'float', sceneFog ).setGroup( renderGroup );
  38823. return fog( color, rangeFogFactor( near, far ) );
  38824. } else {
  38825. error( 'Renderer: Unsupported fog configuration.', sceneFog );
  38826. }
  38827. } );
  38828. sceneData.fogNode = fogNode;
  38829. sceneData.fog = sceneFog;
  38830. }
  38831. } else {
  38832. delete sceneData.fogNode;
  38833. delete sceneData.fog;
  38834. }
  38835. }
  38836. /**
  38837. * If a scene environment is configured, this method makes sure to
  38838. * represent the environment with a corresponding node-based implementation.
  38839. *
  38840. * @param {Scene} scene - The scene.
  38841. */
  38842. updateEnvironment( scene ) {
  38843. const sceneData = this.get( scene );
  38844. const environment = scene.environment;
  38845. if ( environment ) {
  38846. if ( sceneData.environment !== environment ) {
  38847. const environmentNode = this.getCacheNode( 'environment', environment, () => {
  38848. if ( environment.isCubeTexture === true ) {
  38849. return cubeTexture( environment );
  38850. } else if ( environment.isTexture === true ) {
  38851. return texture( environment );
  38852. } else {
  38853. error( 'Nodes: Unsupported environment configuration.', environment );
  38854. }
  38855. } );
  38856. sceneData.environmentNode = environmentNode;
  38857. sceneData.environment = environment;
  38858. }
  38859. } else if ( sceneData.environmentNode ) {
  38860. delete sceneData.environmentNode;
  38861. delete sceneData.environment;
  38862. }
  38863. }
  38864. getNodeFrame( renderer = this.renderer, scene = null, object = null, camera = null, material = null ) {
  38865. const nodeFrame = this.nodeFrame;
  38866. nodeFrame.renderer = renderer;
  38867. nodeFrame.scene = scene;
  38868. nodeFrame.object = object;
  38869. nodeFrame.camera = camera;
  38870. nodeFrame.material = material;
  38871. return nodeFrame;
  38872. }
  38873. getNodeFrameForRender( renderObject ) {
  38874. return this.getNodeFrame( renderObject.renderer, renderObject.scene, renderObject.object, renderObject.camera, renderObject.material );
  38875. }
  38876. /**
  38877. * Returns the current output cache key.
  38878. *
  38879. * @return {string} The output cache key.
  38880. */
  38881. getOutputCacheKey() {
  38882. const renderer = this.renderer;
  38883. return renderer.toneMapping + ',' + renderer.currentColorSpace + ',' + renderer.xr.isPresenting;
  38884. }
  38885. /**
  38886. * Checks if the output configuration (tone mapping and color space) for
  38887. * the given target has changed.
  38888. *
  38889. * @param {Texture} outputTarget - The output target.
  38890. * @return {boolean} Whether the output configuration has changed or not.
  38891. */
  38892. hasOutputChange( outputTarget ) {
  38893. const cacheKey = _outputNodeMap.get( outputTarget );
  38894. return cacheKey !== this.getOutputCacheKey();
  38895. }
  38896. /**
  38897. * Returns a node that represents the output configuration (tone mapping and
  38898. * color space) for the current target.
  38899. *
  38900. * @param {Texture} outputTarget - The output target.
  38901. * @return {Node} The output node.
  38902. */
  38903. getOutputNode( outputTarget ) {
  38904. const renderer = this.renderer;
  38905. const cacheKey = this.getOutputCacheKey();
  38906. const output = outputTarget.isArrayTexture ?
  38907. texture3D( outputTarget, vec3( screenUV, builtin( 'gl_ViewID_OVR' ) ) ).renderOutput( renderer.toneMapping, renderer.currentColorSpace ) :
  38908. texture( outputTarget, screenUV ).renderOutput( renderer.toneMapping, renderer.currentColorSpace );
  38909. _outputNodeMap.set( outputTarget, cacheKey );
  38910. return output;
  38911. }
  38912. /**
  38913. * Triggers the call of `updateBefore()` methods
  38914. * for all nodes of the given render object.
  38915. *
  38916. * @param {RenderObject} renderObject - The render object.
  38917. */
  38918. updateBefore( renderObject ) {
  38919. const nodeBuilder = renderObject.getNodeBuilderState();
  38920. for ( const node of nodeBuilder.updateBeforeNodes ) {
  38921. // update frame state for each node
  38922. this.getNodeFrameForRender( renderObject ).updateBeforeNode( node );
  38923. }
  38924. }
  38925. /**
  38926. * Triggers the call of `updateAfter()` methods
  38927. * for all nodes of the given render object.
  38928. *
  38929. * @param {RenderObject} renderObject - The render object.
  38930. */
  38931. updateAfter( renderObject ) {
  38932. const nodeBuilder = renderObject.getNodeBuilderState();
  38933. for ( const node of nodeBuilder.updateAfterNodes ) {
  38934. // update frame state for each node
  38935. this.getNodeFrameForRender( renderObject ).updateAfterNode( node );
  38936. }
  38937. }
  38938. /**
  38939. * Triggers the call of `update()` methods
  38940. * for all nodes of the given compute node.
  38941. *
  38942. * @param {Node} computeNode - The compute node.
  38943. */
  38944. updateForCompute( computeNode ) {
  38945. const nodeFrame = this.getNodeFrame();
  38946. const nodeBuilder = this.getForCompute( computeNode );
  38947. for ( const node of nodeBuilder.updateNodes ) {
  38948. nodeFrame.updateNode( node );
  38949. }
  38950. }
  38951. /**
  38952. * Triggers the call of `update()` methods
  38953. * for all nodes of the given compute node.
  38954. *
  38955. * @param {RenderObject} renderObject - The render object.
  38956. */
  38957. updateForRender( renderObject ) {
  38958. const nodeFrame = this.getNodeFrameForRender( renderObject );
  38959. const nodeBuilder = renderObject.getNodeBuilderState();
  38960. for ( const node of nodeBuilder.updateNodes ) {
  38961. nodeFrame.updateNode( node );
  38962. }
  38963. }
  38964. /**
  38965. * Returns `true` if the given render object requires a refresh.
  38966. *
  38967. * @param {RenderObject} renderObject - The render object.
  38968. * @return {boolean} Whether the given render object requires a refresh or not.
  38969. */
  38970. needsRefresh( renderObject ) {
  38971. const nodeFrame = this.getNodeFrameForRender( renderObject );
  38972. const monitor = renderObject.getMonitor();
  38973. return monitor.needsRefresh( renderObject, nodeFrame );
  38974. }
  38975. /**
  38976. * Frees the internal resources.
  38977. */
  38978. dispose() {
  38979. super.dispose();
  38980. this.nodeFrame = new NodeFrame();
  38981. this.nodeBuilderCache = new Map();
  38982. this.cacheLib = {};
  38983. }
  38984. }
  38985. const _plane = /*@__PURE__*/ new Plane();
  38986. /**
  38987. * Represents the state that is used to perform clipping via clipping planes.
  38988. * There is a default clipping context for each render context. When the
  38989. * scene holds instances of `ClippingGroup`, there will be a context for each
  38990. * group.
  38991. *
  38992. * @private
  38993. */
  38994. class ClippingContext {
  38995. /**
  38996. * Constructs a new clipping context.
  38997. *
  38998. * @param {?ClippingContext} [parentContext=null] - A reference to the parent clipping context.
  38999. */
  39000. constructor( parentContext = null ) {
  39001. /**
  39002. * The clipping context's version.
  39003. *
  39004. * @type {number}
  39005. * @readonly
  39006. */
  39007. this.version = 0;
  39008. /**
  39009. * Whether the intersection of the clipping planes is used to clip objects, rather than their union.
  39010. *
  39011. * @type {?boolean}
  39012. * @default null
  39013. */
  39014. this.clipIntersection = null;
  39015. /**
  39016. * The clipping context's cache key.
  39017. *
  39018. * @type {string}
  39019. */
  39020. this.cacheKey = '';
  39021. /**
  39022. * Whether the shadow pass is active or not.
  39023. *
  39024. * @type {boolean}
  39025. * @default false
  39026. */
  39027. this.shadowPass = false;
  39028. /**
  39029. * The view normal matrix.
  39030. *
  39031. * @type {Matrix3}
  39032. */
  39033. this.viewNormalMatrix = new Matrix3();
  39034. /**
  39035. * Internal cache for maintaining clipping contexts.
  39036. *
  39037. * @type {WeakMap<ClippingGroup,ClippingContext>}
  39038. */
  39039. this.clippingGroupContexts = new WeakMap();
  39040. /**
  39041. * The intersection planes.
  39042. *
  39043. * @type {Array<Vector4>}
  39044. */
  39045. this.intersectionPlanes = [];
  39046. /**
  39047. * The intersection planes.
  39048. *
  39049. * @type {Array<Vector4>}
  39050. */
  39051. this.unionPlanes = [];
  39052. /**
  39053. * The version of the clipping context's parent context.
  39054. *
  39055. * @type {?number}
  39056. * @readonly
  39057. */
  39058. this.parentVersion = null;
  39059. if ( parentContext !== null ) {
  39060. this.viewNormalMatrix = parentContext.viewNormalMatrix;
  39061. this.clippingGroupContexts = parentContext.clippingGroupContexts;
  39062. this.shadowPass = parentContext.shadowPass;
  39063. this.viewMatrix = parentContext.viewMatrix;
  39064. }
  39065. }
  39066. /**
  39067. * Projects the given source clipping planes and writes the result into the
  39068. * destination array.
  39069. *
  39070. * @param {Array<Plane>} source - The source clipping planes.
  39071. * @param {Array<Vector4>} destination - The destination.
  39072. * @param {number} offset - The offset.
  39073. */
  39074. projectPlanes( source, destination, offset ) {
  39075. const l = source.length;
  39076. for ( let i = 0; i < l; i ++ ) {
  39077. _plane.copy( source[ i ] ).applyMatrix4( this.viewMatrix, this.viewNormalMatrix );
  39078. const v = destination[ offset + i ];
  39079. const normal = _plane.normal;
  39080. v.x = - normal.x;
  39081. v.y = - normal.y;
  39082. v.z = - normal.z;
  39083. v.w = _plane.constant;
  39084. }
  39085. }
  39086. /**
  39087. * Updates the root clipping context of a scene.
  39088. *
  39089. * @param {Scene} scene - The scene.
  39090. * @param {Camera} camera - The camera that is used to render the scene.
  39091. */
  39092. updateGlobal( scene, camera ) {
  39093. this.shadowPass = ( scene.overrideMaterial !== null && scene.overrideMaterial.isShadowPassMaterial );
  39094. this.viewMatrix = camera.matrixWorldInverse;
  39095. this.viewNormalMatrix.getNormalMatrix( this.viewMatrix );
  39096. }
  39097. /**
  39098. * Updates the clipping context.
  39099. *
  39100. * @param {ClippingContext} parentContext - The parent context.
  39101. * @param {ClippingGroup} clippingGroup - The clipping group this context belongs to.
  39102. */
  39103. update( parentContext, clippingGroup ) {
  39104. let update = false;
  39105. if ( parentContext.version !== this.parentVersion ) {
  39106. this.intersectionPlanes = Array.from( parentContext.intersectionPlanes );
  39107. this.unionPlanes = Array.from( parentContext.unionPlanes );
  39108. this.parentVersion = parentContext.version;
  39109. }
  39110. if ( this.clipIntersection !== clippingGroup.clipIntersection ) {
  39111. this.clipIntersection = clippingGroup.clipIntersection;
  39112. if ( this.clipIntersection ) {
  39113. this.unionPlanes.length = parentContext.unionPlanes.length;
  39114. } else {
  39115. this.intersectionPlanes.length = parentContext.intersectionPlanes.length;
  39116. }
  39117. }
  39118. const srcClippingPlanes = clippingGroup.clippingPlanes;
  39119. const l = srcClippingPlanes.length;
  39120. let dstClippingPlanes;
  39121. let offset;
  39122. if ( this.clipIntersection ) {
  39123. dstClippingPlanes = this.intersectionPlanes;
  39124. offset = parentContext.intersectionPlanes.length;
  39125. } else {
  39126. dstClippingPlanes = this.unionPlanes;
  39127. offset = parentContext.unionPlanes.length;
  39128. }
  39129. if ( dstClippingPlanes.length !== offset + l ) {
  39130. dstClippingPlanes.length = offset + l;
  39131. for ( let i = 0; i < l; i ++ ) {
  39132. dstClippingPlanes[ offset + i ] = new Vector4();
  39133. }
  39134. update = true;
  39135. }
  39136. this.projectPlanes( srcClippingPlanes, dstClippingPlanes, offset );
  39137. if ( update ) {
  39138. this.version ++;
  39139. this.cacheKey = `${ this.intersectionPlanes.length }:${ this.unionPlanes.length }`;
  39140. }
  39141. }
  39142. /**
  39143. * Returns a clipping context for the given clipping group.
  39144. *
  39145. * @param {ClippingGroup} clippingGroup - The clipping group.
  39146. * @return {ClippingContext} The clipping context.
  39147. */
  39148. getGroupContext( clippingGroup ) {
  39149. if ( this.shadowPass && ! clippingGroup.clipShadows ) return this;
  39150. let context = this.clippingGroupContexts.get( clippingGroup );
  39151. if ( context === undefined ) {
  39152. context = new ClippingContext( this );
  39153. this.clippingGroupContexts.set( clippingGroup, context );
  39154. }
  39155. context.update( this, clippingGroup );
  39156. return context;
  39157. }
  39158. /**
  39159. * The count of union clipping planes.
  39160. *
  39161. * @type {number}
  39162. * @readonly
  39163. */
  39164. get unionClippingCount() {
  39165. return this.unionPlanes.length;
  39166. }
  39167. }
  39168. /**
  39169. * This module is used to represent render bundles inside the renderer
  39170. * for further processing.
  39171. *
  39172. * @private
  39173. */
  39174. class RenderBundle {
  39175. /**
  39176. * Constructs a new bundle group.
  39177. *
  39178. * @param {BundleGroup} bundleGroup - The bundle group.
  39179. * @param {Camera} camera - The camera the bundle group is rendered with.
  39180. */
  39181. constructor( bundleGroup, camera ) {
  39182. this.bundleGroup = bundleGroup;
  39183. this.camera = camera;
  39184. }
  39185. }
  39186. const _chainKeys$1 = [];
  39187. /**
  39188. * This renderer module manages render bundles.
  39189. *
  39190. * @private
  39191. */
  39192. class RenderBundles {
  39193. /**
  39194. * Constructs a new render bundle management component.
  39195. */
  39196. constructor() {
  39197. /**
  39198. * A chain map for maintaining the render bundles.
  39199. *
  39200. * @type {ChainMap}
  39201. */
  39202. this.bundles = new ChainMap();
  39203. }
  39204. /**
  39205. * Returns a render bundle for the given bundle group and camera.
  39206. *
  39207. * @param {BundleGroup} bundleGroup - The bundle group.
  39208. * @param {Camera} camera - The camera the bundle group is rendered with.
  39209. * @return {RenderBundle} The render bundle.
  39210. */
  39211. get( bundleGroup, camera ) {
  39212. const bundles = this.bundles;
  39213. _chainKeys$1[ 0 ] = bundleGroup;
  39214. _chainKeys$1[ 1 ] = camera;
  39215. let bundle = bundles.get( _chainKeys$1 );
  39216. if ( bundle === undefined ) {
  39217. bundle = new RenderBundle( bundleGroup, camera );
  39218. bundles.set( _chainKeys$1, bundle );
  39219. }
  39220. _chainKeys$1.length = 0;
  39221. return bundle;
  39222. }
  39223. /**
  39224. * Frees all internal resources.
  39225. */
  39226. dispose() {
  39227. this.bundles = new ChainMap();
  39228. }
  39229. }
  39230. /**
  39231. * The purpose of a node library is to assign node implementations
  39232. * to existing library features. In `WebGPURenderer` lights, materials
  39233. * which are not based on `NodeMaterial` as well as tone mapping techniques
  39234. * are implemented with node-based modules.
  39235. *
  39236. * @private
  39237. */
  39238. class NodeLibrary {
  39239. /**
  39240. * Constructs a new node library.
  39241. */
  39242. constructor() {
  39243. /**
  39244. * A weak map that maps lights to light nodes.
  39245. *
  39246. * @type {WeakMap<Light.constructor,AnalyticLightNode.constructor>}
  39247. */
  39248. this.lightNodes = new WeakMap();
  39249. /**
  39250. * A map that maps materials to node materials.
  39251. *
  39252. * @type {Map<string,NodeMaterial.constructor>}
  39253. */
  39254. this.materialNodes = new Map();
  39255. /**
  39256. * A map that maps tone mapping techniques (constants)
  39257. * to tone mapping node functions.
  39258. *
  39259. * @type {Map<number,Function>}
  39260. */
  39261. this.toneMappingNodes = new Map();
  39262. }
  39263. /**
  39264. * Returns a matching node material instance for the given material object.
  39265. *
  39266. * This method also assigns/copies the properties of the given material object
  39267. * to the node material. This is done to make sure the current material
  39268. * configuration carries over to the node version.
  39269. *
  39270. * @param {Material} material - A material.
  39271. * @return {NodeMaterial} The corresponding node material.
  39272. */
  39273. fromMaterial( material ) {
  39274. if ( material.isNodeMaterial ) return material;
  39275. let nodeMaterial = null;
  39276. const nodeMaterialClass = this.getMaterialNodeClass( material.type );
  39277. if ( nodeMaterialClass !== null ) {
  39278. nodeMaterial = new nodeMaterialClass();
  39279. for ( const key in material ) {
  39280. nodeMaterial[ key ] = material[ key ];
  39281. }
  39282. }
  39283. return nodeMaterial;
  39284. }
  39285. /**
  39286. * Adds a tone mapping node function for a tone mapping technique (constant).
  39287. *
  39288. * @param {Function} toneMappingNode - The tone mapping node function.
  39289. * @param {number} toneMapping - The tone mapping.
  39290. */
  39291. addToneMapping( toneMappingNode, toneMapping ) {
  39292. this.addType( toneMappingNode, toneMapping, this.toneMappingNodes );
  39293. }
  39294. /**
  39295. * Returns a tone mapping node function for a tone mapping technique (constant).
  39296. *
  39297. * @param {number} toneMapping - The tone mapping.
  39298. * @return {?Function} The tone mapping node function. Returns `null` if no node function is found.
  39299. */
  39300. getToneMappingFunction( toneMapping ) {
  39301. return this.toneMappingNodes.get( toneMapping ) || null;
  39302. }
  39303. /**
  39304. * Returns a node material class definition for a material type.
  39305. *
  39306. * @param {string} materialType - The material type.
  39307. * @return {?NodeMaterial.constructor} The node material class definition. Returns `null` if no node material is found.
  39308. */
  39309. getMaterialNodeClass( materialType ) {
  39310. return this.materialNodes.get( materialType ) || null;
  39311. }
  39312. /**
  39313. * Adds a node material class definition for a given material type.
  39314. *
  39315. * @param {NodeMaterial.constructor} materialNodeClass - The node material class definition.
  39316. * @param {string} materialClassType - The material type.
  39317. */
  39318. addMaterial( materialNodeClass, materialClassType ) {
  39319. this.addType( materialNodeClass, materialClassType, this.materialNodes );
  39320. }
  39321. /**
  39322. * Returns a light node class definition for a light class definition.
  39323. *
  39324. * @param {Light.constructor} light - The light class definition.
  39325. * @return {?AnalyticLightNode.constructor} The light node class definition. Returns `null` if no light node is found.
  39326. */
  39327. getLightNodeClass( light ) {
  39328. return this.lightNodes.get( light ) || null;
  39329. }
  39330. /**
  39331. * Adds a light node class definition for a given light class definition.
  39332. *
  39333. * @param {AnalyticLightNode.constructor} lightNodeClass - The light node class definition.
  39334. * @param {Light.constructor} lightClass - The light class definition.
  39335. */
  39336. addLight( lightNodeClass, lightClass ) {
  39337. this.addClass( lightNodeClass, lightClass, this.lightNodes );
  39338. }
  39339. /**
  39340. * Adds a node class definition for the given type to the provided type library.
  39341. *
  39342. * @param {Node.constructor} nodeClass - The node class definition.
  39343. * @param {number|string} type - The object type.
  39344. * @param {Map<number|string,Node.constructor>} library - The type library.
  39345. */
  39346. addType( nodeClass, type, library ) {
  39347. if ( library.has( type ) ) {
  39348. warn( `Redefinition of node ${ type }` );
  39349. return;
  39350. }
  39351. if ( typeof nodeClass !== 'function' ) throw new Error( `Node class ${ nodeClass.name } is not a class.` );
  39352. if ( typeof type === 'function' || typeof type === 'object' ) throw new Error( `Base class ${ type } is not a class.` );
  39353. library.set( type, nodeClass );
  39354. }
  39355. /**
  39356. * Adds a node class definition for the given class definition to the provided type library.
  39357. *
  39358. * @param {Node.constructor} nodeClass - The node class definition.
  39359. * @param {Node.constructor} baseClass - The class definition.
  39360. * @param {WeakMap<Node.constructor, Node.constructor>} library - The type library.
  39361. */
  39362. addClass( nodeClass, baseClass, library ) {
  39363. if ( library.has( baseClass ) ) {
  39364. warn( `Redefinition of node ${ baseClass.name }` );
  39365. return;
  39366. }
  39367. if ( typeof nodeClass !== 'function' ) throw new Error( `Node class ${ nodeClass.name } is not a class.` );
  39368. if ( typeof baseClass !== 'function' ) throw new Error( `Base class ${ baseClass.name } is not a class.` );
  39369. library.set( baseClass, nodeClass );
  39370. }
  39371. }
  39372. const _defaultLights = /*@__PURE__*/ new LightsNode();
  39373. const _chainKeys = [];
  39374. /**
  39375. * This renderer module manages the lights nodes which are unique
  39376. * per scene and camera combination.
  39377. *
  39378. * The lights node itself is later configured in the render list
  39379. * with the actual lights from the scene.
  39380. *
  39381. * @private
  39382. * @augments ChainMap
  39383. */
  39384. class Lighting extends ChainMap {
  39385. /**
  39386. * Constructs a lighting management component.
  39387. */
  39388. constructor() {
  39389. super();
  39390. }
  39391. /**
  39392. * Creates a new lights node for the given array of lights.
  39393. *
  39394. * @param {Array<Light>} lights - The render object.
  39395. * @return {LightsNode} The lights node.
  39396. */
  39397. createNode( lights = [] ) {
  39398. return new LightsNode().setLights( lights );
  39399. }
  39400. /**
  39401. * Returns a lights node for the given scene and camera.
  39402. *
  39403. * @param {Scene} scene - The scene.
  39404. * @param {Camera} camera - The camera.
  39405. * @return {LightsNode} The lights node.
  39406. */
  39407. getNode( scene, camera ) {
  39408. // ignore post-processing
  39409. if ( scene.isQuadMesh ) return _defaultLights;
  39410. _chainKeys[ 0 ] = scene;
  39411. _chainKeys[ 1 ] = camera;
  39412. let node = this.get( _chainKeys );
  39413. if ( node === undefined ) {
  39414. node = this.createNode();
  39415. this.set( _chainKeys, node );
  39416. }
  39417. _chainKeys.length = 0;
  39418. return node;
  39419. }
  39420. }
  39421. /**
  39422. * A special type of render target that is used when rendering
  39423. * with the WebXR Device API.
  39424. *
  39425. * @private
  39426. * @augments RenderTarget
  39427. */
  39428. class XRRenderTarget extends RenderTarget {
  39429. /**
  39430. * Constructs a new XR render target.
  39431. *
  39432. * @param {number} [width=1] - The width of the render target.
  39433. * @param {number} [height=1] - The height of the render target.
  39434. * @param {Object} [options={}] - The configuration options.
  39435. */
  39436. constructor( width = 1, height = 1, options = {} ) {
  39437. super( width, height, options );
  39438. /**
  39439. * This flag can be used for type testing.
  39440. *
  39441. * @type {boolean}
  39442. * @readonly
  39443. * @default true
  39444. */
  39445. this.isXRRenderTarget = true;
  39446. /**
  39447. * Whether the attachments of the render target
  39448. * are defined by external textures. This flag is
  39449. * set to `true` when using the WebXR Layers API.
  39450. *
  39451. * @private
  39452. * @type {boolean}
  39453. * @default false
  39454. */
  39455. this._hasExternalTextures = false;
  39456. /**
  39457. * Whether a depth buffer should automatically be allocated
  39458. * for this XR render target or not.
  39459. *
  39460. * Allocating a depth buffer is the default behavior of XR render
  39461. * targets. However, when using the WebXR Layers API, this flag
  39462. * must be set to `false` when the `ignoreDepthValues` property of
  39463. * the projection layers evaluates to `false`.
  39464. *
  39465. * Reference: {@link https://www.w3.org/TR/webxrlayers-1/#dom-xrprojectionlayer-ignoredepthvalues}.
  39466. *
  39467. * @private
  39468. * @type {boolean}
  39469. * @default true
  39470. */
  39471. this._autoAllocateDepthBuffer = true;
  39472. /**
  39473. * Whether this render target is associated with a XRWebGLLayer.
  39474. *
  39475. * A XRWebGLLayer points to an opaque framebuffer. Basically,
  39476. * this means that you don't have access to its bound color,
  39477. * stencil and depth buffers. We need to handle this framebuffer
  39478. * differently since its textures are always bound.
  39479. *
  39480. * @private
  39481. * @type {boolean}
  39482. * @default false
  39483. * */
  39484. this._isOpaqueFramebuffer = false;
  39485. }
  39486. copy( source ) {
  39487. super.copy( source );
  39488. this._hasExternalTextures = source._hasExternalTextures;
  39489. this._autoAllocateDepthBuffer = source._autoAllocateDepthBuffer;
  39490. this._isOpaqueFramebuffer = source._isOpaqueFramebuffer;
  39491. return this;
  39492. }
  39493. }
  39494. const _cameraLPos = /*@__PURE__*/ new Vector3();
  39495. const _cameraRPos = /*@__PURE__*/ new Vector3();
  39496. /**
  39497. * The XR manager is built on top of the WebXR Device API to
  39498. * manage XR sessions with `WebGPURenderer`.
  39499. *
  39500. * XR is currently only supported with a WebGL 2 backend.
  39501. *
  39502. * @augments EventDispatcher
  39503. */
  39504. class XRManager extends EventDispatcher {
  39505. /**
  39506. * Constructs a new XR manager.
  39507. *
  39508. * @param {Renderer} renderer - The renderer.
  39509. * @param {boolean} [multiview=false] - Enables multiview if the device supports it.
  39510. */
  39511. constructor( renderer, multiview = false ) {
  39512. super();
  39513. /**
  39514. * This flag globally enables XR rendering.
  39515. *
  39516. * @type {boolean}
  39517. * @default false
  39518. */
  39519. this.enabled = false;
  39520. /**
  39521. * Whether the XR device is currently presenting or not.
  39522. *
  39523. * @type {boolean}
  39524. * @default false
  39525. * @readonly
  39526. */
  39527. this.isPresenting = false;
  39528. /**
  39529. * Whether the XR camera should automatically be updated or not.
  39530. *
  39531. * @type {boolean}
  39532. * @default true
  39533. */
  39534. this.cameraAutoUpdate = true;
  39535. /**
  39536. * The renderer.
  39537. *
  39538. * @private
  39539. * @type {Renderer}
  39540. */
  39541. this._renderer = renderer;
  39542. // camera
  39543. /**
  39544. * Represents the camera for the left eye.
  39545. *
  39546. * @private
  39547. * @type {PerspectiveCamera}
  39548. */
  39549. this._cameraL = new PerspectiveCamera();
  39550. this._cameraL.viewport = new Vector4();
  39551. /**
  39552. * Represents the camera for the right eye.
  39553. *
  39554. * @private
  39555. * @type {PerspectiveCamera}
  39556. */
  39557. this._cameraR = new PerspectiveCamera();
  39558. this._cameraR.viewport = new Vector4();
  39559. /**
  39560. * A list of cameras used for rendering the XR views.
  39561. *
  39562. * @private
  39563. * @type {Array<Camera>}
  39564. */
  39565. this._cameras = [ this._cameraL, this._cameraR ];
  39566. /**
  39567. * The main XR camera.
  39568. *
  39569. * @private
  39570. * @type {ArrayCamera}
  39571. */
  39572. this._cameraXR = new ArrayCamera();
  39573. /**
  39574. * The current near value of the XR camera.
  39575. *
  39576. * @private
  39577. * @type {?number}
  39578. * @default null
  39579. */
  39580. this._currentDepthNear = null;
  39581. /**
  39582. * The current far value of the XR camera.
  39583. *
  39584. * @private
  39585. * @type {?number}
  39586. * @default null
  39587. */
  39588. this._currentDepthFar = null;
  39589. /**
  39590. * A list of WebXR controllers requested by the application.
  39591. *
  39592. * @private
  39593. * @type {Array<WebXRController>}
  39594. */
  39595. this._controllers = [];
  39596. /**
  39597. * A list of XR input source. Each input source belongs to
  39598. * an instance of WebXRController.
  39599. *
  39600. * @private
  39601. * @type {Array<XRInputSource?>}
  39602. */
  39603. this._controllerInputSources = [];
  39604. /**
  39605. * The XR render target that represents the rendering destination
  39606. * during an active XR session.
  39607. *
  39608. * @private
  39609. * @type {?RenderTarget}
  39610. * @default null
  39611. */
  39612. this._xrRenderTarget = null;
  39613. /**
  39614. * An array holding all the non-projection layers
  39615. *
  39616. * @private
  39617. * @type {Array<Object>}
  39618. * @default []
  39619. */
  39620. this._layers = [];
  39621. /**
  39622. * Whether the XR session uses layers.
  39623. *
  39624. * @private
  39625. * @type {boolean}
  39626. * @default false
  39627. */
  39628. this._sessionUsesLayers = false;
  39629. /**
  39630. * Whether the device supports binding gl objects.
  39631. *
  39632. * @private
  39633. * @type {boolean}
  39634. * @readonly
  39635. */
  39636. this._supportsGlBinding = typeof XRWebGLBinding !== 'undefined';
  39637. this._frameBufferTargets = null;
  39638. /**
  39639. * Helper function to create native WebXR Layer.
  39640. *
  39641. * @private
  39642. * @type {Function}
  39643. */
  39644. this._createXRLayer = createXRLayer.bind( this );
  39645. /**
  39646. * The current WebGL context.
  39647. *
  39648. * @private
  39649. * @type {?WebGL2RenderingContext}
  39650. * @default null
  39651. */
  39652. this._gl = null;
  39653. /**
  39654. * The current animation context.
  39655. *
  39656. * @private
  39657. * @type {?Window}
  39658. * @default null
  39659. */
  39660. this._currentAnimationContext = null;
  39661. /**
  39662. * The current animation loop.
  39663. *
  39664. * @private
  39665. * @type {?Function}
  39666. * @default null
  39667. */
  39668. this._currentAnimationLoop = null;
  39669. /**
  39670. * The current pixel ratio.
  39671. *
  39672. * @private
  39673. * @type {?number}
  39674. * @default null
  39675. */
  39676. this._currentPixelRatio = null;
  39677. /**
  39678. * The current size of the renderer's canvas
  39679. * in logical pixel unit.
  39680. *
  39681. * @private
  39682. * @type {Vector2}
  39683. */
  39684. this._currentSize = new Vector2();
  39685. /**
  39686. * The default event listener for handling events inside a XR session.
  39687. *
  39688. * @private
  39689. * @type {Function}
  39690. */
  39691. this._onSessionEvent = onSessionEvent.bind( this );
  39692. /**
  39693. * The event listener for handling the end of a XR session.
  39694. *
  39695. * @private
  39696. * @type {Function}
  39697. */
  39698. this._onSessionEnd = onSessionEnd.bind( this );
  39699. /**
  39700. * The event listener for handling the `inputsourceschange` event.
  39701. *
  39702. * @private
  39703. * @type {Function}
  39704. */
  39705. this._onInputSourcesChange = onInputSourcesChange.bind( this );
  39706. /**
  39707. * The animation loop which is used as a replacement for the default
  39708. * animation loop of the application. It is only used when a XR session
  39709. * is active.
  39710. *
  39711. * @private
  39712. * @type {Function}
  39713. */
  39714. this._onAnimationFrame = onAnimationFrame.bind( this );
  39715. /**
  39716. * The current XR reference space.
  39717. *
  39718. * @private
  39719. * @type {?XRReferenceSpace}
  39720. * @default null
  39721. */
  39722. this._referenceSpace = null;
  39723. /**
  39724. * The current XR reference space type.
  39725. *
  39726. * @private
  39727. * @type {XRReferenceSpaceType}
  39728. * @default 'local-floor'
  39729. */
  39730. this._referenceSpaceType = 'local-floor';
  39731. /**
  39732. * A custom reference space defined by the application.
  39733. *
  39734. * @private
  39735. * @type {?XRReferenceSpace}
  39736. * @default null
  39737. */
  39738. this._customReferenceSpace = null;
  39739. /**
  39740. * The framebuffer scale factor.
  39741. *
  39742. * @private
  39743. * @type {number}
  39744. * @default 1
  39745. */
  39746. this._framebufferScaleFactor = 1;
  39747. /**
  39748. * The foveation factor.
  39749. *
  39750. * @private
  39751. * @type {number}
  39752. * @default 1
  39753. */
  39754. this._foveation = 1.0;
  39755. /**
  39756. * A reference to the current XR session.
  39757. *
  39758. * @private
  39759. * @type {?XRSession}
  39760. * @default null
  39761. */
  39762. this._session = null;
  39763. /**
  39764. * A reference to the current XR base layer.
  39765. *
  39766. * @private
  39767. * @type {?XRWebGLLayer}
  39768. * @default null
  39769. */
  39770. this._glBaseLayer = null;
  39771. /**
  39772. * A reference to the current XR binding.
  39773. *
  39774. * @private
  39775. * @type {?XRWebGLBinding}
  39776. * @default null
  39777. */
  39778. this._glBinding = null;
  39779. /**
  39780. * A reference to the current XR projection layer.
  39781. *
  39782. * @private
  39783. * @type {?XRProjectionLayer}
  39784. * @default null
  39785. */
  39786. this._glProjLayer = null;
  39787. /**
  39788. * A reference to the current XR frame.
  39789. *
  39790. * @private
  39791. * @type {?XRFrame}
  39792. * @default null
  39793. */
  39794. this._xrFrame = null;
  39795. /**
  39796. * Whether the browser supports the APIs necessary to use XRProjectionLayers.
  39797. *
  39798. * Note: this does not represent XRSession explicitly requesting
  39799. * `'layers'` as a feature - see `_sessionUsesLayers` and #30112
  39800. *
  39801. * @private
  39802. * @type {boolean}
  39803. * @readonly
  39804. */
  39805. this._supportsLayers = ( this._supportsGlBinding && 'createProjectionLayer' in XRWebGLBinding.prototype ); // eslint-disable-line compat/compat
  39806. /**
  39807. * Whether the usage of multiview has been requested by the application or not.
  39808. *
  39809. * @private
  39810. * @type {boolean}
  39811. * @default false
  39812. * @readonly
  39813. */
  39814. this._useMultiviewIfPossible = multiview;
  39815. /**
  39816. * Whether the usage of multiview is actually enabled. This flag only evaluates to `true`
  39817. * if multiview has been requested by the application and the `OVR_multiview2` is available.
  39818. *
  39819. * @private
  39820. * @type {boolean}
  39821. * @readonly
  39822. */
  39823. this._useMultiview = false;
  39824. }
  39825. /**
  39826. * Returns an instance of `THREE.Group` that represents the transformation
  39827. * of a XR controller in target ray space. The requested controller is defined
  39828. * by the given index.
  39829. *
  39830. * @param {number} index - The index of the XR controller.
  39831. * @return {Group} A group that represents the controller's transformation.
  39832. */
  39833. getController( index ) {
  39834. const controller = this._getController( index );
  39835. return controller.getTargetRaySpace();
  39836. }
  39837. /**
  39838. * Returns an instance of `THREE.Group` that represents the transformation
  39839. * of a XR controller in grip space. The requested controller is defined
  39840. * by the given index.
  39841. *
  39842. * @param {number} index - The index of the XR controller.
  39843. * @return {Group} A group that represents the controller's transformation.
  39844. */
  39845. getControllerGrip( index ) {
  39846. const controller = this._getController( index );
  39847. return controller.getGripSpace();
  39848. }
  39849. /**
  39850. * Returns an instance of `THREE.Group` that represents the transformation
  39851. * of a XR controller in hand space. The requested controller is defined
  39852. * by the given index.
  39853. *
  39854. * @param {number} index - The index of the XR controller.
  39855. * @return {Group} A group that represents the controller's transformation.
  39856. */
  39857. getHand( index ) {
  39858. const controller = this._getController( index );
  39859. return controller.getHandSpace();
  39860. }
  39861. /**
  39862. * Returns the foveation value.
  39863. *
  39864. * @return {number|undefined} The foveation value. Returns `undefined` if no base or projection layer is defined.
  39865. */
  39866. getFoveation() {
  39867. if ( this._glProjLayer === null && this._glBaseLayer === null ) {
  39868. return undefined;
  39869. }
  39870. return this._foveation;
  39871. }
  39872. /**
  39873. * Sets the foveation value.
  39874. *
  39875. * @param {number} foveation - A number in the range `[0,1]` where `0` means no foveation (full resolution)
  39876. * and `1` means maximum foveation (the edges render at lower resolution).
  39877. */
  39878. setFoveation( foveation ) {
  39879. this._foveation = foveation;
  39880. if ( this._glProjLayer !== null ) {
  39881. this._glProjLayer.fixedFoveation = foveation;
  39882. }
  39883. if ( this._glBaseLayer !== null && this._glBaseLayer.fixedFoveation !== undefined ) {
  39884. this._glBaseLayer.fixedFoveation = foveation;
  39885. }
  39886. }
  39887. /**
  39888. * Returns the framebuffer scale factor.
  39889. *
  39890. * @return {number} The framebuffer scale factor.
  39891. */
  39892. getFramebufferScaleFactor() {
  39893. return this._framebufferScaleFactor;
  39894. }
  39895. /**
  39896. * Sets the framebuffer scale factor.
  39897. *
  39898. * This method can not be used during a XR session.
  39899. *
  39900. * @param {number} factor - The framebuffer scale factor.
  39901. */
  39902. setFramebufferScaleFactor( factor ) {
  39903. this._framebufferScaleFactor = factor;
  39904. if ( this.isPresenting === true ) {
  39905. warn( 'XRManager: Cannot change framebuffer scale while presenting.' );
  39906. }
  39907. }
  39908. /**
  39909. * Returns the reference space type.
  39910. *
  39911. * @return {XRReferenceSpaceType} The reference space type.
  39912. */
  39913. getReferenceSpaceType() {
  39914. return this._referenceSpaceType;
  39915. }
  39916. /**
  39917. * Sets the reference space type.
  39918. *
  39919. * This method can not be used during a XR session.
  39920. *
  39921. * @param {XRReferenceSpaceType} type - The reference space type.
  39922. */
  39923. setReferenceSpaceType( type ) {
  39924. this._referenceSpaceType = type;
  39925. if ( this.isPresenting === true ) {
  39926. warn( 'XRManager: Cannot change reference space type while presenting.' );
  39927. }
  39928. }
  39929. /**
  39930. * Returns the XR reference space.
  39931. *
  39932. * @return {XRReferenceSpace} The XR reference space.
  39933. */
  39934. getReferenceSpace() {
  39935. return this._customReferenceSpace || this._referenceSpace;
  39936. }
  39937. /**
  39938. * Sets a custom XR reference space.
  39939. *
  39940. * @param {XRReferenceSpace} space - The XR reference space.
  39941. */
  39942. setReferenceSpace( space ) {
  39943. this._customReferenceSpace = space;
  39944. }
  39945. /**
  39946. * Returns the XR camera.
  39947. *
  39948. * @return {ArrayCamera} The XR camera.
  39949. */
  39950. getCamera() {
  39951. return this._cameraXR;
  39952. }
  39953. /**
  39954. * Returns the environment blend mode from the current XR session.
  39955. *
  39956. * @return {'opaque'|'additive'|'alpha-blend'|undefined} The environment blend mode. Returns `undefined` when used outside of a XR session.
  39957. */
  39958. getEnvironmentBlendMode() {
  39959. if ( this._session !== null ) {
  39960. return this._session.environmentBlendMode;
  39961. }
  39962. }
  39963. /**
  39964. * Returns the current XR binding.
  39965. *
  39966. * Creates a new binding if needed and the browser is
  39967. * capable of doing so.
  39968. *
  39969. * @return {?XRWebGLBinding} The XR binding. Returns `null` if one cannot be created.
  39970. */
  39971. getBinding() {
  39972. if ( this._glBinding === null && this._supportsGlBinding ) {
  39973. this._glBinding = new XRWebGLBinding( this._session, this._gl );
  39974. }
  39975. return this._glBinding;
  39976. }
  39977. /**
  39978. * Returns the current XR frame.
  39979. *
  39980. * @return {?XRFrame} The XR frame. Returns `null` when used outside a XR session.
  39981. */
  39982. getFrame() {
  39983. return this._xrFrame;
  39984. }
  39985. /**
  39986. * Returns `true` if the engine renders to a multiview target.
  39987. *
  39988. * @return {boolean} Whether the engine renders to a multiview render target or not.
  39989. */
  39990. useMultiview() {
  39991. return this._useMultiview;
  39992. }
  39993. /**
  39994. * This method can be used in XR applications to create a quadratic layer that presents a separate
  39995. * rendered scene.
  39996. *
  39997. * @param {number} width - The width of the layer plane in world units.
  39998. * @param {number} height - The height of the layer plane in world units.
  39999. * @param {Vector3} translation - The position/translation of the layer plane in world units.
  40000. * @param {Quaternion} quaternion - The orientation of the layer plane expressed as a quaternion.
  40001. * @param {number} pixelwidth - The width of the layer's render target in pixels.
  40002. * @param {number} pixelheight - The height of the layer's render target in pixels.
  40003. * @param {Function} rendercall - A callback function that renders the layer. Similar to code in
  40004. * the default animation loop, this method can be used to update/transform 3D object in the layer's scene.
  40005. * @param {Object} [attributes={}] - Allows to configure the layer's render target.
  40006. * @return {Mesh} A mesh representing the quadratic XR layer. This mesh should be added to the XR scene.
  40007. */
  40008. createQuadLayer( width, height, translation, quaternion, pixelwidth, pixelheight, rendercall, attributes = {} ) {
  40009. const geometry = new PlaneGeometry( width, height );
  40010. const renderTarget = new XRRenderTarget(
  40011. pixelwidth,
  40012. pixelheight,
  40013. {
  40014. format: RGBAFormat,
  40015. type: UnsignedByteType,
  40016. depthTexture: new DepthTexture(
  40017. pixelwidth,
  40018. pixelheight,
  40019. attributes.stencil ? UnsignedInt248Type : UnsignedIntType,
  40020. undefined,
  40021. undefined,
  40022. undefined,
  40023. undefined,
  40024. undefined,
  40025. undefined,
  40026. attributes.stencil ? DepthStencilFormat : DepthFormat
  40027. ),
  40028. stencilBuffer: attributes.stencil,
  40029. resolveDepthBuffer: false,
  40030. resolveStencilBuffer: false
  40031. } );
  40032. renderTarget._autoAllocateDepthBuffer = true;
  40033. const material = new MeshBasicMaterial( { color: 0xffffff, side: FrontSide } );
  40034. material.map = renderTarget.texture;
  40035. material.map.offset.y = 1;
  40036. material.map.repeat.y = -1;
  40037. const plane = new Mesh( geometry, material );
  40038. plane.position.copy( translation );
  40039. plane.quaternion.copy( quaternion );
  40040. const layer = {
  40041. type: 'quad',
  40042. width: width,
  40043. height: height,
  40044. translation: translation,
  40045. quaternion: quaternion,
  40046. pixelwidth: pixelwidth,
  40047. pixelheight: pixelheight,
  40048. plane: plane,
  40049. material: material,
  40050. rendercall: rendercall,
  40051. renderTarget: renderTarget };
  40052. this._layers.push( layer );
  40053. if ( this._session !== null ) {
  40054. layer.plane.material = new MeshBasicMaterial( { color: 0xffffff, side: FrontSide } );
  40055. layer.plane.material.blending = CustomBlending;
  40056. layer.plane.material.blendEquation = AddEquation;
  40057. layer.plane.material.blendSrc = ZeroFactor;
  40058. layer.plane.material.blendDst = ZeroFactor;
  40059. layer.xrlayer = this._createXRLayer( layer );
  40060. const xrlayers = this._session.renderState.layers;
  40061. xrlayers.unshift( layer.xrlayer );
  40062. this._session.updateRenderState( { layers: xrlayers } );
  40063. } else {
  40064. renderTarget.isXRRenderTarget = false;
  40065. }
  40066. return plane;
  40067. }
  40068. /**
  40069. * This method can be used in XR applications to create a cylindrical layer that presents a separate
  40070. * rendered scene.
  40071. *
  40072. * @param {number} radius - The radius of the cylinder in world units.
  40073. * @param {number} centralAngle - The central angle of the cylinder in radians.
  40074. * @param {number} aspectratio - The aspect ratio.
  40075. * @param {Vector3} translation - The position/translation of the layer plane in world units.
  40076. * @param {Quaternion} quaternion - The orientation of the layer plane expressed as a quaternion.
  40077. * @param {number} pixelwidth - The width of the layer's render target in pixels.
  40078. * @param {number} pixelheight - The height of the layer's render target in pixels.
  40079. * @param {Function} rendercall - A callback function that renders the layer. Similar to code in
  40080. * the default animation loop, this method can be used to update/transform 3D object in the layer's scene.
  40081. * @param {Object} [attributes={}] - Allows to configure the layer's render target.
  40082. * @return {Mesh} A mesh representing the cylindrical XR layer. This mesh should be added to the XR scene.
  40083. */
  40084. createCylinderLayer( radius, centralAngle, aspectratio, translation, quaternion, pixelwidth, pixelheight, rendercall, attributes = {} ) {
  40085. const geometry = new CylinderGeometry( radius, radius, radius * centralAngle / aspectratio, 64, 64, true, Math.PI - centralAngle / 2, centralAngle );
  40086. const renderTarget = new XRRenderTarget(
  40087. pixelwidth,
  40088. pixelheight,
  40089. {
  40090. format: RGBAFormat,
  40091. type: UnsignedByteType,
  40092. depthTexture: new DepthTexture(
  40093. pixelwidth,
  40094. pixelheight,
  40095. attributes.stencil ? UnsignedInt248Type : UnsignedIntType,
  40096. undefined,
  40097. undefined,
  40098. undefined,
  40099. undefined,
  40100. undefined,
  40101. undefined,
  40102. attributes.stencil ? DepthStencilFormat : DepthFormat
  40103. ),
  40104. stencilBuffer: attributes.stencil,
  40105. resolveDepthBuffer: false,
  40106. resolveStencilBuffer: false
  40107. } );
  40108. renderTarget._autoAllocateDepthBuffer = true;
  40109. const material = new MeshBasicMaterial( { color: 0xffffff, side: BackSide } );
  40110. material.map = renderTarget.texture;
  40111. material.map.offset.y = 1;
  40112. material.map.repeat.y = -1;
  40113. const plane = new Mesh( geometry, material );
  40114. plane.position.copy( translation );
  40115. plane.quaternion.copy( quaternion );
  40116. const layer = {
  40117. type: 'cylinder',
  40118. radius: radius,
  40119. centralAngle: centralAngle,
  40120. aspectratio: aspectratio,
  40121. translation: translation,
  40122. quaternion: quaternion,
  40123. pixelwidth: pixelwidth,
  40124. pixelheight: pixelheight,
  40125. plane: plane,
  40126. material: material,
  40127. rendercall: rendercall,
  40128. renderTarget: renderTarget };
  40129. this._layers.push( layer );
  40130. if ( this._session !== null ) {
  40131. layer.plane.material = new MeshBasicMaterial( { color: 0xffffff, side: BackSide } );
  40132. layer.plane.material.blending = CustomBlending;
  40133. layer.plane.material.blendEquation = AddEquation;
  40134. layer.plane.material.blendSrc = ZeroFactor;
  40135. layer.plane.material.blendDst = ZeroFactor;
  40136. layer.xrlayer = this._createXRLayer( layer );
  40137. const xrlayers = this._session.renderState.layers;
  40138. xrlayers.unshift( layer.xrlayer );
  40139. this._session.updateRenderState( { layers: xrlayers } );
  40140. } else {
  40141. renderTarget.isXRRenderTarget = false;
  40142. }
  40143. return plane;
  40144. }
  40145. /**
  40146. * Renders the XR layers that have been previously added to the scene.
  40147. *
  40148. * This method is usually called in your animation loop before rendering
  40149. * the actual scene via `renderer.render( scene, camera );`.
  40150. */
  40151. renderLayers( ) {
  40152. const translationObject = new Vector3();
  40153. const quaternionObject = new Quaternion();
  40154. const renderer = this._renderer;
  40155. const wasPresenting = this.isPresenting;
  40156. const rendererOutputTarget = renderer.getOutputRenderTarget();
  40157. const rendererFramebufferTarget = renderer._frameBufferTarget;
  40158. this.isPresenting = false;
  40159. const rendererSize = new Vector2();
  40160. renderer.getSize( rendererSize );
  40161. const rendererQuad = renderer._quad;
  40162. for ( const layer of this._layers ) {
  40163. layer.renderTarget.isXRRenderTarget = this._session !== null;
  40164. layer.renderTarget._hasExternalTextures = layer.renderTarget.isXRRenderTarget;
  40165. if ( layer.renderTarget.isXRRenderTarget && this._sessionUsesLayers ) {
  40166. layer.xrlayer.transform = new XRRigidTransform( layer.plane.getWorldPosition( translationObject ), layer.plane.getWorldQuaternion( quaternionObject ) );
  40167. const glSubImage = this._glBinding.getSubImage( layer.xrlayer, this._xrFrame );
  40168. renderer.backend.setXRRenderTargetTextures(
  40169. layer.renderTarget,
  40170. glSubImage.colorTexture,
  40171. undefined );
  40172. renderer._setXRLayerSize( layer.renderTarget.width, layer.renderTarget.height );
  40173. renderer.setOutputRenderTarget( layer.renderTarget );
  40174. renderer.setRenderTarget( null );
  40175. renderer._frameBufferTarget = null;
  40176. this._frameBufferTargets || ( this._frameBufferTargets = new WeakMap() );
  40177. const { frameBufferTarget, quad } = this._frameBufferTargets.get( layer.renderTarget ) || { frameBufferTarget: null, quad: null };
  40178. if ( ! frameBufferTarget ) {
  40179. renderer._quad = new QuadMesh( new NodeMaterial() );
  40180. this._frameBufferTargets.set( layer.renderTarget, { frameBufferTarget: renderer._getFrameBufferTarget(), quad: renderer._quad } );
  40181. } else {
  40182. renderer._frameBufferTarget = frameBufferTarget;
  40183. renderer._quad = quad;
  40184. }
  40185. layer.rendercall();
  40186. renderer._frameBufferTarget = null;
  40187. } else {
  40188. renderer.setRenderTarget( layer.renderTarget );
  40189. layer.rendercall();
  40190. }
  40191. }
  40192. renderer.setRenderTarget( null );
  40193. renderer.setOutputRenderTarget( rendererOutputTarget );
  40194. renderer._frameBufferTarget = rendererFramebufferTarget;
  40195. renderer._setXRLayerSize( rendererSize.x, rendererSize.y );
  40196. renderer._quad = rendererQuad;
  40197. this.isPresenting = wasPresenting;
  40198. }
  40199. /**
  40200. * Returns the current XR session.
  40201. *
  40202. * @return {?XRSession} The XR session. Returns `null` when used outside a XR session.
  40203. */
  40204. getSession() {
  40205. return this._session;
  40206. }
  40207. /**
  40208. * After a XR session has been requested usually with one of the `*Button` modules, it
  40209. * is injected into the renderer with this method. This method triggers the start of
  40210. * the actual XR rendering.
  40211. *
  40212. * @async
  40213. * @param {XRSession} session - The XR session to set.
  40214. * @return {Promise} A Promise that resolves when the session has been set.
  40215. */
  40216. async setSession( session ) {
  40217. const renderer = this._renderer;
  40218. const backend = renderer.backend;
  40219. this._gl = renderer.getContext();
  40220. const gl = this._gl;
  40221. const attributes = gl.getContextAttributes();
  40222. this._session = session;
  40223. if ( session !== null ) {
  40224. 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.' );
  40225. session.addEventListener( 'select', this._onSessionEvent );
  40226. session.addEventListener( 'selectstart', this._onSessionEvent );
  40227. session.addEventListener( 'selectend', this._onSessionEvent );
  40228. session.addEventListener( 'squeeze', this._onSessionEvent );
  40229. session.addEventListener( 'squeezestart', this._onSessionEvent );
  40230. session.addEventListener( 'squeezeend', this._onSessionEvent );
  40231. session.addEventListener( 'end', this._onSessionEnd );
  40232. session.addEventListener( 'inputsourceschange', this._onInputSourcesChange );
  40233. await backend.makeXRCompatible();
  40234. this._currentPixelRatio = renderer.getPixelRatio();
  40235. renderer.getSize( this._currentSize );
  40236. this._currentAnimationContext = renderer._animation.getContext();
  40237. this._currentAnimationLoop = renderer._animation.getAnimationLoop();
  40238. renderer._animation.stop();
  40239. //
  40240. if ( this._supportsLayers === true ) {
  40241. // default path using XRProjectionLayer
  40242. let depthFormat = null;
  40243. let depthType = null;
  40244. let glDepthFormat = null;
  40245. if ( renderer.depth ) {
  40246. glDepthFormat = renderer.stencil ? gl.DEPTH24_STENCIL8 : gl.DEPTH_COMPONENT24;
  40247. depthFormat = renderer.stencil ? DepthStencilFormat : DepthFormat;
  40248. depthType = renderer.stencil ? UnsignedInt248Type : UnsignedIntType;
  40249. }
  40250. const projectionlayerInit = {
  40251. colorFormat: gl.RGBA8,
  40252. depthFormat: glDepthFormat,
  40253. scaleFactor: this._framebufferScaleFactor,
  40254. clearOnAccess: false
  40255. };
  40256. if ( this._useMultiviewIfPossible && renderer.hasFeature( 'OVR_multiview2' ) ) {
  40257. projectionlayerInit.textureType = 'texture-array';
  40258. this._useMultiview = true;
  40259. }
  40260. this._glBinding = this.getBinding();
  40261. const glProjLayer = this._glBinding.createProjectionLayer( projectionlayerInit );
  40262. const layersArray = [ glProjLayer ];
  40263. this._glProjLayer = glProjLayer;
  40264. renderer.setPixelRatio( 1 );
  40265. renderer._setXRLayerSize( glProjLayer.textureWidth, glProjLayer.textureHeight );
  40266. const depth = this._useMultiview ? 2 : 1;
  40267. const depthTexture = new DepthTexture( glProjLayer.textureWidth, glProjLayer.textureHeight, depthType, undefined, undefined, undefined, undefined, undefined, undefined, depthFormat, depth );
  40268. this._xrRenderTarget = new XRRenderTarget(
  40269. glProjLayer.textureWidth,
  40270. glProjLayer.textureHeight,
  40271. {
  40272. format: RGBAFormat,
  40273. type: UnsignedByteType,
  40274. colorSpace: renderer.outputColorSpace,
  40275. depthTexture: depthTexture,
  40276. stencilBuffer: renderer.stencil,
  40277. samples: attributes.antialias ? 4 : 0,
  40278. resolveDepthBuffer: ( glProjLayer.ignoreDepthValues === false ),
  40279. resolveStencilBuffer: ( glProjLayer.ignoreDepthValues === false ),
  40280. depth: this._useMultiview ? 2 : 1,
  40281. multiview: this._useMultiview
  40282. } );
  40283. this._xrRenderTarget._hasExternalTextures = true;
  40284. this._xrRenderTarget.depth = this._useMultiview ? 2 : 1;
  40285. this._sessionUsesLayers = session.enabledFeatures.includes( 'layers' );
  40286. this._referenceSpace = await session.requestReferenceSpace( this.getReferenceSpaceType() );
  40287. if ( this._sessionUsesLayers ) {
  40288. // switch layers to native
  40289. for ( const layer of this._layers ) {
  40290. // change material so it "punches" out a hole to show the XR Layer.
  40291. layer.plane.material = new MeshBasicMaterial( { color: 0xffffff, side: layer.type === 'cylinder' ? BackSide : FrontSide } );
  40292. layer.plane.material.blending = CustomBlending;
  40293. layer.plane.material.blendEquation = AddEquation;
  40294. layer.plane.material.blendSrc = ZeroFactor;
  40295. layer.plane.material.blendDst = ZeroFactor;
  40296. layer.xrlayer = this._createXRLayer( layer );
  40297. layersArray.unshift( layer.xrlayer );
  40298. }
  40299. }
  40300. session.updateRenderState( { layers: layersArray } );
  40301. } else {
  40302. // fallback to XRWebGLLayer
  40303. const layerInit = {
  40304. antialias: renderer.currentSamples > 0,
  40305. alpha: true,
  40306. depth: renderer.depth,
  40307. stencil: renderer.stencil,
  40308. framebufferScaleFactor: this.getFramebufferScaleFactor()
  40309. };
  40310. const glBaseLayer = new XRWebGLLayer( session, gl, layerInit );
  40311. this._glBaseLayer = glBaseLayer;
  40312. session.updateRenderState( { baseLayer: glBaseLayer } );
  40313. renderer.setPixelRatio( 1 );
  40314. renderer._setXRLayerSize( glBaseLayer.framebufferWidth, glBaseLayer.framebufferHeight );
  40315. this._xrRenderTarget = new XRRenderTarget(
  40316. glBaseLayer.framebufferWidth,
  40317. glBaseLayer.framebufferHeight,
  40318. {
  40319. format: RGBAFormat,
  40320. type: UnsignedByteType,
  40321. colorSpace: renderer.outputColorSpace,
  40322. stencilBuffer: renderer.stencil,
  40323. resolveDepthBuffer: ( glBaseLayer.ignoreDepthValues === false ),
  40324. resolveStencilBuffer: ( glBaseLayer.ignoreDepthValues === false ),
  40325. }
  40326. );
  40327. this._xrRenderTarget._isOpaqueFramebuffer = true;
  40328. this._referenceSpace = await session.requestReferenceSpace( this.getReferenceSpaceType() );
  40329. }
  40330. //
  40331. this.setFoveation( this.getFoveation() );
  40332. renderer._animation.setAnimationLoop( this._onAnimationFrame );
  40333. renderer._animation.setContext( session );
  40334. renderer._animation.start();
  40335. this.isPresenting = true;
  40336. this.dispatchEvent( { type: 'sessionstart' } );
  40337. }
  40338. }
  40339. /**
  40340. * This method is called by the renderer per frame and updates the XR camera
  40341. * and it sub cameras based on the given camera. The given camera is the "user"
  40342. * camera created on application level and used for non-XR rendering.
  40343. *
  40344. * @param {PerspectiveCamera} camera - The camera.
  40345. */
  40346. updateCamera( camera ) {
  40347. const session = this._session;
  40348. if ( session === null ) return;
  40349. const depthNear = camera.near;
  40350. const depthFar = camera.far;
  40351. const cameraXR = this._cameraXR;
  40352. const cameraL = this._cameraL;
  40353. const cameraR = this._cameraR;
  40354. cameraXR.near = cameraR.near = cameraL.near = depthNear;
  40355. cameraXR.far = cameraR.far = cameraL.far = depthFar;
  40356. cameraXR.isMultiViewCamera = this._useMultiview;
  40357. if ( this._currentDepthNear !== cameraXR.near || this._currentDepthFar !== cameraXR.far ) {
  40358. // Note that the new renderState won't apply until the next frame. See #18320
  40359. session.updateRenderState( {
  40360. depthNear: cameraXR.near,
  40361. depthFar: cameraXR.far
  40362. } );
  40363. this._currentDepthNear = cameraXR.near;
  40364. this._currentDepthFar = cameraXR.far;
  40365. }
  40366. // inherit camera layers and enable eye layers (1 = left, 2 = right)
  40367. cameraXR.layers.mask = camera.layers.mask | 0b110;
  40368. cameraL.layers.mask = cameraXR.layers.mask & 0b011;
  40369. cameraR.layers.mask = cameraXR.layers.mask & 0b101;
  40370. const parent = camera.parent;
  40371. const cameras = cameraXR.cameras;
  40372. updateCamera( cameraXR, parent );
  40373. for ( let i = 0; i < cameras.length; i ++ ) {
  40374. updateCamera( cameras[ i ], parent );
  40375. }
  40376. // update projection matrix for proper view frustum culling
  40377. if ( cameras.length === 2 ) {
  40378. setProjectionFromUnion( cameraXR, cameraL, cameraR );
  40379. } else {
  40380. // assume single camera setup (AR)
  40381. cameraXR.projectionMatrix.copy( cameraL.projectionMatrix );
  40382. }
  40383. // update user camera and its children
  40384. updateUserCamera( camera, cameraXR, parent );
  40385. }
  40386. /**
  40387. * Returns a WebXR controller for the given controller index.
  40388. *
  40389. * @private
  40390. * @param {number} index - The controller index.
  40391. * @return {WebXRController} The XR controller.
  40392. */
  40393. _getController( index ) {
  40394. let controller = this._controllers[ index ];
  40395. if ( controller === undefined ) {
  40396. controller = new WebXRController();
  40397. this._controllers[ index ] = controller;
  40398. }
  40399. return controller;
  40400. }
  40401. }
  40402. /**
  40403. * Assumes 2 cameras that are parallel and share an X-axis, and that
  40404. * the cameras' projection and world matrices have already been set.
  40405. * And that near and far planes are identical for both cameras.
  40406. * Visualization of this technique: https://computergraphics.stackexchange.com/a/4765
  40407. *
  40408. * @param {ArrayCamera} camera - The camera to update.
  40409. * @param {PerspectiveCamera} cameraL - The left camera.
  40410. * @param {PerspectiveCamera} cameraR - The right camera.
  40411. */
  40412. function setProjectionFromUnion( camera, cameraL, cameraR ) {
  40413. _cameraLPos.setFromMatrixPosition( cameraL.matrixWorld );
  40414. _cameraRPos.setFromMatrixPosition( cameraR.matrixWorld );
  40415. const ipd = _cameraLPos.distanceTo( _cameraRPos );
  40416. const projL = cameraL.projectionMatrix.elements;
  40417. const projR = cameraR.projectionMatrix.elements;
  40418. // VR systems will have identical far and near planes, and
  40419. // most likely identical top and bottom frustum extents.
  40420. // Use the left camera for these values.
  40421. const near = projL[ 14 ] / ( projL[ 10 ] - 1 );
  40422. const far = projL[ 14 ] / ( projL[ 10 ] + 1 );
  40423. const topFov = ( projL[ 9 ] + 1 ) / projL[ 5 ];
  40424. const bottomFov = ( projL[ 9 ] - 1 ) / projL[ 5 ];
  40425. const leftFov = ( projL[ 8 ] - 1 ) / projL[ 0 ];
  40426. const rightFov = ( projR[ 8 ] + 1 ) / projR[ 0 ];
  40427. const left = near * leftFov;
  40428. const right = near * rightFov;
  40429. // Calculate the new camera's position offset from the
  40430. // left camera. xOffset should be roughly half `ipd`.
  40431. const zOffset = ipd / ( - leftFov + rightFov );
  40432. const xOffset = zOffset * - leftFov;
  40433. // TODO: Better way to apply this offset?
  40434. cameraL.matrixWorld.decompose( camera.position, camera.quaternion, camera.scale );
  40435. camera.translateX( xOffset );
  40436. camera.translateZ( zOffset );
  40437. camera.matrixWorld.compose( camera.position, camera.quaternion, camera.scale );
  40438. camera.matrixWorldInverse.copy( camera.matrixWorld ).invert();
  40439. // Check if the projection uses an infinite far plane.
  40440. if ( projL[ 10 ] === -1 ) {
  40441. // Use the projection matrix from the left eye.
  40442. // The camera offset is sufficient to include the view volumes
  40443. // of both eyes (assuming symmetric projections).
  40444. camera.projectionMatrix.copy( cameraL.projectionMatrix );
  40445. camera.projectionMatrixInverse.copy( cameraL.projectionMatrixInverse );
  40446. } else {
  40447. // Find the union of the frustum values of the cameras and scale
  40448. // the values so that the near plane's position does not change in world space,
  40449. // although must now be relative to the new union camera.
  40450. const near2 = near + zOffset;
  40451. const far2 = far + zOffset;
  40452. const left2 = left - xOffset;
  40453. const right2 = right + ( ipd - xOffset );
  40454. const top2 = topFov * far / far2 * near2;
  40455. const bottom2 = bottomFov * far / far2 * near2;
  40456. camera.projectionMatrix.makePerspective( left2, right2, top2, bottom2, near2, far2 );
  40457. camera.projectionMatrixInverse.copy( camera.projectionMatrix ).invert();
  40458. }
  40459. }
  40460. /**
  40461. * Updates the world matrices for the given camera based on the parent 3D object.
  40462. *
  40463. * @inner
  40464. * @param {Camera} camera - The camera to update.
  40465. * @param {Object3D} parent - The parent 3D object.
  40466. */
  40467. function updateCamera( camera, parent ) {
  40468. if ( parent === null ) {
  40469. camera.matrixWorld.copy( camera.matrix );
  40470. } else {
  40471. camera.matrixWorld.multiplyMatrices( parent.matrixWorld, camera.matrix );
  40472. }
  40473. camera.matrixWorldInverse.copy( camera.matrixWorld ).invert();
  40474. }
  40475. /**
  40476. * Updates the given camera with the transformation of the XR camera and parent object.
  40477. *
  40478. * @inner
  40479. * @param {Camera} camera - The camera to update.
  40480. * @param {ArrayCamera} cameraXR - The XR camera.
  40481. * @param {Object3D} parent - The parent 3D object.
  40482. */
  40483. function updateUserCamera( camera, cameraXR, parent ) {
  40484. if ( parent === null ) {
  40485. camera.matrix.copy( cameraXR.matrixWorld );
  40486. } else {
  40487. camera.matrix.copy( parent.matrixWorld );
  40488. camera.matrix.invert();
  40489. camera.matrix.multiply( cameraXR.matrixWorld );
  40490. }
  40491. camera.matrix.decompose( camera.position, camera.quaternion, camera.scale );
  40492. camera.updateMatrixWorld( true );
  40493. camera.projectionMatrix.copy( cameraXR.projectionMatrix );
  40494. camera.projectionMatrixInverse.copy( cameraXR.projectionMatrixInverse );
  40495. if ( camera.isPerspectiveCamera ) {
  40496. camera.fov = RAD2DEG * 2 * Math.atan( 1 / camera.projectionMatrix.elements[ 5 ] );
  40497. camera.zoom = 1;
  40498. }
  40499. }
  40500. function onSessionEvent( event ) {
  40501. const controllerIndex = this._controllerInputSources.indexOf( event.inputSource );
  40502. if ( controllerIndex === -1 ) {
  40503. return;
  40504. }
  40505. const controller = this._controllers[ controllerIndex ];
  40506. if ( controller !== undefined ) {
  40507. const referenceSpace = this.getReferenceSpace();
  40508. controller.update( event.inputSource, event.frame, referenceSpace );
  40509. controller.dispatchEvent( { type: event.type, data: event.inputSource } );
  40510. }
  40511. }
  40512. function onSessionEnd() {
  40513. const session = this._session;
  40514. const renderer = this._renderer;
  40515. session.removeEventListener( 'select', this._onSessionEvent );
  40516. session.removeEventListener( 'selectstart', this._onSessionEvent );
  40517. session.removeEventListener( 'selectend', this._onSessionEvent );
  40518. session.removeEventListener( 'squeeze', this._onSessionEvent );
  40519. session.removeEventListener( 'squeezestart', this._onSessionEvent );
  40520. session.removeEventListener( 'squeezeend', this._onSessionEvent );
  40521. session.removeEventListener( 'end', this._onSessionEnd );
  40522. session.removeEventListener( 'inputsourceschange', this._onInputSourcesChange );
  40523. for ( let i = 0; i < this._controllers.length; i ++ ) {
  40524. const inputSource = this._controllerInputSources[ i ];
  40525. if ( inputSource === null ) continue;
  40526. this._controllerInputSources[ i ] = null;
  40527. this._controllers[ i ].disconnect( inputSource );
  40528. }
  40529. this._currentDepthNear = null;
  40530. this._currentDepthFar = null;
  40531. // restore framebuffer/rendering state
  40532. renderer._resetXRState();
  40533. this._session = null;
  40534. this._xrRenderTarget = null;
  40535. this._glBinding = null;
  40536. this._glBaseLayer = null;
  40537. this._glProjLayer = null;
  40538. // switch layers back to emulated
  40539. if ( this._sessionUsesLayers === true ) {
  40540. for ( const layer of this._layers ) {
  40541. // Recreate layer render target to reset state
  40542. layer.renderTarget = new XRRenderTarget(
  40543. layer.pixelwidth,
  40544. layer.pixelheight,
  40545. {
  40546. format: RGBAFormat,
  40547. type: UnsignedByteType,
  40548. depthTexture: new DepthTexture(
  40549. layer.pixelwidth,
  40550. layer.pixelheight,
  40551. layer.stencilBuffer ? UnsignedInt248Type : UnsignedIntType,
  40552. undefined,
  40553. undefined,
  40554. undefined,
  40555. undefined,
  40556. undefined,
  40557. undefined,
  40558. layer.stencilBuffer ? DepthStencilFormat : DepthFormat
  40559. ),
  40560. stencilBuffer: layer.stencilBuffer,
  40561. resolveDepthBuffer: false,
  40562. resolveStencilBuffer: false
  40563. } );
  40564. layer.renderTarget.isXRRenderTarget = false;
  40565. layer.plane.material = layer.material;
  40566. layer.material.map = layer.renderTarget.texture;
  40567. layer.material.map.offset.y = 1;
  40568. layer.material.map.repeat.y = -1;
  40569. delete layer.xrlayer;
  40570. }
  40571. }
  40572. //
  40573. this.isPresenting = false;
  40574. this._useMultiview = false;
  40575. renderer._animation.stop();
  40576. renderer._animation.setAnimationLoop( this._currentAnimationLoop );
  40577. renderer._animation.setContext( this._currentAnimationContext );
  40578. renderer._animation.start();
  40579. renderer.setPixelRatio( this._currentPixelRatio );
  40580. renderer.setSize( this._currentSize.width, this._currentSize.height, false );
  40581. this.dispatchEvent( { type: 'sessionend' } );
  40582. }
  40583. function onInputSourcesChange( event ) {
  40584. const controllers = this._controllers;
  40585. const controllerInputSources = this._controllerInputSources;
  40586. // Notify disconnected
  40587. for ( let i = 0; i < event.removed.length; i ++ ) {
  40588. const inputSource = event.removed[ i ];
  40589. const index = controllerInputSources.indexOf( inputSource );
  40590. if ( index >= 0 ) {
  40591. controllerInputSources[ index ] = null;
  40592. controllers[ index ].disconnect( inputSource );
  40593. }
  40594. }
  40595. // Notify connected
  40596. for ( let i = 0; i < event.added.length; i ++ ) {
  40597. const inputSource = event.added[ i ];
  40598. let controllerIndex = controllerInputSources.indexOf( inputSource );
  40599. if ( controllerIndex === -1 ) {
  40600. // Assign input source a controller that currently has no input source
  40601. for ( let i = 0; i < controllers.length; i ++ ) {
  40602. if ( i >= controllerInputSources.length ) {
  40603. controllerInputSources.push( inputSource );
  40604. controllerIndex = i;
  40605. break;
  40606. } else if ( controllerInputSources[ i ] === null ) {
  40607. controllerInputSources[ i ] = inputSource;
  40608. controllerIndex = i;
  40609. break;
  40610. }
  40611. }
  40612. // If all controllers do currently receive input we ignore new ones
  40613. if ( controllerIndex === -1 ) break;
  40614. }
  40615. const controller = controllers[ controllerIndex ];
  40616. if ( controller ) {
  40617. controller.connect( inputSource );
  40618. }
  40619. }
  40620. }
  40621. // Creation method for native WebXR layers
  40622. function createXRLayer( layer ) {
  40623. if ( layer.type === 'quad' ) {
  40624. return this._glBinding.createQuadLayer( {
  40625. transform: new XRRigidTransform( layer.translation, layer.quaternion ),
  40626. width: layer.width / 2,
  40627. height: layer.height / 2,
  40628. space: this._referenceSpace,
  40629. viewPixelWidth: layer.pixelwidth,
  40630. viewPixelHeight: layer.pixelheight,
  40631. clearOnAccess: false
  40632. } );
  40633. } else {
  40634. return this._glBinding.createCylinderLayer( {
  40635. transform: new XRRigidTransform( layer.translation, layer.quaternion ),
  40636. radius: layer.radius,
  40637. centralAngle: layer.centralAngle,
  40638. aspectRatio: layer.aspectRatio,
  40639. space: this._referenceSpace,
  40640. viewPixelWidth: layer.pixelwidth,
  40641. viewPixelHeight: layer.pixelheight,
  40642. clearOnAccess: false
  40643. } );
  40644. }
  40645. }
  40646. // Animation Loop
  40647. function onAnimationFrame( time, frame ) {
  40648. if ( frame === undefined ) return;
  40649. const cameraXR = this._cameraXR;
  40650. const renderer = this._renderer;
  40651. const backend = renderer.backend;
  40652. const glBaseLayer = this._glBaseLayer;
  40653. const referenceSpace = this.getReferenceSpace();
  40654. const pose = frame.getViewerPose( referenceSpace );
  40655. this._xrFrame = frame;
  40656. if ( pose !== null ) {
  40657. const views = pose.views;
  40658. if ( this._glBaseLayer !== null ) {
  40659. backend.setXRTarget( glBaseLayer.framebuffer );
  40660. }
  40661. let cameraXRNeedsUpdate = false;
  40662. // check if it's necessary to rebuild cameraXR's camera list
  40663. if ( views.length !== cameraXR.cameras.length ) {
  40664. cameraXR.cameras.length = 0;
  40665. cameraXRNeedsUpdate = true;
  40666. }
  40667. for ( let i = 0; i < views.length; i ++ ) {
  40668. const view = views[ i ];
  40669. let viewport;
  40670. if ( this._supportsLayers === true ) {
  40671. const glSubImage = this._glBinding.getViewSubImage( this._glProjLayer, view );
  40672. viewport = glSubImage.viewport;
  40673. // For side-by-side projection, we only produce a single texture for both eyes.
  40674. if ( i === 0 ) {
  40675. backend.setXRRenderTargetTextures(
  40676. this._xrRenderTarget,
  40677. glSubImage.colorTexture,
  40678. ( this._glProjLayer.ignoreDepthValues && ! this._useMultiview ) ? undefined : glSubImage.depthStencilTexture
  40679. );
  40680. }
  40681. } else {
  40682. viewport = glBaseLayer.getViewport( view );
  40683. }
  40684. let camera = this._cameras[ i ];
  40685. if ( camera === undefined ) {
  40686. camera = new PerspectiveCamera();
  40687. camera.layers.enable( i );
  40688. camera.viewport = new Vector4();
  40689. this._cameras[ i ] = camera;
  40690. }
  40691. camera.matrix.fromArray( view.transform.matrix );
  40692. camera.matrix.decompose( camera.position, camera.quaternion, camera.scale );
  40693. camera.projectionMatrix.fromArray( view.projectionMatrix );
  40694. camera.projectionMatrixInverse.copy( camera.projectionMatrix ).invert();
  40695. camera.viewport.set( viewport.x, viewport.y, viewport.width, viewport.height );
  40696. if ( i === 0 ) {
  40697. cameraXR.matrix.copy( camera.matrix );
  40698. cameraXR.matrix.decompose( cameraXR.position, cameraXR.quaternion, cameraXR.scale );
  40699. }
  40700. if ( cameraXRNeedsUpdate === true ) {
  40701. cameraXR.cameras.push( camera );
  40702. }
  40703. }
  40704. renderer.setOutputRenderTarget( this._xrRenderTarget );
  40705. }
  40706. //
  40707. for ( let i = 0; i < this._controllers.length; i ++ ) {
  40708. const inputSource = this._controllerInputSources[ i ];
  40709. const controller = this._controllers[ i ];
  40710. if ( inputSource !== null && controller !== undefined ) {
  40711. controller.update( inputSource, frame, referenceSpace );
  40712. }
  40713. }
  40714. if ( this._currentAnimationLoop ) this._currentAnimationLoop( time, frame );
  40715. if ( frame.detectedPlanes ) {
  40716. this.dispatchEvent( { type: 'planesdetected', data: frame } );
  40717. }
  40718. this._xrFrame = null;
  40719. }
  40720. /**
  40721. * CanvasTarget is a class that represents the final output destination of the renderer.
  40722. *
  40723. * @augments EventDispatcher
  40724. */
  40725. class CanvasTarget extends EventDispatcher {
  40726. /**
  40727. * Constructs a new CanvasTarget.
  40728. *
  40729. * @param {HTMLCanvasElement|OffscreenCanvas} domElement - The canvas element to render to.
  40730. */
  40731. constructor( domElement ) {
  40732. super();
  40733. /**
  40734. * A reference to the canvas element the renderer is drawing to.
  40735. * This value of this property will automatically be created by
  40736. * the renderer.
  40737. *
  40738. * @type {HTMLCanvasElement|OffscreenCanvas}
  40739. */
  40740. this.domElement = domElement;
  40741. /**
  40742. * The renderer's pixel ratio.
  40743. *
  40744. * @private
  40745. * @type {number}
  40746. * @default 1
  40747. */
  40748. this._pixelRatio = 1;
  40749. /**
  40750. * The width of the renderer's default framebuffer in logical pixel unit.
  40751. *
  40752. * @private
  40753. * @type {number}
  40754. */
  40755. this._width = this.domElement.width;
  40756. /**
  40757. * The height of the renderer's default framebuffer in logical pixel unit.
  40758. *
  40759. * @private
  40760. * @type {number}
  40761. */
  40762. this._height = this.domElement.height;
  40763. /**
  40764. * The viewport of the renderer in logical pixel unit.
  40765. *
  40766. * @private
  40767. * @type {Vector4}
  40768. */
  40769. this._viewport = new Vector4( 0, 0, this._width, this._height );
  40770. /**
  40771. * The scissor rectangle of the renderer in logical pixel unit.
  40772. *
  40773. * @private
  40774. * @type {Vector4}
  40775. */
  40776. this._scissor = new Vector4( 0, 0, this._width, this._height );
  40777. /**
  40778. * Whether the scissor test should be enabled or not.
  40779. *
  40780. * @private
  40781. * @type {boolean}
  40782. */
  40783. this._scissorTest = false;
  40784. /**
  40785. * The color texture of the default framebuffer.
  40786. *
  40787. * @type {FramebufferTexture}
  40788. */
  40789. this.colorTexture = new FramebufferTexture();
  40790. /**
  40791. * The depth texture of the default framebuffer.
  40792. *
  40793. * @type {DepthTexture}
  40794. */
  40795. this.depthTexture = new DepthTexture();
  40796. }
  40797. /**
  40798. * Returns the pixel ratio.
  40799. *
  40800. * @return {number} The pixel ratio.
  40801. */
  40802. getPixelRatio() {
  40803. return this._pixelRatio;
  40804. }
  40805. /**
  40806. * Returns the drawing buffer size in physical pixels. This method honors the pixel ratio.
  40807. *
  40808. * @param {Vector2} target - The method writes the result in this target object.
  40809. * @return {Vector2} The drawing buffer size.
  40810. */
  40811. getDrawingBufferSize( target ) {
  40812. return target.set( this._width * this._pixelRatio, this._height * this._pixelRatio ).floor();
  40813. }
  40814. /**
  40815. * Returns the renderer's size in logical pixels. This method does not honor the pixel ratio.
  40816. *
  40817. * @param {Vector2} target - The method writes the result in this target object.
  40818. * @return {Vector2} The renderer's size in logical pixels.
  40819. */
  40820. getSize( target ) {
  40821. return target.set( this._width, this._height );
  40822. }
  40823. /**
  40824. * Sets the given pixel ratio and resizes the canvas if necessary.
  40825. *
  40826. * @param {number} [value=1] - The pixel ratio.
  40827. */
  40828. setPixelRatio( value = 1 ) {
  40829. if ( this._pixelRatio === value ) return;
  40830. this._pixelRatio = value;
  40831. this.setSize( this._width, this._height, false );
  40832. }
  40833. /**
  40834. * This method allows to define the drawing buffer size by specifying
  40835. * width, height and pixel ratio all at once. The size of the drawing
  40836. * buffer is computed with this formula:
  40837. * ```js
  40838. * size.x = width * pixelRatio;
  40839. * size.y = height * pixelRatio;
  40840. * ```
  40841. *
  40842. * @param {number} width - The width in logical pixels.
  40843. * @param {number} height - The height in logical pixels.
  40844. * @param {number} pixelRatio - The pixel ratio.
  40845. */
  40846. setDrawingBufferSize( width, height, pixelRatio ) {
  40847. // Renderer can't be resized while presenting in XR.
  40848. if ( this.xr && this.xr.isPresenting ) return;
  40849. this._width = width;
  40850. this._height = height;
  40851. this._pixelRatio = pixelRatio;
  40852. this.domElement.width = Math.floor( width * pixelRatio );
  40853. this.domElement.height = Math.floor( height * pixelRatio );
  40854. this.setViewport( 0, 0, width, height );
  40855. this._dispatchResize();
  40856. }
  40857. /**
  40858. * Sets the size of the renderer.
  40859. *
  40860. * @param {number} width - The width in logical pixels.
  40861. * @param {number} height - The height in logical pixels.
  40862. * @param {boolean} [updateStyle=true] - Whether to update the `style` attribute of the canvas or not.
  40863. */
  40864. setSize( width, height, updateStyle = true ) {
  40865. // Renderer can't be resized while presenting in XR.
  40866. if ( this.xr && this.xr.isPresenting ) return;
  40867. this._width = width;
  40868. this._height = height;
  40869. this.domElement.width = Math.floor( width * this._pixelRatio );
  40870. this.domElement.height = Math.floor( height * this._pixelRatio );
  40871. if ( updateStyle === true ) {
  40872. this.domElement.style.width = width + 'px';
  40873. this.domElement.style.height = height + 'px';
  40874. }
  40875. this.setViewport( 0, 0, width, height );
  40876. this._dispatchResize();
  40877. }
  40878. /**
  40879. * Returns the scissor rectangle.
  40880. *
  40881. * @param {Vector4} target - The method writes the result in this target object.
  40882. * @return {Vector4} The scissor rectangle.
  40883. */
  40884. getScissor( target ) {
  40885. const scissor = this._scissor;
  40886. target.x = scissor.x;
  40887. target.y = scissor.y;
  40888. target.width = scissor.width;
  40889. target.height = scissor.height;
  40890. return target;
  40891. }
  40892. /**
  40893. * Defines the scissor rectangle.
  40894. *
  40895. * @param {number | Vector4} x - The horizontal coordinate for the lower left corner of the box in logical pixel unit.
  40896. * Instead of passing four arguments, the method also works with a single four-dimensional vector.
  40897. * @param {number} y - The vertical coordinate for the lower left corner of the box in logical pixel unit.
  40898. * @param {number} width - The width of the scissor box in logical pixel unit.
  40899. * @param {number} height - The height of the scissor box in logical pixel unit.
  40900. */
  40901. setScissor( x, y, width, height ) {
  40902. const scissor = this._scissor;
  40903. if ( x.isVector4 ) {
  40904. scissor.copy( x );
  40905. } else {
  40906. scissor.set( x, y, width, height );
  40907. }
  40908. }
  40909. /**
  40910. * Returns the scissor test value.
  40911. *
  40912. * @return {boolean} Whether the scissor test should be enabled or not.
  40913. */
  40914. getScissorTest() {
  40915. return this._scissorTest;
  40916. }
  40917. /**
  40918. * Defines the scissor test.
  40919. *
  40920. * @param {boolean} boolean - Whether the scissor test should be enabled or not.
  40921. */
  40922. setScissorTest( boolean ) {
  40923. this._scissorTest = boolean;
  40924. }
  40925. /**
  40926. * Returns the viewport definition.
  40927. *
  40928. * @param {Vector4} target - The method writes the result in this target object.
  40929. * @return {Vector4} The viewport definition.
  40930. */
  40931. getViewport( target ) {
  40932. return target.copy( this._viewport );
  40933. }
  40934. /**
  40935. * Defines the viewport.
  40936. *
  40937. * @param {number | Vector4} x - The horizontal coordinate for the lower left corner of the viewport origin in logical pixel unit.
  40938. * @param {number} y - The vertical coordinate for the lower left corner of the viewport origin in logical pixel unit.
  40939. * @param {number} width - The width of the viewport in logical pixel unit.
  40940. * @param {number} height - The height of the viewport in logical pixel unit.
  40941. * @param {number} minDepth - The minimum depth value of the viewport. WebGPU only.
  40942. * @param {number} maxDepth - The maximum depth value of the viewport. WebGPU only.
  40943. */
  40944. setViewport( x, y, width, height, minDepth = 0, maxDepth = 1 ) {
  40945. const viewport = this._viewport;
  40946. if ( x.isVector4 ) {
  40947. viewport.copy( x );
  40948. } else {
  40949. viewport.set( x, y, width, height );
  40950. }
  40951. viewport.minDepth = minDepth;
  40952. viewport.maxDepth = maxDepth;
  40953. }
  40954. /**
  40955. * Dispatches the resize event.
  40956. *
  40957. * @private
  40958. */
  40959. _dispatchResize() {
  40960. this.dispatchEvent( { type: 'resize' } );
  40961. }
  40962. /**
  40963. * Frees the GPU-related resources allocated by this instance. Call this
  40964. * method whenever this instance is no longer used in your app.
  40965. *
  40966. * @fires RenderTarget#dispose
  40967. */
  40968. dispose() {
  40969. this.dispatchEvent( { type: 'dispose' } );
  40970. }
  40971. }
  40972. const _scene = /*@__PURE__*/ new Scene();
  40973. const _drawingBufferSize = /*@__PURE__*/ new Vector2();
  40974. const _screen = /*@__PURE__*/ new Vector4();
  40975. const _frustum = /*@__PURE__*/ new Frustum();
  40976. const _frustumArray = /*@__PURE__*/ new FrustumArray();
  40977. const _projScreenMatrix = /*@__PURE__*/ new Matrix4();
  40978. const _vector4 = /*@__PURE__*/ new Vector4();
  40979. /**
  40980. * Base class for renderers.
  40981. */
  40982. class Renderer {
  40983. /**
  40984. * Renderer options.
  40985. *
  40986. * @typedef {Object} Renderer~Options
  40987. * @property {boolean} [logarithmicDepthBuffer=false] - Whether logarithmic depth buffer is enabled or not.
  40988. * @property {boolean} [alpha=true] - Whether the default framebuffer (which represents the final contents of the canvas) should be transparent or opaque.
  40989. * @property {boolean} [depth=true] - Whether the default framebuffer should have a depth buffer or not.
  40990. * @property {boolean} [stencil=false] - Whether the default framebuffer should have a stencil buffer or not.
  40991. * @property {boolean} [antialias=false] - Whether MSAA as the default anti-aliasing should be enabled or not.
  40992. * @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
  40993. * to overwrite the default.
  40994. * @property {?Function} [getFallback=null] - This callback function can be used to provide a fallback backend, if the primary backend can't be targeted.
  40995. * @property {number} [outputBufferType=HalfFloatType] - Defines the type of output buffers. The default `HalfFloatType` is recommend for best
  40996. * quality. To save memory and bandwidth, `UnsignedByteType` might be used. This will reduce rendering quality though.
  40997. * @property {boolean} [multiview=false] - If set to `true`, the renderer will use multiview during WebXR rendering if supported.
  40998. */
  40999. /**
  41000. * Constructs a new renderer.
  41001. *
  41002. * @param {Backend} backend - The backend the renderer is targeting (e.g. WebGPU or WebGL 2).
  41003. * @param {Renderer~Options} [parameters] - The configuration parameter.
  41004. */
  41005. constructor( backend, parameters = {} ) {
  41006. /**
  41007. * This flag can be used for type testing.
  41008. *
  41009. * @type {boolean}
  41010. * @readonly
  41011. * @default true
  41012. */
  41013. this.isRenderer = true;
  41014. //
  41015. const {
  41016. logarithmicDepthBuffer = false,
  41017. alpha = true,
  41018. depth = true,
  41019. stencil = false,
  41020. antialias = false,
  41021. samples = 0,
  41022. getFallback = null,
  41023. outputBufferType = HalfFloatType,
  41024. multiview = false
  41025. } = parameters;
  41026. /**
  41027. * A reference to the current backend.
  41028. *
  41029. * @type {Backend}
  41030. */
  41031. this.backend = backend;
  41032. /**
  41033. * Whether the renderer should automatically clear the current rendering target
  41034. * before execute a `render()` call. The target can be the canvas (default framebuffer)
  41035. * or the current bound render target (custom framebuffer).
  41036. *
  41037. * @type {boolean}
  41038. * @default true
  41039. */
  41040. this.autoClear = true;
  41041. /**
  41042. * When `autoClear` is set to `true`, this property defines whether the renderer
  41043. * should clear the color buffer.
  41044. *
  41045. * @type {boolean}
  41046. * @default true
  41047. */
  41048. this.autoClearColor = true;
  41049. /**
  41050. * When `autoClear` is set to `true`, this property defines whether the renderer
  41051. * should clear the depth buffer.
  41052. *
  41053. * @type {boolean}
  41054. * @default true
  41055. */
  41056. this.autoClearDepth = true;
  41057. /**
  41058. * When `autoClear` is set to `true`, this property defines whether the renderer
  41059. * should clear the stencil buffer.
  41060. *
  41061. * @type {boolean}
  41062. * @default true
  41063. */
  41064. this.autoClearStencil = true;
  41065. /**
  41066. * Whether the default framebuffer should be transparent or opaque.
  41067. *
  41068. * @type {boolean}
  41069. * @default true
  41070. */
  41071. this.alpha = alpha;
  41072. /**
  41073. * Whether logarithmic depth buffer is enabled or not.
  41074. *
  41075. * @type {boolean}
  41076. * @default false
  41077. */
  41078. this.logarithmicDepthBuffer = logarithmicDepthBuffer;
  41079. /**
  41080. * Defines the output color space of the renderer.
  41081. *
  41082. * @type {string}
  41083. * @default SRGBColorSpace
  41084. */
  41085. this.outputColorSpace = SRGBColorSpace;
  41086. /**
  41087. * Defines the tone mapping of the renderer.
  41088. *
  41089. * @type {number}
  41090. * @default NoToneMapping
  41091. */
  41092. this.toneMapping = NoToneMapping;
  41093. /**
  41094. * Defines the tone mapping exposure.
  41095. *
  41096. * @type {number}
  41097. * @default 1
  41098. */
  41099. this.toneMappingExposure = 1.0;
  41100. /**
  41101. * Whether the renderer should sort its render lists or not.
  41102. *
  41103. * Note: Sorting is used to attempt to properly render objects that have some degree of transparency.
  41104. * By definition, sorting objects may not work in all cases. Depending on the needs of application,
  41105. * it may be necessary to turn off sorting and use other methods to deal with transparency rendering
  41106. * e.g. manually determining each object's rendering order.
  41107. *
  41108. * @type {boolean}
  41109. * @default true
  41110. */
  41111. this.sortObjects = true;
  41112. /**
  41113. * Whether the default framebuffer should have a depth buffer or not.
  41114. *
  41115. * @type {boolean}
  41116. * @default true
  41117. */
  41118. this.depth = depth;
  41119. /**
  41120. * Whether the default framebuffer should have a stencil buffer or not.
  41121. *
  41122. * @type {boolean}
  41123. * @default false
  41124. */
  41125. this.stencil = stencil;
  41126. /**
  41127. * Holds a series of statistical information about the GPU memory
  41128. * and the rendering process. Useful for debugging and monitoring.
  41129. *
  41130. * @type {Info}
  41131. */
  41132. this.info = new Info();
  41133. /**
  41134. * A global context node that stores override nodes for specific transformations or calculations.
  41135. * These nodes can be used to replace default behavior in the rendering pipeline.
  41136. *
  41137. * @type {ContextNode}
  41138. * @property {Object} value - The context value object.
  41139. */
  41140. this.contextNode = context();
  41141. /**
  41142. * The node library defines how certain library objects like materials, lights
  41143. * or tone mapping functions are mapped to node types. This is required since
  41144. * although instances of classes like `MeshBasicMaterial` or `PointLight` can
  41145. * be part of the scene graph, they are internally represented as nodes for
  41146. * further processing.
  41147. *
  41148. * @type {NodeLibrary}
  41149. */
  41150. this.library = new NodeLibrary();
  41151. /**
  41152. * A map-like data structure for managing lights.
  41153. *
  41154. * @type {Lighting}
  41155. */
  41156. this.lighting = new Lighting();
  41157. // internals
  41158. /**
  41159. * The number of MSAA samples.
  41160. *
  41161. * @private
  41162. * @type {number}
  41163. * @default 0
  41164. */
  41165. this._samples = samples || ( antialias === true ) ? 4 : 0;
  41166. /**
  41167. * OnCanvasTargetResize callback function.
  41168. *
  41169. * @private
  41170. * @type {Function}
  41171. */
  41172. this._onCanvasTargetResize = this._onCanvasTargetResize.bind( this );
  41173. /**
  41174. * The canvas target for rendering.
  41175. *
  41176. * @private
  41177. * @type {CanvasTarget}
  41178. */
  41179. this._canvasTarget = new CanvasTarget( backend.getDomElement() );
  41180. this._canvasTarget.addEventListener( 'resize', this._onCanvasTargetResize );
  41181. this._canvasTarget.isDefaultCanvasTarget = true;
  41182. /**
  41183. * The inspector provides information about the internal renderer state.
  41184. *
  41185. * @private
  41186. * @type {InspectorBase}
  41187. */
  41188. this._inspector = new InspectorBase();
  41189. this._inspector.setRenderer( this );
  41190. /**
  41191. * This callback function can be used to provide a fallback backend, if the primary backend can't be targeted.
  41192. *
  41193. * @private
  41194. * @type {?Function}
  41195. */
  41196. this._getFallback = getFallback;
  41197. /**
  41198. * A reference to a renderer module for managing shader attributes.
  41199. *
  41200. * @private
  41201. * @type {?Attributes}
  41202. * @default null
  41203. */
  41204. this._attributes = null;
  41205. /**
  41206. * A reference to a renderer module for managing geometries.
  41207. *
  41208. * @private
  41209. * @type {?Geometries}
  41210. * @default null
  41211. */
  41212. this._geometries = null;
  41213. /**
  41214. * A reference to a renderer module for managing node related logic.
  41215. *
  41216. * @private
  41217. * @type {?Nodes}
  41218. * @default null
  41219. */
  41220. this._nodes = null;
  41221. /**
  41222. * A reference to a renderer module for managing the internal animation loop.
  41223. *
  41224. * @private
  41225. * @type {?Animation}
  41226. * @default null
  41227. */
  41228. this._animation = null;
  41229. /**
  41230. * A reference to a renderer module for managing shader program bindings.
  41231. *
  41232. * @private
  41233. * @type {?Bindings}
  41234. * @default null
  41235. */
  41236. this._bindings = null;
  41237. /**
  41238. * A reference to a renderer module for managing render objects.
  41239. *
  41240. * @private
  41241. * @type {?RenderObjects}
  41242. * @default null
  41243. */
  41244. this._objects = null;
  41245. /**
  41246. * A reference to a renderer module for managing render and compute pipelines.
  41247. *
  41248. * @private
  41249. * @type {?Pipelines}
  41250. * @default null
  41251. */
  41252. this._pipelines = null;
  41253. /**
  41254. * A reference to a renderer module for managing render bundles.
  41255. *
  41256. * @private
  41257. * @type {?RenderBundles}
  41258. * @default null
  41259. */
  41260. this._bundles = null;
  41261. /**
  41262. * A reference to a renderer module for managing render lists.
  41263. *
  41264. * @private
  41265. * @type {?RenderLists}
  41266. * @default null
  41267. */
  41268. this._renderLists = null;
  41269. /**
  41270. * A reference to a renderer module for managing render contexts.
  41271. *
  41272. * @private
  41273. * @type {?RenderContexts}
  41274. * @default null
  41275. */
  41276. this._renderContexts = null;
  41277. /**
  41278. * A reference to a renderer module for managing textures.
  41279. *
  41280. * @private
  41281. * @type {?Textures}
  41282. * @default null
  41283. */
  41284. this._textures = null;
  41285. /**
  41286. * A reference to a renderer module for backgrounds.
  41287. *
  41288. * @private
  41289. * @type {?Background}
  41290. * @default null
  41291. */
  41292. this._background = null;
  41293. /**
  41294. * This fullscreen quad is used for internal render passes
  41295. * like the tone mapping and color space output pass.
  41296. *
  41297. * @private
  41298. * @type {QuadMesh}
  41299. */
  41300. this._quad = new QuadMesh( new NodeMaterial() );
  41301. this._quad.name = 'Output Color Transform';
  41302. this._quad.material.name = 'outputColorTransform';
  41303. /**
  41304. * A reference to the current render context.
  41305. *
  41306. * @private
  41307. * @type {?RenderContext}
  41308. * @default null
  41309. */
  41310. this._currentRenderContext = null;
  41311. /**
  41312. * A custom sort function for the opaque render list.
  41313. *
  41314. * @private
  41315. * @type {?Function}
  41316. * @default null
  41317. */
  41318. this._opaqueSort = null;
  41319. /**
  41320. * A custom sort function for the transparent render list.
  41321. *
  41322. * @private
  41323. * @type {?Function}
  41324. * @default null
  41325. */
  41326. this._transparentSort = null;
  41327. /**
  41328. * The framebuffer target.
  41329. *
  41330. * @private
  41331. * @type {?RenderTarget}
  41332. * @default null
  41333. */
  41334. this._frameBufferTarget = null;
  41335. const alphaClear = this.alpha === true ? 0 : 1;
  41336. /**
  41337. * The clear color value.
  41338. *
  41339. * @private
  41340. * @type {Color4}
  41341. */
  41342. this._clearColor = new Color4( 0, 0, 0, alphaClear );
  41343. /**
  41344. * The clear depth value.
  41345. *
  41346. * @private
  41347. * @type {number}
  41348. * @default 1
  41349. */
  41350. this._clearDepth = 1;
  41351. /**
  41352. * The clear stencil value.
  41353. *
  41354. * @private
  41355. * @type {number}
  41356. * @default 0
  41357. */
  41358. this._clearStencil = 0;
  41359. /**
  41360. * The current render target.
  41361. *
  41362. * @private
  41363. * @type {?RenderTarget}
  41364. * @default null
  41365. */
  41366. this._renderTarget = null;
  41367. /**
  41368. * The active cube face.
  41369. *
  41370. * @private
  41371. * @type {number}
  41372. * @default 0
  41373. */
  41374. this._activeCubeFace = 0;
  41375. /**
  41376. * The active mipmap level.
  41377. *
  41378. * @private
  41379. * @type {number}
  41380. * @default 0
  41381. */
  41382. this._activeMipmapLevel = 0;
  41383. /**
  41384. * The current output render target.
  41385. *
  41386. * @private
  41387. * @type {?RenderTarget}
  41388. * @default null
  41389. */
  41390. this._outputRenderTarget = null;
  41391. /**
  41392. * The MRT setting.
  41393. *
  41394. * @private
  41395. * @type {?MRTNode}
  41396. * @default null
  41397. */
  41398. this._mrt = null;
  41399. /**
  41400. * This function defines how a render object is going
  41401. * to be rendered.
  41402. *
  41403. * @private
  41404. * @type {?Function}
  41405. * @default null
  41406. */
  41407. this._renderObjectFunction = null;
  41408. /**
  41409. * Used to keep track of the current render object function.
  41410. *
  41411. * @private
  41412. * @type {?Function}
  41413. * @default null
  41414. */
  41415. this._currentRenderObjectFunction = null;
  41416. /**
  41417. * Used to keep track of the current render bundle.
  41418. *
  41419. * @private
  41420. * @type {?RenderBundle}
  41421. * @default null
  41422. */
  41423. this._currentRenderBundle = null;
  41424. /**
  41425. * Next to `_renderObjectFunction()`, this function provides another hook
  41426. * for influencing the render process of a render object. It is meant for internal
  41427. * use and only relevant for `compileAsync()` right now. Instead of using
  41428. * the default logic of `_renderObjectDirect()` which actually draws the render object,
  41429. * a different function might be used which performs no draw but just the node
  41430. * and pipeline updates.
  41431. *
  41432. * @private
  41433. * @type {?Function}
  41434. * @default null
  41435. */
  41436. this._handleObjectFunction = this._renderObjectDirect;
  41437. /**
  41438. * Indicates whether the device has been lost or not. In WebGL terms, the device
  41439. * lost is considered as a context lost. When this is set to `true`, rendering
  41440. * isn't possible anymore.
  41441. *
  41442. * @private
  41443. * @type {boolean}
  41444. * @default false
  41445. */
  41446. this._isDeviceLost = false;
  41447. /**
  41448. * A callback function that defines what should happen when a device/context lost occurs.
  41449. *
  41450. * @type {Function}
  41451. */
  41452. this.onDeviceLost = this._onDeviceLost;
  41453. /**
  41454. * Defines the type of output buffers. The default `HalfFloatType` is recommend for
  41455. * best quality. To save memory and bandwidth, `UnsignedByteType` might be used.
  41456. * This will reduce rendering quality though.
  41457. *
  41458. * @private
  41459. * @type {number}
  41460. * @default HalfFloatType
  41461. */
  41462. this._outputBufferType = outputBufferType;
  41463. /**
  41464. * A cache for shadow nodes per material
  41465. *
  41466. * @private
  41467. * @type {WeakMap<Material, Object>}
  41468. */
  41469. this._cacheShadowNodes = new WeakMap();
  41470. /**
  41471. * Whether the renderer has been initialized or not.
  41472. *
  41473. * @private
  41474. * @type {boolean}
  41475. * @default false
  41476. */
  41477. this._initialized = false;
  41478. /**
  41479. * A reference to the promise which initializes the renderer.
  41480. *
  41481. * @private
  41482. * @type {?Promise<this>}
  41483. * @default null
  41484. */
  41485. this._initPromise = null;
  41486. /**
  41487. * An array of compilation promises which are used in `compileAsync()`.
  41488. *
  41489. * @private
  41490. * @type {?Array<Promise>}
  41491. * @default null
  41492. */
  41493. this._compilationPromises = null;
  41494. /**
  41495. * Whether the renderer should render transparent render objects or not.
  41496. *
  41497. * @type {boolean}
  41498. * @default true
  41499. */
  41500. this.transparent = true;
  41501. /**
  41502. * Whether the renderer should render opaque render objects or not.
  41503. *
  41504. * @type {boolean}
  41505. * @default true
  41506. */
  41507. this.opaque = true;
  41508. /**
  41509. * Shadow map configuration
  41510. * @typedef {Object} ShadowMapConfig
  41511. * @property {boolean} enabled - Whether to globally enable shadows or not.
  41512. * @property {number} type - The shadow map type.
  41513. */
  41514. /**
  41515. * The renderer's shadow configuration.
  41516. *
  41517. * @type {ShadowMapConfig}
  41518. */
  41519. this.shadowMap = {
  41520. enabled: false,
  41521. type: PCFShadowMap
  41522. };
  41523. /**
  41524. * XR configuration.
  41525. * @typedef {Object} XRConfig
  41526. * @property {boolean} enabled - Whether to globally enable XR or not.
  41527. */
  41528. /**
  41529. * The renderer's XR manager.
  41530. *
  41531. * @type {XRManager}
  41532. */
  41533. this.xr = new XRManager( this, multiview );
  41534. /**
  41535. * Debug configuration.
  41536. * @typedef {Object} DebugConfig
  41537. * @property {boolean} checkShaderErrors - Whether shader errors should be checked or not.
  41538. * @property {?Function} onShaderError - A callback function that is executed when a shader error happens. Only supported with WebGL 2 right now.
  41539. * @property {Function} getShaderAsync - Allows the get the raw shader code for the given scene, camera and 3D object.
  41540. */
  41541. /**
  41542. * The renderer's debug configuration.
  41543. *
  41544. * @type {DebugConfig}
  41545. */
  41546. this.debug = {
  41547. checkShaderErrors: true,
  41548. onShaderError: null,
  41549. getShaderAsync: async ( scene, camera, object ) => {
  41550. await this.compileAsync( scene, camera );
  41551. const renderList = this._renderLists.get( scene, camera );
  41552. const renderContext = this._renderContexts.get( scene, camera, this._renderTarget, this._mrt );
  41553. const material = scene.overrideMaterial || object.material;
  41554. const renderObject = this._objects.get( object, material, scene, camera, renderList.lightsNode, renderContext, renderContext.clippingContext );
  41555. const { fragmentShader, vertexShader } = renderObject.getNodeBuilderState();
  41556. return { fragmentShader, vertexShader };
  41557. }
  41558. };
  41559. }
  41560. /**
  41561. * Initializes the renderer so it is ready for usage.
  41562. *
  41563. * @async
  41564. * @return {Promise<this>} A Promise that resolves when the renderer has been initialized.
  41565. */
  41566. async init() {
  41567. if ( this._initPromise !== null ) {
  41568. return this._initPromise;
  41569. }
  41570. this._initPromise = new Promise( async ( resolve, reject ) => {
  41571. let backend = this.backend;
  41572. try {
  41573. await backend.init( this );
  41574. } catch ( error ) {
  41575. if ( this._getFallback !== null ) {
  41576. // try the fallback
  41577. try {
  41578. this.backend = backend = this._getFallback( error );
  41579. await backend.init( this );
  41580. } catch ( error ) {
  41581. reject( error );
  41582. return;
  41583. }
  41584. } else {
  41585. reject( error );
  41586. return;
  41587. }
  41588. }
  41589. this._nodes = new Nodes( this, backend );
  41590. this._animation = new Animation( this, this._nodes, this.info );
  41591. this._attributes = new Attributes( backend );
  41592. this._background = new Background( this, this._nodes );
  41593. this._geometries = new Geometries( this._attributes, this.info );
  41594. this._textures = new Textures( this, backend, this.info );
  41595. this._pipelines = new Pipelines( backend, this._nodes );
  41596. this._bindings = new Bindings( backend, this._nodes, this._textures, this._attributes, this._pipelines, this.info );
  41597. this._objects = new RenderObjects( this, this._nodes, this._geometries, this._pipelines, this._bindings, this.info );
  41598. this._renderLists = new RenderLists( this.lighting );
  41599. this._bundles = new RenderBundles();
  41600. this._renderContexts = new RenderContexts();
  41601. //
  41602. this._animation.start();
  41603. this._initialized = true;
  41604. //
  41605. this._inspector.init();
  41606. //
  41607. resolve( this );
  41608. } );
  41609. return this._initPromise;
  41610. }
  41611. /**
  41612. * A reference to the canvas element the renderer is drawing to.
  41613. * This value of this property will automatically be created by
  41614. * the renderer.
  41615. *
  41616. * @type {HTMLCanvasElement|OffscreenCanvas}
  41617. */
  41618. get domElement() {
  41619. return this._canvasTarget.domElement;
  41620. }
  41621. /**
  41622. * The coordinate system of the renderer. The value of this property
  41623. * depends on the selected backend. Either `THREE.WebGLCoordinateSystem` or
  41624. * `THREE.WebGPUCoordinateSystem`.
  41625. *
  41626. * @readonly
  41627. * @type {number}
  41628. */
  41629. get coordinateSystem() {
  41630. return this.backend.coordinateSystem;
  41631. }
  41632. /**
  41633. * Compiles all materials in the given scene. This can be useful to avoid a
  41634. * phenomenon which is called "shader compilation stutter", which occurs when
  41635. * rendering an object with a new shader for the first time.
  41636. *
  41637. * If you want to add a 3D object to an existing scene, use the third optional
  41638. * parameter for applying the target scene. Note that the (target) scene's lighting
  41639. * and environment must be configured before calling this method.
  41640. *
  41641. * @async
  41642. * @param {Object3D} scene - The scene or 3D object to precompile.
  41643. * @param {Camera} camera - The camera that is used to render the scene.
  41644. * @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.
  41645. * @return {Promise} A Promise that resolves when the compile has been finished.
  41646. */
  41647. async compileAsync( scene, camera, targetScene = null ) {
  41648. if ( this._isDeviceLost === true ) return;
  41649. if ( this._initialized === false ) await this.init();
  41650. // preserve render tree
  41651. const nodeFrame = this._nodes.nodeFrame;
  41652. const previousRenderId = nodeFrame.renderId;
  41653. const previousRenderContext = this._currentRenderContext;
  41654. const previousRenderObjectFunction = this._currentRenderObjectFunction;
  41655. const previousCompilationPromises = this._compilationPromises;
  41656. //
  41657. const sceneRef = ( scene.isScene === true ) ? scene : _scene;
  41658. if ( targetScene === null ) targetScene = scene;
  41659. const renderTarget = this._renderTarget;
  41660. const renderContext = this._renderContexts.get( targetScene, camera, renderTarget, this._mrt );
  41661. const activeMipmapLevel = this._activeMipmapLevel;
  41662. const compilationPromises = [];
  41663. this._currentRenderContext = renderContext;
  41664. this._currentRenderObjectFunction = this.renderObject;
  41665. this._handleObjectFunction = this._createObjectPipeline;
  41666. this._compilationPromises = compilationPromises;
  41667. nodeFrame.renderId ++;
  41668. //
  41669. nodeFrame.update();
  41670. //
  41671. renderContext.depth = this.depth;
  41672. renderContext.stencil = this.stencil;
  41673. if ( ! renderContext.clippingContext ) renderContext.clippingContext = new ClippingContext();
  41674. renderContext.clippingContext.updateGlobal( sceneRef, camera );
  41675. //
  41676. sceneRef.onBeforeRender( this, scene, camera, renderTarget );
  41677. //
  41678. const renderList = this._renderLists.get( scene, camera );
  41679. renderList.begin();
  41680. this._projectObject( scene, camera, 0, renderList, renderContext.clippingContext );
  41681. // include lights from target scene
  41682. if ( targetScene !== scene ) {
  41683. targetScene.traverseVisible( function ( object ) {
  41684. if ( object.isLight && object.layers.test( camera.layers ) ) {
  41685. renderList.pushLight( object );
  41686. }
  41687. } );
  41688. }
  41689. renderList.finish();
  41690. //
  41691. if ( renderTarget !== null ) {
  41692. this._textures.updateRenderTarget( renderTarget, activeMipmapLevel );
  41693. const renderTargetData = this._textures.get( renderTarget );
  41694. renderContext.textures = renderTargetData.textures;
  41695. renderContext.depthTexture = renderTargetData.depthTexture;
  41696. } else {
  41697. renderContext.textures = null;
  41698. renderContext.depthTexture = null;
  41699. }
  41700. //
  41701. this._background.update( sceneRef, renderList, renderContext );
  41702. // process render lists
  41703. const opaqueObjects = renderList.opaque;
  41704. const transparentObjects = renderList.transparent;
  41705. const transparentDoublePassObjects = renderList.transparentDoublePass;
  41706. const lightsNode = renderList.lightsNode;
  41707. if ( this.opaque === true && opaqueObjects.length > 0 ) this._renderObjects( opaqueObjects, camera, sceneRef, lightsNode );
  41708. if ( this.transparent === true && transparentObjects.length > 0 ) this._renderTransparents( transparentObjects, transparentDoublePassObjects, camera, sceneRef, lightsNode );
  41709. // restore render tree
  41710. nodeFrame.renderId = previousRenderId;
  41711. this._currentRenderContext = previousRenderContext;
  41712. this._currentRenderObjectFunction = previousRenderObjectFunction;
  41713. this._compilationPromises = previousCompilationPromises;
  41714. this._handleObjectFunction = this._renderObjectDirect;
  41715. // wait for all promises setup by backends awaiting compilation/linking/pipeline creation to complete
  41716. await Promise.all( compilationPromises );
  41717. }
  41718. /**
  41719. * Renders the scene in an async fashion.
  41720. *
  41721. * @async
  41722. * @deprecated
  41723. * @param {Object3D} scene - The scene or 3D object to render.
  41724. * @param {Camera} camera - The camera.
  41725. * @return {Promise} A Promise that resolves when the render has been finished.
  41726. */
  41727. async renderAsync( scene, camera ) {
  41728. warnOnce( 'Renderer: "renderAsync()" has been deprecated. Use "render()" and "await renderer.init();" when creating the renderer.' ); // @deprecated r181
  41729. await this.init();
  41730. this.render( scene, camera );
  41731. }
  41732. /**
  41733. * Can be used to synchronize CPU operations with GPU tasks. So when this method is called,
  41734. * the CPU waits for the GPU to complete its operation (e.g. a compute task).
  41735. *
  41736. * @async
  41737. * @deprecated
  41738. * @return {Promise} A Promise that resolves when synchronization has been finished.
  41739. */
  41740. async waitForGPU() {
  41741. error( 'Renderer: waitForGPU() has been removed. Read https://github.com/mrdoob/three.js/issues/32012 for more information.' );
  41742. }
  41743. //
  41744. set inspector( value ) {
  41745. if ( this._inspector !== null ) {
  41746. this._inspector.setRenderer( null );
  41747. }
  41748. this._inspector = value;
  41749. this._inspector.setRenderer( this );
  41750. }
  41751. /**
  41752. * The inspector instance. The inspector can be any class that extends from `InspectorBase`.
  41753. *
  41754. * @type {InspectorBase}
  41755. */
  41756. get inspector() {
  41757. return this._inspector;
  41758. }
  41759. /**
  41760. * Enables or disables high precision for model-view and normal-view matrices.
  41761. * When enabled, will use CPU 64-bit precision for higher precision instead of GPU 32-bit for higher performance.
  41762. *
  41763. * NOTE: 64-bit precision is not compatible with `InstancedMesh` and `SkinnedMesh`.
  41764. *
  41765. * @param {boolean} value - Whether to enable or disable high precision.
  41766. * @type {boolean}
  41767. */
  41768. set highPrecision( value ) {
  41769. const contextNodeData = this.contextNode.value;
  41770. if ( value === true ) {
  41771. contextNodeData.modelViewMatrix = highpModelViewMatrix;
  41772. contextNodeData.modelNormalViewMatrix = highpModelNormalViewMatrix;
  41773. } else if ( this.highPrecision ) {
  41774. delete contextNodeData.modelViewMatrix;
  41775. delete contextNodeData.modelNormalViewMatrix;
  41776. }
  41777. }
  41778. /**
  41779. * Returns whether high precision is enabled or not.
  41780. *
  41781. * @return {boolean} Whether high precision is enabled or not.
  41782. * @type {boolean}
  41783. */
  41784. get highPrecision() {
  41785. const contextNodeData = this.contextNode.value;
  41786. return contextNodeData.modelViewMatrix === highpModelViewMatrix && contextNodeData.modelNormalViewMatrix === highpModelNormalViewMatrix;
  41787. }
  41788. /**
  41789. * Sets the given MRT configuration.
  41790. *
  41791. * @param {MRTNode} mrt - The MRT node to set.
  41792. * @return {Renderer} A reference to this renderer.
  41793. */
  41794. setMRT( mrt ) {
  41795. this._mrt = mrt;
  41796. return this;
  41797. }
  41798. /**
  41799. * Returns the MRT configuration.
  41800. *
  41801. * @return {MRTNode} The MRT configuration.
  41802. */
  41803. getMRT() {
  41804. return this._mrt;
  41805. }
  41806. /**
  41807. * Returns the output buffer type.
  41808. *
  41809. * @return {number} The output buffer type.
  41810. */
  41811. getOutputBufferType() {
  41812. return this._outputBufferType;
  41813. }
  41814. /**
  41815. * Returns the output buffer type.
  41816. *
  41817. * @deprecated since r182. Use `.getOutputBufferType()` instead.
  41818. * @return {number} The output buffer type.
  41819. */
  41820. getColorBufferType() { // @deprecated, r182
  41821. warnOnce( 'Renderer: ".getColorBufferType()" has been renamed to ".getOutputBufferType()".' );
  41822. return this.getOutputBufferType();
  41823. }
  41824. /**
  41825. * Default implementation of the device lost callback.
  41826. *
  41827. * @private
  41828. * @param {Object} info - Information about the context lost.
  41829. */
  41830. _onDeviceLost( info ) {
  41831. let errorMessage = `THREE.WebGPURenderer: ${info.api} Device Lost:\n\nMessage: ${info.message}`;
  41832. if ( info.reason ) {
  41833. errorMessage += `\nReason: ${info.reason}`;
  41834. }
  41835. error( errorMessage );
  41836. this._isDeviceLost = true;
  41837. }
  41838. /**
  41839. * Renders the given render bundle.
  41840. *
  41841. * @private
  41842. * @param {Object} bundle - Render bundle data.
  41843. * @param {Scene} sceneRef - The scene the render bundle belongs to.
  41844. * @param {LightsNode} lightsNode - The lights node.
  41845. */
  41846. _renderBundle( bundle, sceneRef, lightsNode ) {
  41847. const { bundleGroup, camera, renderList } = bundle;
  41848. const renderContext = this._currentRenderContext;
  41849. //
  41850. const renderBundle = this._bundles.get( bundleGroup, camera );
  41851. const renderBundleData = this.backend.get( renderBundle );
  41852. if ( renderBundleData.renderContexts === undefined ) renderBundleData.renderContexts = new Set();
  41853. //
  41854. const needsUpdate = bundleGroup.version !== renderBundleData.version;
  41855. const renderBundleNeedsUpdate = renderBundleData.renderContexts.has( renderContext ) === false || needsUpdate;
  41856. renderBundleData.renderContexts.add( renderContext );
  41857. if ( renderBundleNeedsUpdate ) {
  41858. this.backend.beginBundle( renderContext );
  41859. if ( renderBundleData.renderObjects === undefined || needsUpdate ) {
  41860. renderBundleData.renderObjects = [];
  41861. }
  41862. this._currentRenderBundle = renderBundle;
  41863. const {
  41864. transparentDoublePass: transparentDoublePassObjects,
  41865. transparent: transparentObjects,
  41866. opaque: opaqueObjects
  41867. } = renderList;
  41868. if ( this.opaque === true && opaqueObjects.length > 0 ) this._renderObjects( opaqueObjects, camera, sceneRef, lightsNode );
  41869. if ( this.transparent === true && transparentObjects.length > 0 ) this._renderTransparents( transparentObjects, transparentDoublePassObjects, camera, sceneRef, lightsNode );
  41870. this._currentRenderBundle = null;
  41871. //
  41872. this.backend.finishBundle( renderContext, renderBundle );
  41873. renderBundleData.version = bundleGroup.version;
  41874. } else {
  41875. const { renderObjects } = renderBundleData;
  41876. for ( let i = 0, l = renderObjects.length; i < l; i ++ ) {
  41877. const renderObject = renderObjects[ i ];
  41878. if ( this._nodes.needsRefresh( renderObject ) ) {
  41879. this._nodes.updateBefore( renderObject );
  41880. this._nodes.updateForRender( renderObject );
  41881. this._bindings.updateForRender( renderObject );
  41882. this._nodes.updateAfter( renderObject );
  41883. }
  41884. }
  41885. }
  41886. this.backend.addBundle( renderContext, renderBundle );
  41887. }
  41888. /**
  41889. * Renders the scene or 3D object with the given camera. This method can only be called
  41890. * if the renderer has been initialized. When using `render()` inside an animation loop,
  41891. * it's guaranteed the renderer will be initialized. The animation loop must be defined
  41892. * with {@link Renderer#setAnimationLoop} though.
  41893. *
  41894. * For all other use cases (like when using on-demand rendering), you must call
  41895. * {@link Renderer#init} before rendering.
  41896. *
  41897. * The target of the method is the default framebuffer (meaning the canvas)
  41898. * or alternatively a render target when specified via `setRenderTarget()`.
  41899. *
  41900. * @param {Object3D} scene - The scene or 3D object to render.
  41901. * @param {Camera} camera - The camera to render the scene with.
  41902. */
  41903. render( scene, camera ) {
  41904. if ( this._initialized === false ) {
  41905. throw new Error( 'Renderer: .render() called before the backend is initialized. Use "await renderer.init();" before rendering.' );
  41906. }
  41907. this._renderScene( scene, camera );
  41908. }
  41909. /**
  41910. * Returns whether the renderer has been initialized or not.
  41911. *
  41912. * @readonly
  41913. * @return {boolean} Whether the renderer has been initialized or not.
  41914. */
  41915. get initialized() {
  41916. return this._initialized;
  41917. }
  41918. /**
  41919. * Returns an internal render target which is used when computing the output tone mapping
  41920. * and color space conversion. Unlike in `WebGLRenderer`, this is done in a separate render
  41921. * pass and not inline to achieve more correct results.
  41922. *
  41923. * @private
  41924. * @return {?RenderTarget} The render target. The method returns `null` if no output conversion should be applied.
  41925. */
  41926. _getFrameBufferTarget() {
  41927. const { currentToneMapping, currentColorSpace } = this;
  41928. const useToneMapping = currentToneMapping !== NoToneMapping;
  41929. const useColorSpace = currentColorSpace !== ColorManagement.workingColorSpace;
  41930. if ( useToneMapping === false && useColorSpace === false ) return null;
  41931. const { width, height } = this.getDrawingBufferSize( _drawingBufferSize );
  41932. const { depth, stencil } = this;
  41933. let frameBufferTarget = this._frameBufferTarget;
  41934. if ( frameBufferTarget === null ) {
  41935. frameBufferTarget = new RenderTarget( width, height, {
  41936. depthBuffer: depth,
  41937. stencilBuffer: stencil,
  41938. type: this._outputBufferType,
  41939. format: RGBAFormat,
  41940. colorSpace: ColorManagement.workingColorSpace,
  41941. generateMipmaps: false,
  41942. minFilter: LinearFilter,
  41943. magFilter: LinearFilter,
  41944. samples: this.samples
  41945. } );
  41946. frameBufferTarget.isPostProcessingRenderTarget = true;
  41947. this._frameBufferTarget = frameBufferTarget;
  41948. }
  41949. const outputRenderTarget = this.getOutputRenderTarget();
  41950. frameBufferTarget.depthBuffer = depth;
  41951. frameBufferTarget.stencilBuffer = stencil;
  41952. if ( outputRenderTarget !== null ) {
  41953. frameBufferTarget.setSize( outputRenderTarget.width, outputRenderTarget.height, outputRenderTarget.depth );
  41954. } else {
  41955. frameBufferTarget.setSize( width, height, 1 );
  41956. }
  41957. const canvasTarget = this._canvasTarget;
  41958. frameBufferTarget.viewport.copy( canvasTarget._viewport );
  41959. frameBufferTarget.scissor.copy( canvasTarget._scissor );
  41960. frameBufferTarget.viewport.multiplyScalar( canvasTarget._pixelRatio );
  41961. frameBufferTarget.scissor.multiplyScalar( canvasTarget._pixelRatio );
  41962. frameBufferTarget.scissorTest = canvasTarget._scissorTest;
  41963. frameBufferTarget.multiview = outputRenderTarget !== null ? outputRenderTarget.multiview : false;
  41964. frameBufferTarget.resolveDepthBuffer = outputRenderTarget !== null ? outputRenderTarget.resolveDepthBuffer : true;
  41965. frameBufferTarget._autoAllocateDepthBuffer = outputRenderTarget !== null ? outputRenderTarget._autoAllocateDepthBuffer : false;
  41966. return frameBufferTarget;
  41967. }
  41968. /**
  41969. * Renders the scene or 3D object with the given camera.
  41970. *
  41971. * @private
  41972. * @param {Object3D} scene - The scene or 3D object to render.
  41973. * @param {Camera} camera - The camera to render the scene with.
  41974. * @param {boolean} [useFrameBufferTarget=true] - Whether to use a framebuffer target or not.
  41975. * @return {RenderContext} The current render context.
  41976. */
  41977. _renderScene( scene, camera, useFrameBufferTarget = true ) {
  41978. if ( this._isDeviceLost === true ) return;
  41979. //
  41980. const frameBufferTarget = useFrameBufferTarget ? this._getFrameBufferTarget() : null;
  41981. // preserve render tree
  41982. const nodeFrame = this._nodes.nodeFrame;
  41983. const previousRenderId = nodeFrame.renderId;
  41984. const previousRenderContext = this._currentRenderContext;
  41985. const previousRenderObjectFunction = this._currentRenderObjectFunction;
  41986. //
  41987. const sceneRef = ( scene.isScene === true ) ? scene : _scene;
  41988. const outputRenderTarget = this._renderTarget || this._outputRenderTarget;
  41989. const activeCubeFace = this._activeCubeFace;
  41990. const activeMipmapLevel = this._activeMipmapLevel;
  41991. //
  41992. let renderTarget;
  41993. if ( frameBufferTarget !== null ) {
  41994. renderTarget = frameBufferTarget;
  41995. this.setRenderTarget( renderTarget );
  41996. } else {
  41997. renderTarget = outputRenderTarget;
  41998. }
  41999. //
  42000. const renderContext = this._renderContexts.get( scene, camera, renderTarget, this._mrt );
  42001. this._currentRenderContext = renderContext;
  42002. this._currentRenderObjectFunction = this._renderObjectFunction || this.renderObject;
  42003. //
  42004. this.info.calls ++;
  42005. this.info.render.calls ++;
  42006. this.info.render.frameCalls ++;
  42007. nodeFrame.renderId = this.info.calls;
  42008. //
  42009. this.backend.updateTimeStampUID( renderContext );
  42010. this.inspector.beginRender( this.backend.getTimestampUID( renderContext ), scene, camera, renderTarget );
  42011. //
  42012. const coordinateSystem = this.coordinateSystem;
  42013. const xr = this.xr;
  42014. if ( camera.coordinateSystem !== coordinateSystem && xr.isPresenting === false ) {
  42015. camera.coordinateSystem = coordinateSystem;
  42016. camera.updateProjectionMatrix();
  42017. if ( camera.isArrayCamera ) {
  42018. for ( const subCamera of camera.cameras ) {
  42019. subCamera.coordinateSystem = coordinateSystem;
  42020. subCamera.updateProjectionMatrix();
  42021. }
  42022. }
  42023. }
  42024. //
  42025. if ( scene.matrixWorldAutoUpdate === true ) scene.updateMatrixWorld();
  42026. if ( camera.parent === null && camera.matrixWorldAutoUpdate === true ) camera.updateMatrixWorld();
  42027. if ( xr.enabled === true && xr.isPresenting === true ) {
  42028. if ( xr.cameraAutoUpdate === true ) xr.updateCamera( camera );
  42029. camera = xr.getCamera(); // use XR camera for rendering
  42030. }
  42031. //
  42032. const canvasTarget = this._canvasTarget;
  42033. let viewport = canvasTarget._viewport;
  42034. let scissor = canvasTarget._scissor;
  42035. let pixelRatio = canvasTarget._pixelRatio;
  42036. if ( renderTarget !== null ) {
  42037. viewport = renderTarget.viewport;
  42038. scissor = renderTarget.scissor;
  42039. pixelRatio = 1;
  42040. }
  42041. this.getDrawingBufferSize( _drawingBufferSize );
  42042. _screen.set( 0, 0, _drawingBufferSize.width, _drawingBufferSize.height );
  42043. const minDepth = ( viewport.minDepth === undefined ) ? 0 : viewport.minDepth;
  42044. const maxDepth = ( viewport.maxDepth === undefined ) ? 1 : viewport.maxDepth;
  42045. renderContext.viewportValue.copy( viewport ).multiplyScalar( pixelRatio ).floor();
  42046. renderContext.viewportValue.width >>= activeMipmapLevel;
  42047. renderContext.viewportValue.height >>= activeMipmapLevel;
  42048. renderContext.viewportValue.minDepth = minDepth;
  42049. renderContext.viewportValue.maxDepth = maxDepth;
  42050. renderContext.viewport = renderContext.viewportValue.equals( _screen ) === false;
  42051. renderContext.scissorValue.copy( scissor ).multiplyScalar( pixelRatio ).floor();
  42052. renderContext.scissor = canvasTarget._scissorTest && renderContext.scissorValue.equals( _screen ) === false;
  42053. renderContext.scissorValue.width >>= activeMipmapLevel;
  42054. renderContext.scissorValue.height >>= activeMipmapLevel;
  42055. if ( ! renderContext.clippingContext ) renderContext.clippingContext = new ClippingContext();
  42056. renderContext.clippingContext.updateGlobal( sceneRef, camera );
  42057. //
  42058. sceneRef.onBeforeRender( this, scene, camera, renderTarget );
  42059. //
  42060. const frustum = camera.isArrayCamera ? _frustumArray : _frustum;
  42061. if ( ! camera.isArrayCamera ) {
  42062. _projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
  42063. frustum.setFromProjectionMatrix( _projScreenMatrix, camera.coordinateSystem, camera.reversedDepth );
  42064. }
  42065. const renderList = this._renderLists.get( scene, camera );
  42066. renderList.begin();
  42067. this._projectObject( scene, camera, 0, renderList, renderContext.clippingContext );
  42068. renderList.finish();
  42069. if ( this.sortObjects === true ) {
  42070. renderList.sort( this._opaqueSort, this._transparentSort );
  42071. }
  42072. //
  42073. if ( renderTarget !== null ) {
  42074. this._textures.updateRenderTarget( renderTarget, activeMipmapLevel );
  42075. const renderTargetData = this._textures.get( renderTarget );
  42076. renderContext.textures = renderTargetData.textures;
  42077. renderContext.depthTexture = renderTargetData.depthTexture;
  42078. renderContext.width = renderTargetData.width;
  42079. renderContext.height = renderTargetData.height;
  42080. renderContext.renderTarget = renderTarget;
  42081. renderContext.depth = renderTarget.depthBuffer;
  42082. renderContext.stencil = renderTarget.stencilBuffer;
  42083. } else {
  42084. renderContext.textures = null;
  42085. renderContext.depthTexture = null;
  42086. renderContext.width = _drawingBufferSize.width;
  42087. renderContext.height = _drawingBufferSize.height;
  42088. renderContext.depth = this.depth;
  42089. renderContext.stencil = this.stencil;
  42090. }
  42091. renderContext.width >>= activeMipmapLevel;
  42092. renderContext.height >>= activeMipmapLevel;
  42093. renderContext.activeCubeFace = activeCubeFace;
  42094. renderContext.activeMipmapLevel = activeMipmapLevel;
  42095. renderContext.occlusionQueryCount = renderList.occlusionQueryCount;
  42096. //
  42097. renderContext.scissorValue.max( _vector4.set( 0, 0, 0, 0 ) );
  42098. if ( renderContext.scissorValue.x + renderContext.scissorValue.width > renderContext.width ) {
  42099. renderContext.scissorValue.width = Math.max( renderContext.width - renderContext.scissorValue.x, 0 );
  42100. }
  42101. if ( renderContext.scissorValue.y + renderContext.scissorValue.height > renderContext.height ) {
  42102. renderContext.scissorValue.height = Math.max( renderContext.height - renderContext.scissorValue.y, 0 );
  42103. }
  42104. //
  42105. this._background.update( sceneRef, renderList, renderContext );
  42106. //
  42107. renderContext.camera = camera;
  42108. this.backend.beginRender( renderContext );
  42109. // process render lists
  42110. const {
  42111. bundles,
  42112. lightsNode,
  42113. transparentDoublePass: transparentDoublePassObjects,
  42114. transparent: transparentObjects,
  42115. opaque: opaqueObjects
  42116. } = renderList;
  42117. if ( bundles.length > 0 ) this._renderBundles( bundles, sceneRef, lightsNode );
  42118. if ( this.opaque === true && opaqueObjects.length > 0 ) this._renderObjects( opaqueObjects, camera, sceneRef, lightsNode );
  42119. if ( this.transparent === true && transparentObjects.length > 0 ) this._renderTransparents( transparentObjects, transparentDoublePassObjects, camera, sceneRef, lightsNode );
  42120. // finish render pass
  42121. this.backend.finishRender( renderContext );
  42122. // restore render tree
  42123. nodeFrame.renderId = previousRenderId;
  42124. this._currentRenderContext = previousRenderContext;
  42125. this._currentRenderObjectFunction = previousRenderObjectFunction;
  42126. //
  42127. if ( frameBufferTarget !== null ) {
  42128. this.setRenderTarget( outputRenderTarget, activeCubeFace, activeMipmapLevel );
  42129. this._renderOutput( renderTarget );
  42130. }
  42131. //
  42132. sceneRef.onAfterRender( this, scene, camera, renderTarget );
  42133. //
  42134. this.inspector.finishRender( this.backend.getTimestampUID( renderContext ) );
  42135. //
  42136. return renderContext;
  42137. }
  42138. _setXRLayerSize( width, height ) {
  42139. // TODO: Find a better solution to resize the canvas when in XR.
  42140. this._canvasTarget._width = width;
  42141. this._canvasTarget._height = height;
  42142. this.setViewport( 0, 0, width, height );
  42143. }
  42144. /**
  42145. * The output pass performs tone mapping and color space conversion.
  42146. *
  42147. * @private
  42148. * @param {RenderTarget} renderTarget - The current render target.
  42149. */
  42150. _renderOutput( renderTarget ) {
  42151. const quad = this._quad;
  42152. if ( this._nodes.hasOutputChange( renderTarget.texture ) ) {
  42153. quad.material.fragmentNode = this._nodes.getOutputNode( renderTarget.texture );
  42154. quad.material.needsUpdate = true;
  42155. }
  42156. // a clear operation clears the intermediate renderTarget texture, but should not update the screen canvas.
  42157. const currentAutoClear = this.autoClear;
  42158. const currentXR = this.xr.enabled;
  42159. this.autoClear = false;
  42160. this.xr.enabled = false;
  42161. this._renderScene( quad, quad.camera, false );
  42162. this.autoClear = currentAutoClear;
  42163. this.xr.enabled = currentXR;
  42164. }
  42165. /**
  42166. * Returns the maximum available anisotropy for texture filtering.
  42167. *
  42168. * @return {number} The maximum available anisotropy.
  42169. */
  42170. getMaxAnisotropy() {
  42171. return this.backend.getMaxAnisotropy();
  42172. }
  42173. /**
  42174. * Returns the active cube face.
  42175. *
  42176. * @return {number} The active cube face.
  42177. */
  42178. getActiveCubeFace() {
  42179. return this._activeCubeFace;
  42180. }
  42181. /**
  42182. * Returns the active mipmap level.
  42183. *
  42184. * @return {number} The active mipmap level.
  42185. */
  42186. getActiveMipmapLevel() {
  42187. return this._activeMipmapLevel;
  42188. }
  42189. /**
  42190. * Applications are advised to always define the animation loop
  42191. * with this method and not manually with `requestAnimationFrame()`
  42192. * for best compatibility.
  42193. *
  42194. * @async
  42195. * @param {?onAnimationCallback} callback - The application's animation loop.
  42196. * @return {Promise} A Promise that resolves when the set has been executed.
  42197. */
  42198. async setAnimationLoop( callback ) {
  42199. if ( this._initialized === false ) await this.init();
  42200. this._animation.setAnimationLoop( callback );
  42201. }
  42202. /**
  42203. * Returns the current animation loop callback.
  42204. *
  42205. * @return {?Function} The current animation loop callback.
  42206. */
  42207. getAnimationLoop() {
  42208. return this._animation.getAnimationLoop();
  42209. }
  42210. /**
  42211. * Can be used to transfer buffer data from a storage buffer attribute
  42212. * from the GPU to the CPU in context of compute shaders.
  42213. *
  42214. * @async
  42215. * @param {StorageBufferAttribute} attribute - The storage buffer attribute.
  42216. * @return {Promise<ArrayBuffer>} A promise that resolves with the buffer data when the data are ready.
  42217. */
  42218. async getArrayBufferAsync( attribute ) {
  42219. return await this.backend.getArrayBufferAsync( attribute );
  42220. }
  42221. /**
  42222. * Returns the rendering context.
  42223. *
  42224. * @return {GPUCanvasContext|WebGL2RenderingContext} The rendering context.
  42225. */
  42226. getContext() {
  42227. return this.backend.getContext();
  42228. }
  42229. /**
  42230. * Returns the pixel ratio.
  42231. *
  42232. * @return {number} The pixel ratio.
  42233. */
  42234. getPixelRatio() {
  42235. return this._canvasTarget.getPixelRatio();
  42236. }
  42237. /**
  42238. * Returns the drawing buffer size in physical pixels. This method honors the pixel ratio.
  42239. *
  42240. * @param {Vector2} target - The method writes the result in this target object.
  42241. * @return {Vector2} The drawing buffer size.
  42242. */
  42243. getDrawingBufferSize( target ) {
  42244. return this._canvasTarget.getDrawingBufferSize( target );
  42245. }
  42246. /**
  42247. * Returns the renderer's size in logical pixels. This method does not honor the pixel ratio.
  42248. *
  42249. * @param {Vector2} target - The method writes the result in this target object.
  42250. * @return {Vector2} The renderer's size in logical pixels.
  42251. */
  42252. getSize( target ) {
  42253. return this._canvasTarget.getSize( target );
  42254. }
  42255. /**
  42256. * Sets the given pixel ratio and resizes the canvas if necessary.
  42257. *
  42258. * @param {number} [value=1] - The pixel ratio.
  42259. */
  42260. setPixelRatio( value = 1 ) {
  42261. this._canvasTarget.setPixelRatio( value );
  42262. }
  42263. /**
  42264. * This method allows to define the drawing buffer size by specifying
  42265. * width, height and pixel ratio all at once. The size of the drawing
  42266. * buffer is computed with this formula:
  42267. * ```js
  42268. * size.x = width * pixelRatio;
  42269. * size.y = height * pixelRatio;
  42270. * ```
  42271. *
  42272. * @param {number} width - The width in logical pixels.
  42273. * @param {number} height - The height in logical pixels.
  42274. * @param {number} pixelRatio - The pixel ratio.
  42275. */
  42276. setDrawingBufferSize( width, height, pixelRatio ) {
  42277. // Renderer can't be resized while presenting in XR.
  42278. if ( this.xr && this.xr.isPresenting ) return;
  42279. this._canvasTarget.setDrawingBufferSize( width, height, pixelRatio );
  42280. }
  42281. /**
  42282. * Sets the size of the renderer.
  42283. *
  42284. * @param {number} width - The width in logical pixels.
  42285. * @param {number} height - The height in logical pixels.
  42286. * @param {boolean} [updateStyle=true] - Whether to update the `style` attribute of the canvas or not.
  42287. */
  42288. setSize( width, height, updateStyle = true ) {
  42289. // Renderer can't be resized while presenting in XR.
  42290. if ( this.xr && this.xr.isPresenting ) return;
  42291. this._canvasTarget.setSize( width, height, updateStyle );
  42292. }
  42293. /**
  42294. * Defines a manual sort function for the opaque render list.
  42295. * Pass `null` to use the default sort.
  42296. *
  42297. * @param {Function} method - The sort function.
  42298. */
  42299. setOpaqueSort( method ) {
  42300. this._opaqueSort = method;
  42301. }
  42302. /**
  42303. * Defines a manual sort function for the transparent render list.
  42304. * Pass `null` to use the default sort.
  42305. *
  42306. * @param {Function} method - The sort function.
  42307. */
  42308. setTransparentSort( method ) {
  42309. this._transparentSort = method;
  42310. }
  42311. /**
  42312. * Returns the scissor rectangle.
  42313. *
  42314. * @param {Vector4} target - The method writes the result in this target object.
  42315. * @return {Vector4} The scissor rectangle.
  42316. */
  42317. getScissor( target ) {
  42318. return this._canvasTarget.getScissor( target );
  42319. }
  42320. /**
  42321. * Defines the scissor rectangle.
  42322. *
  42323. * @param {number | Vector4} x - The horizontal coordinate for the upper left corner of the box in logical pixel unit.
  42324. * Instead of passing four arguments, the method also works with a single four-dimensional vector.
  42325. * @param {number} y - The vertical coordinate for the upper left corner of the box in logical pixel unit.
  42326. * @param {number} width - The width of the scissor box in logical pixel unit.
  42327. * @param {number} height - The height of the scissor box in logical pixel unit.
  42328. */
  42329. setScissor( x, y, width, height ) {
  42330. this._canvasTarget.setScissor( x, y, width, height );
  42331. }
  42332. /**
  42333. * Returns the scissor test value.
  42334. *
  42335. * @return {boolean} Whether the scissor test should be enabled or not.
  42336. */
  42337. getScissorTest() {
  42338. return this._canvasTarget.getScissorTest();
  42339. }
  42340. /**
  42341. * Defines the scissor test.
  42342. *
  42343. * @param {boolean} boolean - Whether the scissor test should be enabled or not.
  42344. */
  42345. setScissorTest( boolean ) {
  42346. this._canvasTarget.setScissorTest( boolean );
  42347. // TODO: Move it to CanvasTarget event listener.
  42348. this.backend.setScissorTest( boolean );
  42349. }
  42350. /**
  42351. * Returns the viewport definition.
  42352. *
  42353. * @param {Vector4} target - The method writes the result in this target object.
  42354. * @return {Vector4} The viewport definition.
  42355. */
  42356. getViewport( target ) {
  42357. return this._canvasTarget.getViewport( target );
  42358. }
  42359. /**
  42360. * Defines the viewport.
  42361. *
  42362. * @param {number | Vector4} x - The horizontal coordinate for the upper left corner of the viewport origin in logical pixel unit.
  42363. * @param {number} y - The vertical coordinate for the upper left corner of the viewport origin in logical pixel unit.
  42364. * @param {number} width - The width of the viewport in logical pixel unit.
  42365. * @param {number} height - The height of the viewport in logical pixel unit.
  42366. * @param {number} minDepth - The minimum depth value of the viewport. WebGPU only.
  42367. * @param {number} maxDepth - The maximum depth value of the viewport. WebGPU only.
  42368. */
  42369. setViewport( x, y, width, height, minDepth = 0, maxDepth = 1 ) {
  42370. this._canvasTarget.setViewport( x, y, width, height, minDepth, maxDepth );
  42371. }
  42372. /**
  42373. * Returns the clear color.
  42374. *
  42375. * @param {Color} target - The method writes the result in this target object.
  42376. * @return {Color} The clear color.
  42377. */
  42378. getClearColor( target ) {
  42379. return target.copy( this._clearColor );
  42380. }
  42381. /**
  42382. * Defines the clear color and optionally the clear alpha.
  42383. *
  42384. * @param {Color} color - The clear color.
  42385. * @param {number} [alpha=1] - The clear alpha.
  42386. */
  42387. setClearColor( color, alpha = 1 ) {
  42388. this._clearColor.set( color );
  42389. this._clearColor.a = alpha;
  42390. }
  42391. /**
  42392. * Returns the clear alpha.
  42393. *
  42394. * @return {number} The clear alpha.
  42395. */
  42396. getClearAlpha() {
  42397. return this._clearColor.a;
  42398. }
  42399. /**
  42400. * Defines the clear alpha.
  42401. *
  42402. * @param {number} alpha - The clear alpha.
  42403. */
  42404. setClearAlpha( alpha ) {
  42405. this._clearColor.a = alpha;
  42406. }
  42407. /**
  42408. * Returns the clear depth.
  42409. *
  42410. * @return {number} The clear depth.
  42411. */
  42412. getClearDepth() {
  42413. return this._clearDepth;
  42414. }
  42415. /**
  42416. * Defines the clear depth.
  42417. *
  42418. * @param {number} depth - The clear depth.
  42419. */
  42420. setClearDepth( depth ) {
  42421. this._clearDepth = depth;
  42422. }
  42423. /**
  42424. * Returns the clear stencil.
  42425. *
  42426. * @return {number} The clear stencil.
  42427. */
  42428. getClearStencil() {
  42429. return this._clearStencil;
  42430. }
  42431. /**
  42432. * Defines the clear stencil.
  42433. *
  42434. * @param {number} stencil - The clear stencil.
  42435. */
  42436. setClearStencil( stencil ) {
  42437. this._clearStencil = stencil;
  42438. }
  42439. /**
  42440. * This method performs an occlusion query for the given 3D object.
  42441. * It returns `true` if the given 3D object is fully occluded by other
  42442. * 3D objects in the scene.
  42443. *
  42444. * @param {Object3D} object - The 3D object to test.
  42445. * @return {boolean} Whether the 3D object is fully occluded or not.
  42446. */
  42447. isOccluded( object ) {
  42448. const renderContext = this._currentRenderContext;
  42449. return renderContext && this.backend.isOccluded( renderContext, object );
  42450. }
  42451. /**
  42452. * Performs a manual clear operation. This method ignores `autoClear` properties.
  42453. *
  42454. * @param {boolean} [color=true] - Whether the color buffer should be cleared or not.
  42455. * @param {boolean} [depth=true] - Whether the depth buffer should be cleared or not.
  42456. * @param {boolean} [stencil=true] - Whether the stencil buffer should be cleared or not.
  42457. */
  42458. clear( color = true, depth = true, stencil = true ) {
  42459. if ( this._initialized === false ) {
  42460. throw new Error( 'Renderer: .clear() called before the backend is initialized. Use "await renderer.init();" before before using this method.' );
  42461. }
  42462. const renderTarget = this._renderTarget || this._getFrameBufferTarget();
  42463. let renderContext = null;
  42464. if ( renderTarget !== null ) {
  42465. this._textures.updateRenderTarget( renderTarget );
  42466. const renderTargetData = this._textures.get( renderTarget );
  42467. renderContext = this._renderContexts.getForClear( renderTarget );
  42468. renderContext.textures = renderTargetData.textures;
  42469. renderContext.depthTexture = renderTargetData.depthTexture;
  42470. renderContext.width = renderTargetData.width;
  42471. renderContext.height = renderTargetData.height;
  42472. renderContext.renderTarget = renderTarget;
  42473. renderContext.depth = renderTarget.depthBuffer;
  42474. renderContext.stencil = renderTarget.stencilBuffer;
  42475. // #30329
  42476. renderContext.clearColorValue = this.backend.getClearColor();
  42477. renderContext.activeCubeFace = this.getActiveCubeFace();
  42478. renderContext.activeMipmapLevel = this.getActiveMipmapLevel();
  42479. }
  42480. this.backend.clear( color, depth, stencil, renderContext );
  42481. if ( renderTarget !== null && this._renderTarget === null ) {
  42482. this._renderOutput( renderTarget );
  42483. }
  42484. }
  42485. /**
  42486. * Performs a manual clear operation of the color buffer. This method ignores `autoClear` properties.
  42487. */
  42488. clearColor() {
  42489. this.clear( true, false, false );
  42490. }
  42491. /**
  42492. * Performs a manual clear operation of the depth buffer. This method ignores `autoClear` properties.
  42493. */
  42494. clearDepth() {
  42495. this.clear( false, true, false );
  42496. }
  42497. /**
  42498. * Performs a manual clear operation of the stencil buffer. This method ignores `autoClear` properties.
  42499. */
  42500. clearStencil() {
  42501. this.clear( false, false, true );
  42502. }
  42503. /**
  42504. * Async version of {@link Renderer#clear}.
  42505. *
  42506. * @async
  42507. * @deprecated
  42508. * @param {boolean} [color=true] - Whether the color buffer should be cleared or not.
  42509. * @param {boolean} [depth=true] - Whether the depth buffer should be cleared or not.
  42510. * @param {boolean} [stencil=true] - Whether the stencil buffer should be cleared or not.
  42511. * @return {Promise} A Promise that resolves when the clear operation has been executed.
  42512. */
  42513. async clearAsync( color = true, depth = true, stencil = true ) {
  42514. warnOnce( 'Renderer: "clearAsync()" has been deprecated. Use "clear()" and "await renderer.init();" when creating the renderer.' ); // @deprecated r181
  42515. await this.init();
  42516. this.clear( color, depth, stencil );
  42517. }
  42518. /**
  42519. * Async version of {@link Renderer#clearColor}.
  42520. *
  42521. * @async
  42522. * @deprecated
  42523. * @return {Promise} A Promise that resolves when the clear operation has been executed.
  42524. */
  42525. async clearColorAsync() {
  42526. warnOnce( 'Renderer: "clearColorAsync()" has been deprecated. Use "clearColor()" and "await renderer.init();" when creating the renderer.' ); // @deprecated r181
  42527. this.clear( true, false, false );
  42528. }
  42529. /**
  42530. * Async version of {@link Renderer#clearDepth}.
  42531. *
  42532. * @async
  42533. * @deprecated
  42534. * @return {Promise} A Promise that resolves when the clear operation has been executed.
  42535. */
  42536. async clearDepthAsync() {
  42537. warnOnce( 'Renderer: "clearDepthAsync()" has been deprecated. Use "clearDepth()" and "await renderer.init();" when creating the renderer.' ); // @deprecated r181
  42538. this.clear( false, true, false );
  42539. }
  42540. /**
  42541. * Async version of {@link Renderer#clearStencil}.
  42542. *
  42543. * @async
  42544. * @deprecated
  42545. * @return {Promise} A Promise that resolves when the clear operation has been executed.
  42546. */
  42547. async clearStencilAsync() {
  42548. warnOnce( 'Renderer: "clearStencilAsync()" has been deprecated. Use "clearStencil()" and "await renderer.init();" when creating the renderer.' ); // @deprecated r181
  42549. this.clear( false, false, true );
  42550. }
  42551. /**
  42552. * Returns `true` if a framebuffer target is needed to perform tone mapping or color space conversion.
  42553. * If this is the case, the renderer allocates an internal render target for that purpose.
  42554. *
  42555. */
  42556. get needsFrameBufferTarget() {
  42557. const useToneMapping = this.currentToneMapping !== NoToneMapping;
  42558. const useColorSpace = this.currentColorSpace !== ColorManagement.workingColorSpace;
  42559. return useToneMapping || useColorSpace;
  42560. }
  42561. /**
  42562. * The number of samples used for multi-sample anti-aliasing (MSAA).
  42563. *
  42564. * @type {number}
  42565. * @default 0
  42566. */
  42567. get samples() {
  42568. return this._samples;
  42569. }
  42570. /**
  42571. * The current number of samples used for multi-sample anti-aliasing (MSAA).
  42572. *
  42573. * When rendering to a custom render target, the number of samples of that render target is used.
  42574. * If the renderer needs an internal framebuffer target for tone mapping or color space conversion,
  42575. * the number of samples is set to 0.
  42576. *
  42577. * @type {number}
  42578. */
  42579. get currentSamples() {
  42580. let samples = this._samples;
  42581. if ( this._renderTarget !== null ) {
  42582. samples = this._renderTarget.samples;
  42583. } else if ( this.needsFrameBufferTarget ) {
  42584. samples = 0;
  42585. }
  42586. return samples;
  42587. }
  42588. /**
  42589. * The current tone mapping of the renderer. When not producing screen output,
  42590. * the tone mapping is always `NoToneMapping`.
  42591. *
  42592. * @type {number}
  42593. */
  42594. get currentToneMapping() {
  42595. return this.isOutputTarget ? this.toneMapping : NoToneMapping;
  42596. }
  42597. /**
  42598. * The current color space of the renderer. When not producing screen output,
  42599. * the color space is always the working color space.
  42600. *
  42601. * @type {string}
  42602. */
  42603. get currentColorSpace() {
  42604. return this.isOutputTarget ? this.outputColorSpace : ColorManagement.workingColorSpace;
  42605. }
  42606. /**
  42607. * Returns `true` if the rendering settings are set to screen output.
  42608. *
  42609. * @returns {boolean} True if the current render target is the same of output render target or `null`, otherwise false.
  42610. */
  42611. get isOutputTarget() {
  42612. return this._renderTarget === this._outputRenderTarget || this._renderTarget === null;
  42613. }
  42614. /**
  42615. * Frees all internal resources of the renderer. Call this method if the renderer
  42616. * is no longer in use by your app.
  42617. */
  42618. dispose() {
  42619. if ( this._initialized === true ) {
  42620. this.info.dispose();
  42621. this.backend.dispose();
  42622. this._animation.dispose();
  42623. this._objects.dispose();
  42624. this._geometries.dispose();
  42625. this._pipelines.dispose();
  42626. this._nodes.dispose();
  42627. this._bindings.dispose();
  42628. this._renderLists.dispose();
  42629. this._renderContexts.dispose();
  42630. this._textures.dispose();
  42631. if ( this._frameBufferTarget !== null ) this._frameBufferTarget.dispose();
  42632. Object.values( this.backend.timestampQueryPool ).forEach( queryPool => {
  42633. if ( queryPool !== null ) queryPool.dispose();
  42634. } );
  42635. }
  42636. this.setRenderTarget( null );
  42637. this.setAnimationLoop( null );
  42638. }
  42639. /**
  42640. * Sets the given render target. Calling this method means the renderer does not
  42641. * target the default framebuffer (meaning the canvas) anymore but a custom framebuffer.
  42642. * Use `null` as the first argument to reset the state.
  42643. *
  42644. * @param {?RenderTarget} renderTarget - The render target to set.
  42645. * @param {number} [activeCubeFace=0] - The active cube face.
  42646. * @param {number} [activeMipmapLevel=0] - The active mipmap level.
  42647. */
  42648. setRenderTarget( renderTarget, activeCubeFace = 0, activeMipmapLevel = 0 ) {
  42649. this._renderTarget = renderTarget;
  42650. this._activeCubeFace = activeCubeFace;
  42651. this._activeMipmapLevel = activeMipmapLevel;
  42652. }
  42653. /**
  42654. * Returns the current render target.
  42655. *
  42656. * @return {?RenderTarget} The render target. Returns `null` if no render target is set.
  42657. */
  42658. getRenderTarget() {
  42659. return this._renderTarget;
  42660. }
  42661. /**
  42662. * Sets the output render target for the renderer.
  42663. *
  42664. * @param {Object} renderTarget - The render target to set as the output target.
  42665. */
  42666. setOutputRenderTarget( renderTarget ) {
  42667. this._outputRenderTarget = renderTarget;
  42668. }
  42669. /**
  42670. * Returns the current output target.
  42671. *
  42672. * @return {?RenderTarget} The current output render target. Returns `null` if no output target is set.
  42673. */
  42674. getOutputRenderTarget() {
  42675. return this._outputRenderTarget;
  42676. }
  42677. /**
  42678. * Sets the canvas target. The canvas target manages the HTML canvas
  42679. * or the offscreen canvas the renderer draws into.
  42680. *
  42681. * @param {CanvasTarget} canvasTarget - The canvas target.
  42682. */
  42683. setCanvasTarget( canvasTarget ) {
  42684. this._canvasTarget.removeEventListener( 'resize', this._onCanvasTargetResize );
  42685. this._canvasTarget = canvasTarget;
  42686. this._canvasTarget.addEventListener( 'resize', this._onCanvasTargetResize );
  42687. }
  42688. /**
  42689. * Returns the current canvas target.
  42690. *
  42691. * @return {CanvasTarget} The current canvas target.
  42692. */
  42693. getCanvasTarget() {
  42694. return this._canvasTarget;
  42695. }
  42696. /**
  42697. * Resets the renderer to the initial state before WebXR started.
  42698. *
  42699. * @private
  42700. */
  42701. _resetXRState() {
  42702. this.backend.setXRTarget( null );
  42703. this.setOutputRenderTarget( null );
  42704. this.setRenderTarget( null );
  42705. this._frameBufferTarget.dispose();
  42706. this._frameBufferTarget = null;
  42707. }
  42708. /**
  42709. * Callback for {@link Renderer#setRenderObjectFunction}.
  42710. *
  42711. * @callback renderObjectFunction
  42712. * @param {Object3D} object - The 3D object.
  42713. * @param {Scene} scene - The scene the 3D object belongs to.
  42714. * @param {Camera} camera - The camera the object should be rendered with.
  42715. * @param {BufferGeometry} geometry - The object's geometry.
  42716. * @param {Material} material - The object's material.
  42717. * @param {?Object} group - Only relevant for objects using multiple materials. This represents a group entry from the respective `BufferGeometry`.
  42718. * @param {LightsNode} lightsNode - The current lights node.
  42719. * @param {ClippingContext} clippingContext - The clipping context.
  42720. * @param {?string} [passId=null] - An optional ID for identifying the pass.
  42721. */
  42722. /**
  42723. * Sets the given render object function. Calling this method overwrites the default implementation
  42724. * which is {@link Renderer#renderObject}. Defining a custom function can be useful
  42725. * if you want to modify the way objects are rendered. For example you can define things like "every
  42726. * object that has material of a certain type should perform a pre-pass with a special overwrite material".
  42727. * The custom function must always call `renderObject()` in its implementation.
  42728. *
  42729. * Use `null` as the first argument to reset the state.
  42730. *
  42731. * @param {?renderObjectFunction} renderObjectFunction - The render object function.
  42732. */
  42733. setRenderObjectFunction( renderObjectFunction ) {
  42734. this._renderObjectFunction = renderObjectFunction;
  42735. }
  42736. /**
  42737. * Returns the current render object function.
  42738. *
  42739. * @return {?Function} The current render object function. Returns `null` if no function is set.
  42740. */
  42741. getRenderObjectFunction() {
  42742. return this._renderObjectFunction;
  42743. }
  42744. /**
  42745. * Execute a single or an array of compute nodes. This method can only be called
  42746. * if the renderer has been initialized.
  42747. *
  42748. * @param {Node|Array<Node>} computeNodes - The compute node(s).
  42749. * @param {number|Array<number>|IndirectStorageBufferAttribute} [dispatchSize=null]
  42750. * - A single number representing count, or
  42751. * - An array [x, y, z] representing dispatch size, or
  42752. * - A IndirectStorageBufferAttribute for indirect dispatch size.
  42753. * @return {Promise|undefined} A Promise that resolve when the compute has finished. Only returned when the renderer has not been initialized.
  42754. */
  42755. compute( computeNodes, dispatchSize = null ) {
  42756. if ( this._isDeviceLost === true ) return;
  42757. if ( this._initialized === false ) {
  42758. warn( 'Renderer: .compute() called before the backend is initialized. Try using .computeAsync() instead.' );
  42759. return this.computeAsync( computeNodes, dispatchSize );
  42760. }
  42761. //
  42762. const nodeFrame = this._nodes.nodeFrame;
  42763. const previousRenderId = nodeFrame.renderId;
  42764. //
  42765. this.info.calls ++;
  42766. this.info.compute.calls ++;
  42767. this.info.compute.frameCalls ++;
  42768. nodeFrame.renderId = this.info.calls;
  42769. //
  42770. this.backend.updateTimeStampUID( computeNodes );
  42771. this.inspector.beginCompute( this.backend.getTimestampUID( computeNodes ), computeNodes );
  42772. //
  42773. const backend = this.backend;
  42774. const pipelines = this._pipelines;
  42775. const bindings = this._bindings;
  42776. const nodes = this._nodes;
  42777. const computeList = Array.isArray( computeNodes ) ? computeNodes : [ computeNodes ];
  42778. if ( computeList[ 0 ] === undefined || computeList[ 0 ].isComputeNode !== true ) {
  42779. throw new Error( 'THREE.Renderer: .compute() expects a ComputeNode.' );
  42780. }
  42781. backend.beginCompute( computeNodes );
  42782. for ( const computeNode of computeList ) {
  42783. // onInit
  42784. if ( pipelines.has( computeNode ) === false ) {
  42785. const dispose = () => {
  42786. computeNode.removeEventListener( 'dispose', dispose );
  42787. pipelines.delete( computeNode );
  42788. bindings.deleteForCompute( computeNode );
  42789. nodes.delete( computeNode );
  42790. };
  42791. computeNode.addEventListener( 'dispose', dispose );
  42792. //
  42793. const onInitFn = computeNode.onInitFunction;
  42794. if ( onInitFn !== null ) {
  42795. onInitFn.call( computeNode, { renderer: this } );
  42796. }
  42797. }
  42798. nodes.updateForCompute( computeNode );
  42799. bindings.updateForCompute( computeNode );
  42800. const computeBindings = bindings.getForCompute( computeNode );
  42801. const computePipeline = pipelines.getForCompute( computeNode, computeBindings );
  42802. backend.compute( computeNodes, computeNode, computeBindings, computePipeline, dispatchSize );
  42803. }
  42804. backend.finishCompute( computeNodes );
  42805. //
  42806. nodeFrame.renderId = previousRenderId;
  42807. //
  42808. this.inspector.finishCompute( this.backend.getTimestampUID( computeNodes ) );
  42809. }
  42810. /**
  42811. * Execute a single or an array of compute nodes.
  42812. *
  42813. * @async
  42814. * @param {Node|Array<Node>} computeNodes - The compute node(s).
  42815. * @param {number|Array<number>|IndirectStorageBufferAttribute} [dispatchSize=null]
  42816. * - A single number representing count, or
  42817. * - An array [x, y, z] representing dispatch size, or
  42818. * - A IndirectStorageBufferAttribute for indirect dispatch size.
  42819. * @return {Promise} A Promise that resolve when the compute has finished.
  42820. */
  42821. async computeAsync( computeNodes, dispatchSize = null ) {
  42822. if ( this._initialized === false ) await this.init();
  42823. this.compute( computeNodes, dispatchSize );
  42824. }
  42825. /**
  42826. * Checks if the given feature is supported by the selected backend.
  42827. *
  42828. * @async
  42829. * @deprecated
  42830. * @param {string} name - The feature's name.
  42831. * @return {Promise<boolean>} A Promise that resolves with a bool that indicates whether the feature is supported or not.
  42832. */
  42833. async hasFeatureAsync( name ) {
  42834. warnOnce( 'Renderer: "hasFeatureAsync()" has been deprecated. Use "hasFeature()" and "await renderer.init();" when creating the renderer.' ); // @deprecated r181
  42835. await this.init();
  42836. return this.hasFeature( name );
  42837. }
  42838. async resolveTimestampsAsync( type = 'render' ) {
  42839. if ( this._initialized === false ) await this.init();
  42840. return this.backend.resolveTimestampsAsync( type );
  42841. }
  42842. /**
  42843. * Checks if the given feature is supported by the selected backend. If the
  42844. * renderer has not been initialized, this method always returns `false`.
  42845. *
  42846. * @param {string} name - The feature's name.
  42847. * @return {boolean} Whether the feature is supported or not.
  42848. */
  42849. hasFeature( name ) {
  42850. if ( this._initialized === false ) {
  42851. throw new Error( 'Renderer: .hasFeature() called before the backend is initialized. Use "await renderer.init();" before before using this method.' );
  42852. }
  42853. return this.backend.hasFeature( name );
  42854. }
  42855. /**
  42856. * Returns `true` when the renderer has been initialized.
  42857. *
  42858. * @return {boolean} Whether the renderer has been initialized or not.
  42859. */
  42860. hasInitialized() {
  42861. return this._initialized;
  42862. }
  42863. /**
  42864. * Initializes the given textures. Useful for preloading a texture rather than waiting until first render
  42865. * (which can cause noticeable lags due to decode and GPU upload overhead).
  42866. *
  42867. * @async
  42868. * @deprecated
  42869. * @param {Texture} texture - The texture.
  42870. * @return {Promise} A Promise that resolves when the texture has been initialized.
  42871. */
  42872. async initTextureAsync( texture ) {
  42873. warnOnce( 'Renderer: "initTextureAsync()" has been deprecated. Use "initTexture()" and "await renderer.init();" when creating the renderer.' ); // @deprecated r181
  42874. await this.init();
  42875. this.initTexture( texture );
  42876. }
  42877. /**
  42878. * Initializes the given texture. Useful for preloading a texture rather than waiting until first render
  42879. * (which can cause noticeable lags due to decode and GPU upload overhead).
  42880. *
  42881. * This method can only be used if the renderer has been initialized.
  42882. *
  42883. * @param {Texture} texture - The texture.
  42884. */
  42885. initTexture( texture ) {
  42886. if ( this._initialized === false ) {
  42887. throw new Error( 'Renderer: .initTexture() called before the backend is initialized. Use "await renderer.init();" before before using this method.' );
  42888. }
  42889. this._textures.updateTexture( texture );
  42890. }
  42891. /**
  42892. * Copies the current bound framebuffer into the given texture.
  42893. *
  42894. * @param {FramebufferTexture} framebufferTexture - The texture.
  42895. * @param {?(Vector2|Vector4)} [rectangle=null] - A two or four dimensional vector that defines the rectangular portion of the framebuffer that should be copied.
  42896. */
  42897. copyFramebufferToTexture( framebufferTexture, rectangle = null ) {
  42898. if ( rectangle !== null ) {
  42899. if ( rectangle.isVector2 ) {
  42900. rectangle = _vector4.set( rectangle.x, rectangle.y, framebufferTexture.image.width, framebufferTexture.image.height ).floor();
  42901. } else if ( rectangle.isVector4 ) {
  42902. rectangle = _vector4.copy( rectangle ).floor();
  42903. } else {
  42904. error( 'Renderer.copyFramebufferToTexture: Invalid rectangle.' );
  42905. return;
  42906. }
  42907. } else {
  42908. rectangle = _vector4.set( 0, 0, framebufferTexture.image.width, framebufferTexture.image.height );
  42909. }
  42910. //
  42911. let renderContext = this._currentRenderContext;
  42912. let renderTarget;
  42913. if ( renderContext !== null ) {
  42914. renderTarget = renderContext.renderTarget;
  42915. } else {
  42916. renderTarget = this._renderTarget || this._getFrameBufferTarget();
  42917. if ( renderTarget !== null ) {
  42918. this._textures.updateRenderTarget( renderTarget );
  42919. renderContext = this._textures.get( renderTarget );
  42920. }
  42921. }
  42922. //
  42923. this._textures.updateTexture( framebufferTexture, { renderTarget } );
  42924. this.backend.copyFramebufferToTexture( framebufferTexture, renderContext, rectangle );
  42925. this._inspector.copyFramebufferToTexture( framebufferTexture );
  42926. }
  42927. /**
  42928. * Copies data of the given source texture into a destination texture.
  42929. *
  42930. * @param {Texture} srcTexture - The source texture.
  42931. * @param {Texture} dstTexture - The destination texture.
  42932. * @param {Box2|Box3} [srcRegion=null] - A bounding box which describes the source region. Can be two or three-dimensional.
  42933. * @param {Vector2|Vector3} [dstPosition=null] - A vector that represents the origin of the destination region. Can be two or three-dimensional.
  42934. * @param {number} [srcLevel=0] - The source mip level to copy from.
  42935. * @param {number} [dstLevel=0] - The destination mip level to copy to.
  42936. */
  42937. copyTextureToTexture( srcTexture, dstTexture, srcRegion = null, dstPosition = null, srcLevel = 0, dstLevel = 0 ) {
  42938. this._textures.updateTexture( srcTexture );
  42939. this._textures.updateTexture( dstTexture );
  42940. this.backend.copyTextureToTexture( srcTexture, dstTexture, srcRegion, dstPosition, srcLevel, dstLevel );
  42941. this._inspector.copyTextureToTexture( srcTexture, dstTexture );
  42942. }
  42943. /**
  42944. * Reads pixel data from the given render target.
  42945. *
  42946. * @async
  42947. * @param {RenderTarget} renderTarget - The render target to read from.
  42948. * @param {number} x - The `x` coordinate of the copy region's origin.
  42949. * @param {number} y - The `y` coordinate of the copy region's origin.
  42950. * @param {number} width - The width of the copy region.
  42951. * @param {number} height - The height of the copy region.
  42952. * @param {number} [textureIndex=0] - The texture index of a MRT render target.
  42953. * @param {number} [faceIndex=0] - The active cube face index.
  42954. * @return {Promise<TypedArray>} A Promise that resolves when the read has been finished. The resolve provides the read data as a typed array.
  42955. */
  42956. async readRenderTargetPixelsAsync( renderTarget, x, y, width, height, textureIndex = 0, faceIndex = 0 ) {
  42957. return this.backend.copyTextureToBuffer( renderTarget.textures[ textureIndex ], x, y, width, height, faceIndex );
  42958. }
  42959. /**
  42960. * Analyzes the given 3D object's hierarchy and builds render lists from the
  42961. * processed hierarchy.
  42962. *
  42963. * @private
  42964. * @param {Object3D} object - The 3D object to process (usually a scene).
  42965. * @param {Camera} camera - The camera the object is rendered with.
  42966. * @param {number} groupOrder - The group order is derived from the `renderOrder` of groups and is used to group 3D objects within groups.
  42967. * @param {RenderList} renderList - The current render list.
  42968. * @param {ClippingContext} clippingContext - The current clipping context.
  42969. */
  42970. _projectObject( object, camera, groupOrder, renderList, clippingContext ) {
  42971. if ( object.visible === false ) return;
  42972. const visible = object.layers.test( camera.layers );
  42973. if ( visible ) {
  42974. if ( object.isGroup ) {
  42975. groupOrder = object.renderOrder;
  42976. if ( object.isClippingGroup && object.enabled ) clippingContext = clippingContext.getGroupContext( object );
  42977. } else if ( object.isLOD ) {
  42978. if ( object.autoUpdate === true ) object.update( camera );
  42979. } else if ( object.isLight ) {
  42980. renderList.pushLight( object );
  42981. } else if ( object.isSprite ) {
  42982. const frustum = camera.isArrayCamera ? _frustumArray : _frustum;
  42983. if ( ! object.frustumCulled || frustum.intersectsSprite( object, camera ) ) {
  42984. if ( this.sortObjects === true ) {
  42985. _vector4.setFromMatrixPosition( object.matrixWorld ).applyMatrix4( _projScreenMatrix );
  42986. }
  42987. const { geometry, material } = object;
  42988. if ( material.visible ) {
  42989. renderList.push( object, geometry, material, groupOrder, _vector4.z, null, clippingContext );
  42990. }
  42991. }
  42992. } else if ( object.isLineLoop ) {
  42993. error( 'Renderer: Objects of type THREE.LineLoop are not supported. Please use THREE.Line or THREE.LineSegments.' );
  42994. } else if ( object.isMesh || object.isLine || object.isPoints ) {
  42995. const frustum = camera.isArrayCamera ? _frustumArray : _frustum;
  42996. if ( ! object.frustumCulled || frustum.intersectsObject( object, camera ) ) {
  42997. const { geometry, material } = object;
  42998. if ( this.sortObjects === true ) {
  42999. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  43000. _vector4
  43001. .copy( geometry.boundingSphere.center )
  43002. .applyMatrix4( object.matrixWorld )
  43003. .applyMatrix4( _projScreenMatrix );
  43004. }
  43005. if ( Array.isArray( material ) ) {
  43006. const groups = geometry.groups;
  43007. for ( let i = 0, l = groups.length; i < l; i ++ ) {
  43008. const group = groups[ i ];
  43009. const groupMaterial = material[ group.materialIndex ];
  43010. if ( groupMaterial && groupMaterial.visible ) {
  43011. renderList.push( object, geometry, groupMaterial, groupOrder, _vector4.z, group, clippingContext );
  43012. }
  43013. }
  43014. } else if ( material.visible ) {
  43015. renderList.push( object, geometry, material, groupOrder, _vector4.z, null, clippingContext );
  43016. }
  43017. }
  43018. }
  43019. }
  43020. if ( object.isBundleGroup === true && this.backend.beginBundle !== undefined ) {
  43021. const baseRenderList = renderList;
  43022. // replace render list
  43023. renderList = this._renderLists.get( object, camera );
  43024. renderList.begin();
  43025. baseRenderList.pushBundle( {
  43026. bundleGroup: object,
  43027. camera,
  43028. renderList,
  43029. } );
  43030. renderList.finish();
  43031. }
  43032. const children = object.children;
  43033. for ( let i = 0, l = children.length; i < l; i ++ ) {
  43034. this._projectObject( children[ i ], camera, groupOrder, renderList, clippingContext );
  43035. }
  43036. }
  43037. /**
  43038. * Renders the given render bundles.
  43039. *
  43040. * @private
  43041. * @param {Array<Object>} bundles - Array with render bundle data.
  43042. * @param {Scene} sceneRef - The scene the render bundles belong to.
  43043. * @param {LightsNode} lightsNode - The current lights node.
  43044. */
  43045. _renderBundles( bundles, sceneRef, lightsNode ) {
  43046. for ( const bundle of bundles ) {
  43047. this._renderBundle( bundle, sceneRef, lightsNode );
  43048. }
  43049. }
  43050. /**
  43051. * Renders the transparent objects from the given render lists.
  43052. *
  43053. * @private
  43054. * @param {Array<Object>} renderList - The transparent render list.
  43055. * @param {Array<Object>} doublePassList - The list of transparent objects which require a double pass (e.g. because of transmission).
  43056. * @param {Camera} camera - The camera the render list should be rendered with.
  43057. * @param {Scene} scene - The scene the render list belongs to.
  43058. * @param {LightsNode} lightsNode - The current lights node.
  43059. */
  43060. _renderTransparents( renderList, doublePassList, camera, scene, lightsNode ) {
  43061. if ( doublePassList.length > 0 ) {
  43062. // render back side
  43063. for ( const { material } of doublePassList ) {
  43064. material.side = BackSide;
  43065. }
  43066. this._renderObjects( doublePassList, camera, scene, lightsNode, 'backSide' );
  43067. // render front side
  43068. for ( const { material } of doublePassList ) {
  43069. material.side = FrontSide;
  43070. }
  43071. this._renderObjects( renderList, camera, scene, lightsNode );
  43072. // restore
  43073. for ( const { material } of doublePassList ) {
  43074. material.side = DoubleSide;
  43075. }
  43076. } else {
  43077. this._renderObjects( renderList, camera, scene, lightsNode );
  43078. }
  43079. }
  43080. /**
  43081. * Renders the objects from the given render list.
  43082. *
  43083. * @private
  43084. * @param {Array<Object>} renderList - The render list.
  43085. * @param {Camera} camera - The camera the render list should be rendered with.
  43086. * @param {Scene} scene - The scene the render list belongs to.
  43087. * @param {LightsNode} lightsNode - The current lights node.
  43088. * @param {?string} [passId=null] - An optional ID for identifying the pass.
  43089. */
  43090. _renderObjects( renderList, camera, scene, lightsNode, passId = null ) {
  43091. for ( let i = 0, il = renderList.length; i < il; i ++ ) {
  43092. const { object, geometry, material, group, clippingContext } = renderList[ i ];
  43093. this._currentRenderObjectFunction( object, scene, camera, geometry, material, group, lightsNode, clippingContext, passId );
  43094. }
  43095. }
  43096. /**
  43097. * Retrieves shadow nodes for the given material. This is used to setup shadow passes.
  43098. * The result is cached per material and updated when the material's version changes.
  43099. *
  43100. * @private
  43101. * @param {Material} material
  43102. * @returns {Object} - The shadow nodes for the material.
  43103. */
  43104. _getShadowNodes( material ) {
  43105. const version = material.version;
  43106. let cache = this._cacheShadowNodes.get( material );
  43107. if ( cache === undefined || cache.version !== version ) {
  43108. const hasMap = material.map !== null;
  43109. const hasColorNode = material.colorNode && material.colorNode.isNode;
  43110. const hasCastShadowNode = material.castShadowNode && material.castShadowNode.isNode;
  43111. let positionNode = null;
  43112. let colorNode = null;
  43113. let depthNode = null;
  43114. if ( hasMap || hasColorNode || hasCastShadowNode ) {
  43115. let shadowRGB;
  43116. let shadowAlpha;
  43117. if ( hasCastShadowNode ) {
  43118. shadowRGB = material.castShadowNode.rgb;
  43119. shadowAlpha = material.castShadowNode.a;
  43120. } else {
  43121. shadowRGB = vec3( 0 );
  43122. shadowAlpha = float( 1 );
  43123. }
  43124. if ( hasMap ) {
  43125. shadowAlpha = shadowAlpha.mul( reference( 'map', 'texture', material ).a );
  43126. }
  43127. if ( hasColorNode ) {
  43128. shadowAlpha = shadowAlpha.mul( material.colorNode.a );
  43129. }
  43130. colorNode = vec4( shadowRGB, shadowAlpha );
  43131. }
  43132. if ( material.depthNode && material.depthNode.isNode ) {
  43133. depthNode = material.depthNode;
  43134. }
  43135. if ( material.castShadowPositionNode && material.castShadowPositionNode.isNode ) {
  43136. positionNode = material.castShadowPositionNode;
  43137. } else if ( material.positionNode && material.positionNode.isNode ) {
  43138. positionNode = material.positionNode;
  43139. }
  43140. cache = {
  43141. version,
  43142. colorNode,
  43143. depthNode,
  43144. positionNode
  43145. };
  43146. this._cacheShadowNodes.set( material, cache );
  43147. }
  43148. return cache;
  43149. }
  43150. /**
  43151. * This method represents the default render object function that manages the render lifecycle
  43152. * of the object.
  43153. *
  43154. * @param {Object3D} object - The 3D object.
  43155. * @param {Scene} scene - The scene the 3D object belongs to.
  43156. * @param {Camera} camera - The camera the object should be rendered with.
  43157. * @param {BufferGeometry} geometry - The object's geometry.
  43158. * @param {Material} material - The object's material.
  43159. * @param {?Object} group - Only relevant for objects using multiple materials. This represents a group entry from the respective `BufferGeometry`.
  43160. * @param {LightsNode} lightsNode - The current lights node.
  43161. * @param {?ClippingContext} clippingContext - The clipping context.
  43162. * @param {?string} [passId=null] - An optional ID for identifying the pass.
  43163. */
  43164. renderObject( object, scene, camera, geometry, material, group, lightsNode, clippingContext = null, passId = null ) {
  43165. let materialOverride = false;
  43166. let materialColorNode;
  43167. let materialDepthNode;
  43168. let materialPositionNode;
  43169. let materialSide;
  43170. //
  43171. object.onBeforeRender( this, scene, camera, geometry, material, group );
  43172. //
  43173. if ( material.allowOverride === true && scene.overrideMaterial !== null ) {
  43174. const overrideMaterial = scene.overrideMaterial;
  43175. materialOverride = true;
  43176. // store original nodes
  43177. materialColorNode = scene.overrideMaterial.colorNode;
  43178. materialDepthNode = scene.overrideMaterial.depthNode;
  43179. materialPositionNode = scene.overrideMaterial.positionNode;
  43180. materialSide = scene.overrideMaterial.side;
  43181. if ( material.positionNode && material.positionNode.isNode ) {
  43182. overrideMaterial.positionNode = material.positionNode;
  43183. }
  43184. overrideMaterial.alphaTest = material.alphaTest;
  43185. overrideMaterial.alphaMap = material.alphaMap;
  43186. overrideMaterial.transparent = material.transparent || material.transmission > 0 ||
  43187. ( material.transmissionNode && material.transmissionNode.isNode ) ||
  43188. ( material.backdropNode && material.backdropNode.isNode );
  43189. if ( overrideMaterial.isShadowPassMaterial ) {
  43190. const { colorNode, depthNode, positionNode } = this._getShadowNodes( material );
  43191. overrideMaterial.side = material.shadowSide === null ? material.side : material.shadowSide;
  43192. if ( colorNode !== null ) overrideMaterial.colorNode = colorNode;
  43193. if ( depthNode !== null ) overrideMaterial.depthNode = depthNode;
  43194. if ( positionNode !== null ) overrideMaterial.positionNode = positionNode;
  43195. }
  43196. material = overrideMaterial;
  43197. }
  43198. //
  43199. if ( material.transparent === true && material.side === DoubleSide && material.forceSinglePass === false ) {
  43200. material.side = BackSide;
  43201. this._handleObjectFunction( object, material, scene, camera, lightsNode, group, clippingContext, 'backSide' ); // create backSide pass id
  43202. material.side = FrontSide;
  43203. this._handleObjectFunction( object, material, scene, camera, lightsNode, group, clippingContext, passId ); // use default pass id
  43204. material.side = DoubleSide;
  43205. } else {
  43206. this._handleObjectFunction( object, material, scene, camera, lightsNode, group, clippingContext, passId );
  43207. }
  43208. //
  43209. if ( materialOverride ) {
  43210. scene.overrideMaterial.colorNode = materialColorNode;
  43211. scene.overrideMaterial.depthNode = materialDepthNode;
  43212. scene.overrideMaterial.positionNode = materialPositionNode;
  43213. scene.overrideMaterial.side = materialSide;
  43214. }
  43215. //
  43216. object.onAfterRender( this, scene, camera, geometry, material, group );
  43217. }
  43218. /**
  43219. * This method represents the default `_handleObjectFunction` implementation which creates
  43220. * a render object from the given data and performs the draw command with the selected backend.
  43221. *
  43222. * @private
  43223. * @param {Object3D} object - The 3D object.
  43224. * @param {Material} material - The object's material.
  43225. * @param {Scene} scene - The scene the 3D object belongs to.
  43226. * @param {Camera} camera - The camera the object should be rendered with.
  43227. * @param {LightsNode} lightsNode - The current lights node.
  43228. * @param {?{start: number, count: number}} group - Only relevant for objects using multiple materials. This represents a group entry from the respective `BufferGeometry`.
  43229. * @param {ClippingContext} clippingContext - The clipping context.
  43230. * @param {string} [passId] - An optional ID for identifying the pass.
  43231. */
  43232. _renderObjectDirect( object, material, scene, camera, lightsNode, group, clippingContext, passId ) {
  43233. const renderObject = this._objects.get( object, material, scene, camera, lightsNode, this._currentRenderContext, clippingContext, passId );
  43234. renderObject.drawRange = object.geometry.drawRange;
  43235. renderObject.group = group;
  43236. //
  43237. const needsRefresh = this._nodes.needsRefresh( renderObject );
  43238. if ( needsRefresh ) {
  43239. this._nodes.updateBefore( renderObject );
  43240. this._geometries.updateForRender( renderObject );
  43241. this._nodes.updateForRender( renderObject );
  43242. this._bindings.updateForRender( renderObject );
  43243. }
  43244. this._pipelines.updateForRender( renderObject );
  43245. //
  43246. if ( this._currentRenderBundle !== null ) {
  43247. const renderBundleData = this.backend.get( this._currentRenderBundle );
  43248. renderBundleData.renderObjects.push( renderObject );
  43249. renderObject.bundle = this._currentRenderBundle.bundleGroup;
  43250. }
  43251. this.backend.draw( renderObject, this.info );
  43252. if ( needsRefresh ) this._nodes.updateAfter( renderObject );
  43253. }
  43254. /**
  43255. * A different implementation for `_handleObjectFunction` which only makes sure the object is ready for rendering.
  43256. * Used in `compileAsync()`.
  43257. *
  43258. * @private
  43259. * @param {Object3D} object - The 3D object.
  43260. * @param {Material} material - The object's material.
  43261. * @param {Scene} scene - The scene the 3D object belongs to.
  43262. * @param {Camera} camera - The camera the object should be rendered with.
  43263. * @param {LightsNode} lightsNode - The current lights node.
  43264. * @param {?{start: number, count: number}} group - Only relevant for objects using multiple materials. This represents a group entry from the respective `BufferGeometry`.
  43265. * @param {ClippingContext} clippingContext - The clipping context.
  43266. * @param {string} [passId] - An optional ID for identifying the pass.
  43267. */
  43268. _createObjectPipeline( object, material, scene, camera, lightsNode, group, clippingContext, passId ) {
  43269. const renderObject = this._objects.get( object, material, scene, camera, lightsNode, this._currentRenderContext, clippingContext, passId );
  43270. renderObject.drawRange = object.geometry.drawRange;
  43271. renderObject.group = group;
  43272. //
  43273. this._nodes.updateBefore( renderObject );
  43274. this._geometries.updateForRender( renderObject );
  43275. this._nodes.updateForRender( renderObject );
  43276. this._bindings.updateForRender( renderObject );
  43277. this._pipelines.getForRender( renderObject, this._compilationPromises );
  43278. this._nodes.updateAfter( renderObject );
  43279. }
  43280. /**
  43281. * Callback when the canvas has been resized.
  43282. *
  43283. * @private
  43284. */
  43285. _onCanvasTargetResize() {
  43286. if ( this._initialized ) this.backend.updateSize();
  43287. }
  43288. /**
  43289. * Alias for `compileAsync()`.
  43290. *
  43291. * @method
  43292. * @param {Object3D} scene - The scene or 3D object to precompile.
  43293. * @param {Camera} camera - The camera that is used to render the scene.
  43294. * @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.
  43295. * @return {function(Object3D, Camera, ?Scene): Promise|undefined} A Promise that resolves when the compile has been finished.
  43296. */
  43297. get compile() {
  43298. return this.compileAsync;
  43299. }
  43300. }
  43301. /**
  43302. * A binding represents the connection between a resource (like a texture, sampler
  43303. * or uniform buffer) and the resource definition in a shader stage.
  43304. *
  43305. * This module is an abstract base class for all concrete bindings types.
  43306. *
  43307. * @abstract
  43308. * @private
  43309. */
  43310. class Binding {
  43311. /**
  43312. * Constructs a new binding.
  43313. *
  43314. * @param {string} [name=''] - The binding's name.
  43315. */
  43316. constructor( name = '' ) {
  43317. /**
  43318. * The binding's name.
  43319. *
  43320. * @type {string}
  43321. */
  43322. this.name = name;
  43323. /**
  43324. * A bitmask that defines in what shader stages the
  43325. * binding's resource is accessible.
  43326. *
  43327. * @type {number}
  43328. */
  43329. this.visibility = 0;
  43330. }
  43331. /**
  43332. * Makes sure binding's resource is visible for the given shader stage.
  43333. *
  43334. * @param {number} visibility - The shader stage.
  43335. */
  43336. setVisibility( visibility ) {
  43337. this.visibility |= visibility;
  43338. }
  43339. /**
  43340. * The shader stages in which the binding's resource is visible.
  43341. *
  43342. * @return {number} The visibility bitmask.
  43343. */
  43344. getVisibility() {
  43345. return this.visibility;
  43346. }
  43347. /**
  43348. * Clones the binding.
  43349. *
  43350. * @return {Binding} The cloned binding.
  43351. */
  43352. clone() {
  43353. return Object.assign( new this.constructor(), this );
  43354. }
  43355. }
  43356. /**
  43357. * This function is usually called with the length in bytes of an array buffer.
  43358. * It returns an padded value which ensure chunk size alignment according to STD140 layout.
  43359. *
  43360. * @function
  43361. * @param {number} floatLength - The buffer length.
  43362. * @return {number} The padded length.
  43363. */
  43364. function getFloatLength( floatLength ) {
  43365. // ensure chunk size alignment (STD140 layout)
  43366. return floatLength + ( ( GPU_CHUNK_BYTES - ( floatLength % GPU_CHUNK_BYTES ) ) % GPU_CHUNK_BYTES );
  43367. }
  43368. /**
  43369. * Represents a buffer binding type.
  43370. *
  43371. * @private
  43372. * @abstract
  43373. * @augments Binding
  43374. */
  43375. class Buffer extends Binding {
  43376. /**
  43377. * Constructs a new buffer.
  43378. *
  43379. * @param {string} name - The buffer's name.
  43380. * @param {TypedArray} [buffer=null] - The buffer.
  43381. */
  43382. constructor( name, buffer = null ) {
  43383. super( name );
  43384. /**
  43385. * This flag can be used for type testing.
  43386. *
  43387. * @type {boolean}
  43388. * @readonly
  43389. * @default true
  43390. */
  43391. this.isBuffer = true;
  43392. /**
  43393. * The bytes per element.
  43394. *
  43395. * @type {number}
  43396. */
  43397. this.bytesPerElement = Float32Array.BYTES_PER_ELEMENT;
  43398. /**
  43399. * A reference to the internal buffer.
  43400. *
  43401. * @private
  43402. * @type {TypedArray}
  43403. */
  43404. this._buffer = buffer;
  43405. /**
  43406. * An array of update ranges.
  43407. *
  43408. * @private
  43409. * @type {Array<{start: number, count: number}>}
  43410. */
  43411. this._updateRanges = [];
  43412. }
  43413. /**
  43414. * The array of update ranges.
  43415. *
  43416. * @type {Array<{start: number, count: number}>}
  43417. */
  43418. get updateRanges() {
  43419. return this._updateRanges;
  43420. }
  43421. /**
  43422. * Adds an update range.
  43423. *
  43424. * @param {number} start - The start index.
  43425. * @param {number} count - The number of elements.
  43426. */
  43427. addUpdateRange( start, count ) {
  43428. this.updateRanges.push( { start, count } );
  43429. }
  43430. /**
  43431. * Clears all update ranges.
  43432. */
  43433. clearUpdateRanges() {
  43434. this.updateRanges.length = 0;
  43435. }
  43436. /**
  43437. * The buffer's byte length.
  43438. *
  43439. * @type {number}
  43440. * @readonly
  43441. */
  43442. get byteLength() {
  43443. return getFloatLength( this._buffer.byteLength );
  43444. }
  43445. /**
  43446. * A reference to the internal buffer.
  43447. *
  43448. * @type {Float32Array}
  43449. * @readonly
  43450. */
  43451. get buffer() {
  43452. return this._buffer;
  43453. }
  43454. /**
  43455. * Updates the binding.
  43456. *
  43457. * @return {boolean} Whether the buffer has been updated and must be
  43458. * uploaded to the GPU.
  43459. */
  43460. update() {
  43461. return true;
  43462. }
  43463. }
  43464. /**
  43465. * Represents a uniform buffer binding type.
  43466. *
  43467. * @private
  43468. * @augments Buffer
  43469. */
  43470. class UniformBuffer extends Buffer {
  43471. /**
  43472. * Constructs a new uniform buffer.
  43473. *
  43474. * @param {string} name - The buffer's name.
  43475. * @param {TypedArray} [buffer=null] - The buffer.
  43476. */
  43477. constructor( name, buffer = null ) {
  43478. super( name, buffer );
  43479. /**
  43480. * This flag can be used for type testing.
  43481. *
  43482. * @type {boolean}
  43483. * @readonly
  43484. * @default true
  43485. */
  43486. this.isUniformBuffer = true;
  43487. }
  43488. }
  43489. let _id$4 = 0;
  43490. /**
  43491. * A special form of uniform buffer binding type.
  43492. * It's buffer value is managed by a node object.
  43493. *
  43494. * @private
  43495. * @augments UniformBuffer
  43496. */
  43497. class NodeUniformBuffer extends UniformBuffer {
  43498. /**
  43499. * Constructs a new node-based uniform buffer.
  43500. *
  43501. * @param {BufferNode} nodeUniform - The uniform buffer node.
  43502. * @param {UniformGroupNode} groupNode - The uniform group node.
  43503. */
  43504. constructor( nodeUniform, groupNode ) {
  43505. super( 'UniformBuffer_' + _id$4 ++, nodeUniform ? nodeUniform.value : null );
  43506. /**
  43507. * The uniform buffer node.
  43508. *
  43509. * @type {BufferNode}
  43510. */
  43511. this.nodeUniform = nodeUniform;
  43512. /**
  43513. * The uniform group node.
  43514. *
  43515. * @type {UniformGroupNode}
  43516. */
  43517. this.groupNode = groupNode;
  43518. /**
  43519. * This flag can be used for type testing.
  43520. *
  43521. * @type {boolean}
  43522. * @readonly
  43523. * @default true
  43524. */
  43525. this.isNodeUniformBuffer = true;
  43526. }
  43527. /**
  43528. * The array of update ranges.
  43529. *
  43530. * @param {Array<{start: number, count: number}>} value - The update ranges.
  43531. */
  43532. set updateRanges( value ) {
  43533. this.nodeUniform.updateRanges = value;
  43534. }
  43535. /**
  43536. * The array of update ranges.
  43537. *
  43538. * @type {Array<{start: number, count: number}>}
  43539. */
  43540. get updateRanges() {
  43541. return this.nodeUniform.updateRanges;
  43542. }
  43543. /**
  43544. * Adds a range of data in the data array to be updated on the GPU.
  43545. *
  43546. * @param {number} start - Position at which to start update.
  43547. * @param {number} count - The number of components to update.
  43548. */
  43549. addUpdateRange( start, count ) {
  43550. this.nodeUniform.addUpdateRange( start, count );
  43551. }
  43552. /**
  43553. * Clears all update ranges.
  43554. */
  43555. clearUpdateRanges() {
  43556. this.nodeUniform.clearUpdateRanges();
  43557. }
  43558. /**
  43559. * The uniform buffer.
  43560. *
  43561. * @type {Float32Array}
  43562. */
  43563. get buffer() {
  43564. return this.nodeUniform.value;
  43565. }
  43566. }
  43567. /**
  43568. * This class represents a uniform buffer binding but with
  43569. * an API that allows to maintain individual uniform objects.
  43570. *
  43571. * @private
  43572. * @augments UniformBuffer
  43573. */
  43574. class UniformsGroup extends UniformBuffer {
  43575. /**
  43576. * Constructs a new uniforms group.
  43577. *
  43578. * @param {string} name - The group's name.
  43579. */
  43580. constructor( name ) {
  43581. super( name );
  43582. /**
  43583. * This flag can be used for type testing.
  43584. *
  43585. * @type {boolean}
  43586. * @readonly
  43587. * @default true
  43588. */
  43589. this.isUniformsGroup = true;
  43590. /**
  43591. * An array with the raw uniform values.
  43592. *
  43593. * @private
  43594. * @type {?Array<number>}
  43595. * @default null
  43596. */
  43597. this._values = null;
  43598. /**
  43599. * An array of uniform objects.
  43600. *
  43601. * The order of uniforms in this array must match the order of uniforms in the shader.
  43602. *
  43603. * @type {Array<Uniform>}
  43604. */
  43605. this.uniforms = [];
  43606. }
  43607. /**
  43608. * Adds a uniform to this group.
  43609. *
  43610. * @param {Uniform} uniform - The uniform to add.
  43611. * @return {UniformsGroup} A reference to this group.
  43612. */
  43613. addUniform( uniform ) {
  43614. this.uniforms.push( uniform );
  43615. return this;
  43616. }
  43617. /**
  43618. * Removes a uniform from this group.
  43619. *
  43620. * @param {Uniform} uniform - The uniform to remove.
  43621. * @return {UniformsGroup} A reference to this group.
  43622. */
  43623. removeUniform( uniform ) {
  43624. const index = this.uniforms.indexOf( uniform );
  43625. if ( index !== -1 ) {
  43626. this.uniforms.splice( index, 1 );
  43627. }
  43628. return this;
  43629. }
  43630. /**
  43631. * An array with the raw uniform values.
  43632. *
  43633. * @type {Array<number>}
  43634. */
  43635. get values() {
  43636. if ( this._values === null ) {
  43637. this._values = Array.from( this.buffer );
  43638. }
  43639. return this._values;
  43640. }
  43641. /**
  43642. * A Float32 array buffer with the uniform values.
  43643. *
  43644. * @type {Float32Array}
  43645. */
  43646. get buffer() {
  43647. let buffer = this._buffer;
  43648. if ( buffer === null ) {
  43649. const byteLength = this.byteLength;
  43650. buffer = new Float32Array( new ArrayBuffer( byteLength ) );
  43651. this._buffer = buffer;
  43652. }
  43653. return buffer;
  43654. }
  43655. /**
  43656. * The byte length of the buffer with correct buffer alignment.
  43657. *
  43658. * @type {number}
  43659. */
  43660. get byteLength() {
  43661. const bytesPerElement = this.bytesPerElement;
  43662. let offset = 0; // global buffer offset in bytes
  43663. for ( let i = 0, l = this.uniforms.length; i < l; i ++ ) {
  43664. const uniform = this.uniforms[ i ];
  43665. const boundary = uniform.boundary;
  43666. const itemSize = uniform.itemSize * bytesPerElement; // size of the uniform in bytes
  43667. const chunkOffset = offset % GPU_CHUNK_BYTES; // offset in the current chunk
  43668. const chunkPadding = chunkOffset % boundary; // required padding to match boundary
  43669. const chunkStart = chunkOffset + chunkPadding; // start position in the current chunk for the data
  43670. offset += chunkPadding;
  43671. // Check for chunk overflow
  43672. if ( chunkStart !== 0 && ( GPU_CHUNK_BYTES - chunkStart ) < itemSize ) {
  43673. // Add padding to the end of the chunk
  43674. offset += ( GPU_CHUNK_BYTES - chunkStart );
  43675. }
  43676. uniform.offset = offset / bytesPerElement;
  43677. offset += itemSize;
  43678. }
  43679. return Math.ceil( offset / GPU_CHUNK_BYTES ) * GPU_CHUNK_BYTES;
  43680. }
  43681. /**
  43682. * Updates this group by updating each uniform object of
  43683. * the internal uniform list. The uniform objects check if their
  43684. * values has actually changed so this method only returns
  43685. * `true` if there is a real value change.
  43686. *
  43687. * @return {boolean} Whether the uniforms have been updated and
  43688. * must be uploaded to the GPU.
  43689. */
  43690. update() {
  43691. let updated = false;
  43692. for ( const uniform of this.uniforms ) {
  43693. if ( this.updateByType( uniform ) === true ) {
  43694. updated = true;
  43695. }
  43696. }
  43697. return updated;
  43698. }
  43699. /**
  43700. * Updates a given uniform by calling an update method matching
  43701. * the uniforms type.
  43702. *
  43703. * @param {Uniform} uniform - The uniform to update.
  43704. * @return {boolean} Whether the uniform has been updated or not.
  43705. */
  43706. updateByType( uniform ) {
  43707. if ( uniform.isNumberUniform ) return this.updateNumber( uniform );
  43708. if ( uniform.isVector2Uniform ) return this.updateVector2( uniform );
  43709. if ( uniform.isVector3Uniform ) return this.updateVector3( uniform );
  43710. if ( uniform.isVector4Uniform ) return this.updateVector4( uniform );
  43711. if ( uniform.isColorUniform ) return this.updateColor( uniform );
  43712. if ( uniform.isMatrix3Uniform ) return this.updateMatrix3( uniform );
  43713. if ( uniform.isMatrix4Uniform ) return this.updateMatrix4( uniform );
  43714. error( 'WebGPUUniformsGroup: Unsupported uniform type.', uniform );
  43715. }
  43716. /**
  43717. * Updates a given Number uniform.
  43718. *
  43719. * @param {NumberUniform} uniform - The Number uniform.
  43720. * @return {boolean} Whether the uniform has been updated or not.
  43721. */
  43722. updateNumber( uniform ) {
  43723. let updated = false;
  43724. const a = this.values;
  43725. const v = uniform.getValue();
  43726. const offset = uniform.offset;
  43727. const type = uniform.getType();
  43728. if ( a[ offset ] !== v ) {
  43729. const b = this._getBufferForType( type );
  43730. b[ offset ] = a[ offset ] = v;
  43731. updated = true;
  43732. }
  43733. return updated;
  43734. }
  43735. /**
  43736. * Updates a given Vector2 uniform.
  43737. *
  43738. * @param {Vector2Uniform} uniform - The Vector2 uniform.
  43739. * @return {boolean} Whether the uniform has been updated or not.
  43740. */
  43741. updateVector2( uniform ) {
  43742. let updated = false;
  43743. const a = this.values;
  43744. const v = uniform.getValue();
  43745. const offset = uniform.offset;
  43746. const type = uniform.getType();
  43747. if ( a[ offset + 0 ] !== v.x || a[ offset + 1 ] !== v.y ) {
  43748. const b = this._getBufferForType( type );
  43749. b[ offset + 0 ] = a[ offset + 0 ] = v.x;
  43750. b[ offset + 1 ] = a[ offset + 1 ] = v.y;
  43751. updated = true;
  43752. }
  43753. return updated;
  43754. }
  43755. /**
  43756. * Updates a given Vector3 uniform.
  43757. *
  43758. * @param {Vector3Uniform} uniform - The Vector3 uniform.
  43759. * @return {boolean} Whether the uniform has been updated or not.
  43760. */
  43761. updateVector3( uniform ) {
  43762. let updated = false;
  43763. const a = this.values;
  43764. const v = uniform.getValue();
  43765. const offset = uniform.offset;
  43766. const type = uniform.getType();
  43767. if ( a[ offset + 0 ] !== v.x || a[ offset + 1 ] !== v.y || a[ offset + 2 ] !== v.z ) {
  43768. const b = this._getBufferForType( type );
  43769. b[ offset + 0 ] = a[ offset + 0 ] = v.x;
  43770. b[ offset + 1 ] = a[ offset + 1 ] = v.y;
  43771. b[ offset + 2 ] = a[ offset + 2 ] = v.z;
  43772. updated = true;
  43773. }
  43774. return updated;
  43775. }
  43776. /**
  43777. * Updates a given Vector4 uniform.
  43778. *
  43779. * @param {Vector4Uniform} uniform - The Vector4 uniform.
  43780. * @return {boolean} Whether the uniform has been updated or not.
  43781. */
  43782. updateVector4( uniform ) {
  43783. let updated = false;
  43784. const a = this.values;
  43785. const v = uniform.getValue();
  43786. const offset = uniform.offset;
  43787. const type = uniform.getType();
  43788. if ( a[ offset + 0 ] !== v.x || a[ offset + 1 ] !== v.y || a[ offset + 2 ] !== v.z || a[ offset + 4 ] !== v.w ) {
  43789. const b = this._getBufferForType( type );
  43790. b[ offset + 0 ] = a[ offset + 0 ] = v.x;
  43791. b[ offset + 1 ] = a[ offset + 1 ] = v.y;
  43792. b[ offset + 2 ] = a[ offset + 2 ] = v.z;
  43793. b[ offset + 3 ] = a[ offset + 3 ] = v.w;
  43794. updated = true;
  43795. }
  43796. return updated;
  43797. }
  43798. /**
  43799. * Updates a given Color uniform.
  43800. *
  43801. * @param {ColorUniform} uniform - The Color uniform.
  43802. * @return {boolean} Whether the uniform has been updated or not.
  43803. */
  43804. updateColor( uniform ) {
  43805. let updated = false;
  43806. const a = this.values;
  43807. const c = uniform.getValue();
  43808. const offset = uniform.offset;
  43809. if ( a[ offset + 0 ] !== c.r || a[ offset + 1 ] !== c.g || a[ offset + 2 ] !== c.b ) {
  43810. const b = this.buffer;
  43811. b[ offset + 0 ] = a[ offset + 0 ] = c.r;
  43812. b[ offset + 1 ] = a[ offset + 1 ] = c.g;
  43813. b[ offset + 2 ] = a[ offset + 2 ] = c.b;
  43814. updated = true;
  43815. }
  43816. return updated;
  43817. }
  43818. /**
  43819. * Updates a given Matrix3 uniform.
  43820. *
  43821. * @param {Matrix3Uniform} uniform - The Matrix3 uniform.
  43822. * @return {boolean} Whether the uniform has been updated or not.
  43823. */
  43824. updateMatrix3( uniform ) {
  43825. let updated = false;
  43826. const a = this.values;
  43827. const e = uniform.getValue().elements;
  43828. const offset = uniform.offset;
  43829. if ( a[ offset + 0 ] !== e[ 0 ] || a[ offset + 1 ] !== e[ 1 ] || a[ offset + 2 ] !== e[ 2 ] ||
  43830. a[ offset + 4 ] !== e[ 3 ] || a[ offset + 5 ] !== e[ 4 ] || a[ offset + 6 ] !== e[ 5 ] ||
  43831. a[ offset + 8 ] !== e[ 6 ] || a[ offset + 9 ] !== e[ 7 ] || a[ offset + 10 ] !== e[ 8 ] ) {
  43832. const b = this.buffer;
  43833. b[ offset + 0 ] = a[ offset + 0 ] = e[ 0 ];
  43834. b[ offset + 1 ] = a[ offset + 1 ] = e[ 1 ];
  43835. b[ offset + 2 ] = a[ offset + 2 ] = e[ 2 ];
  43836. b[ offset + 4 ] = a[ offset + 4 ] = e[ 3 ];
  43837. b[ offset + 5 ] = a[ offset + 5 ] = e[ 4 ];
  43838. b[ offset + 6 ] = a[ offset + 6 ] = e[ 5 ];
  43839. b[ offset + 8 ] = a[ offset + 8 ] = e[ 6 ];
  43840. b[ offset + 9 ] = a[ offset + 9 ] = e[ 7 ];
  43841. b[ offset + 10 ] = a[ offset + 10 ] = e[ 8 ];
  43842. updated = true;
  43843. }
  43844. return updated;
  43845. }
  43846. /**
  43847. * Updates a given Matrix4 uniform.
  43848. *
  43849. * @param {Matrix4Uniform} uniform - The Matrix4 uniform.
  43850. * @return {boolean} Whether the uniform has been updated or not.
  43851. */
  43852. updateMatrix4( uniform ) {
  43853. let updated = false;
  43854. const a = this.values;
  43855. const e = uniform.getValue().elements;
  43856. const offset = uniform.offset;
  43857. if ( arraysEqual( a, e, offset ) === false ) {
  43858. const b = this.buffer;
  43859. b.set( e, offset );
  43860. setArray( a, e, offset );
  43861. updated = true;
  43862. }
  43863. return updated;
  43864. }
  43865. /**
  43866. * Returns a typed array that matches the given data type.
  43867. *
  43868. * @private
  43869. * @param {string} type - The data type.
  43870. * @return {TypedArray} The typed array.
  43871. */
  43872. _getBufferForType( type ) {
  43873. if ( type === 'int' || type === 'ivec2' || type === 'ivec3' || type === 'ivec4' ) return new Int32Array( this.buffer.buffer );
  43874. if ( type === 'uint' || type === 'uvec2' || type === 'uvec3' || type === 'uvec4' ) return new Uint32Array( this.buffer.buffer );
  43875. return this.buffer;
  43876. }
  43877. }
  43878. /**
  43879. * Sets the values of the second array to the first array.
  43880. *
  43881. * @private
  43882. * @param {TypedArray} a - The first array.
  43883. * @param {TypedArray} b - The second array.
  43884. * @param {number} offset - An index offset for the first array.
  43885. */
  43886. function setArray( a, b, offset ) {
  43887. for ( let i = 0, l = b.length; i < l; i ++ ) {
  43888. a[ offset + i ] = b[ i ];
  43889. }
  43890. }
  43891. /**
  43892. * Returns `true` if the given arrays are equal.
  43893. *
  43894. * @private
  43895. * @param {TypedArray} a - The first array.
  43896. * @param {TypedArray} b - The second array.
  43897. * @param {number} offset - An index offset for the first array.
  43898. * @return {boolean} Whether the given arrays are equal or not.
  43899. */
  43900. function arraysEqual( a, b, offset ) {
  43901. for ( let i = 0, l = b.length; i < l; i ++ ) {
  43902. if ( a[ offset + i ] !== b[ i ] ) return false;
  43903. }
  43904. return true;
  43905. }
  43906. let _id$3 = 0;
  43907. /**
  43908. * A special form of uniforms group that represents
  43909. * the individual uniforms as node-based uniforms.
  43910. *
  43911. * @private
  43912. * @augments UniformsGroup
  43913. */
  43914. class NodeUniformsGroup extends UniformsGroup {
  43915. /**
  43916. * Constructs a new node-based uniforms group.
  43917. *
  43918. * @param {string} name - The group's name.
  43919. * @param {UniformGroupNode} groupNode - The uniform group node.
  43920. */
  43921. constructor( name, groupNode ) {
  43922. super( name );
  43923. /**
  43924. * The group's ID.
  43925. *
  43926. * @type {number}
  43927. */
  43928. this.id = _id$3 ++;
  43929. /**
  43930. * The uniform group node.
  43931. *
  43932. * @type {UniformGroupNode}
  43933. */
  43934. this.groupNode = groupNode;
  43935. /**
  43936. * This flag can be used for type testing.
  43937. *
  43938. * @type {boolean}
  43939. * @readonly
  43940. * @default true
  43941. */
  43942. this.isNodeUniformsGroup = true;
  43943. }
  43944. }
  43945. /**
  43946. * Represents a sampler binding type.
  43947. *
  43948. * @private
  43949. * @augments Binding
  43950. */
  43951. class Sampler extends Binding {
  43952. /**
  43953. * Constructs a new sampler.
  43954. *
  43955. * @param {string} name - The samplers's name.
  43956. * @param {?Texture} texture - The texture this binding is referring to.
  43957. */
  43958. constructor( name, texture ) {
  43959. super( name );
  43960. /**
  43961. * The texture the sampler is referring to.
  43962. *
  43963. * @private
  43964. * @type {?Texture}
  43965. */
  43966. this._texture = null;
  43967. /**
  43968. * An event listener which is added to {@link texture}'s dispose event.
  43969. *
  43970. * @private
  43971. * @type {Function}
  43972. */
  43973. this._onTextureDispose = () => {
  43974. this.generation = null;
  43975. this.version = 0;
  43976. };
  43977. // Assignment to the texture via a setter must occur after "_onTextureDispose" is initialized.
  43978. this.texture = texture;
  43979. /**
  43980. * The binding's version.
  43981. *
  43982. * @type {number}
  43983. */
  43984. this.version = texture ? texture.version : 0;
  43985. /**
  43986. * The binding's generation which is an additional version
  43987. * qualifier.
  43988. *
  43989. * @type {?number}
  43990. * @default null
  43991. */
  43992. this.generation = null;
  43993. /**
  43994. * The binding's sampler key.
  43995. *
  43996. * @type {string}
  43997. * @default ''
  43998. */
  43999. this.samplerKey = '';
  44000. /**
  44001. * This flag can be used for type testing.
  44002. *
  44003. * @type {boolean}
  44004. * @readonly
  44005. * @default true
  44006. */
  44007. this.isSampler = true;
  44008. }
  44009. /**
  44010. * Sets the texture of this sampler.
  44011. *
  44012. * @param {Texture} value - The texture to set.
  44013. */
  44014. set texture( value ) {
  44015. if ( this._texture === value ) return;
  44016. if ( this._texture ) {
  44017. this._texture.removeEventListener( 'dispose', this._onTextureDispose );
  44018. }
  44019. this._texture = value;
  44020. this.generation = null;
  44021. this.version = 0;
  44022. if ( this._texture ) {
  44023. this._texture.addEventListener( 'dispose', this._onTextureDispose );
  44024. }
  44025. }
  44026. /**
  44027. * Gets the texture of this sampler.
  44028. * @return {?Texture} The texture.
  44029. */
  44030. get texture() {
  44031. return this._texture;
  44032. }
  44033. /**
  44034. * Updates the binding.
  44035. *
  44036. * @return {boolean} Whether the texture has been updated and must be
  44037. * uploaded to the GPU.
  44038. */
  44039. update() {
  44040. const { texture, version } = this;
  44041. if ( version !== texture.version ) {
  44042. this.version = texture.version;
  44043. return true;
  44044. }
  44045. return false;
  44046. }
  44047. clone() {
  44048. const clonedSampler = super.clone();
  44049. // fix dispose handler for cloned instances
  44050. // TODO: Find better solution, see #31747
  44051. clonedSampler._texture = null;
  44052. clonedSampler._onTextureDispose = () => {
  44053. clonedSampler.generation = null;
  44054. clonedSampler.version = 0;
  44055. };
  44056. clonedSampler.texture = this.texture;
  44057. return clonedSampler;
  44058. }
  44059. }
  44060. let _id$2 = 0;
  44061. /**
  44062. * Represents a sampled texture binding type.
  44063. *
  44064. * @private
  44065. * @augments Sampler
  44066. */
  44067. class SampledTexture extends Sampler {
  44068. /**
  44069. * Constructs a new sampled texture.
  44070. *
  44071. * @param {string} name - The sampled texture's name.
  44072. * @param {?Texture} texture - The texture this binding is referring to.
  44073. */
  44074. constructor( name, texture ) {
  44075. super( name, texture );
  44076. /**
  44077. * This identifier.
  44078. *
  44079. * @type {number}
  44080. */
  44081. this.id = _id$2 ++;
  44082. /**
  44083. * Whether the texture is a storage texture or not.
  44084. *
  44085. * @type {boolean}
  44086. * @default false
  44087. */
  44088. this.store = false;
  44089. /**
  44090. * The mip level to bind for storage textures.
  44091. *
  44092. * @type {number}
  44093. * @default 0
  44094. */
  44095. this.mipLevel = 0;
  44096. /**
  44097. * This flag can be used for type testing.
  44098. *
  44099. * @type {boolean}
  44100. * @readonly
  44101. * @default true
  44102. */
  44103. this.isSampledTexture = true;
  44104. }
  44105. }
  44106. /**
  44107. * A special form of sampled texture binding type.
  44108. * It's texture value is managed by a node object.
  44109. *
  44110. * @private
  44111. * @augments SampledTexture
  44112. */
  44113. class NodeSampledTexture extends SampledTexture {
  44114. /**
  44115. * Constructs a new node-based sampled texture.
  44116. *
  44117. * @param {string} name - The textures's name.
  44118. * @param {TextureNode} textureNode - The texture node.
  44119. * @param {UniformGroupNode} groupNode - The uniform group node.
  44120. * @param {?string} [access=null] - The access type.
  44121. */
  44122. constructor( name, textureNode, groupNode, access = null ) {
  44123. super( name, textureNode ? textureNode.value : null );
  44124. /**
  44125. * The texture node.
  44126. *
  44127. * @type {TextureNode}
  44128. */
  44129. this.textureNode = textureNode;
  44130. /**
  44131. * The uniform group node.
  44132. *
  44133. * @type {UniformGroupNode}
  44134. */
  44135. this.groupNode = groupNode;
  44136. /**
  44137. * The access type.
  44138. *
  44139. * @type {?string}
  44140. * @default null
  44141. */
  44142. this.access = access;
  44143. }
  44144. /**
  44145. * Updates the binding.
  44146. *
  44147. * @return {boolean} Whether the texture has been updated and must be
  44148. * uploaded to the GPU.
  44149. */
  44150. update() {
  44151. const { textureNode } = this;
  44152. if ( this.texture !== textureNode.value ) {
  44153. this.texture = textureNode.value;
  44154. return true;
  44155. }
  44156. return super.update();
  44157. }
  44158. }
  44159. /**
  44160. * A special form of sampled cube texture binding type.
  44161. * It's texture value is managed by a node object.
  44162. *
  44163. * @private
  44164. * @augments NodeSampledTexture
  44165. */
  44166. class NodeSampledCubeTexture extends NodeSampledTexture {
  44167. /**
  44168. * Constructs a new node-based sampled cube texture.
  44169. *
  44170. * @param {string} name - The textures's name.
  44171. * @param {TextureNode} textureNode - The texture node.
  44172. * @param {UniformGroupNode} groupNode - The uniform group node.
  44173. * @param {?string} [access=null] - The access type.
  44174. */
  44175. constructor( name, textureNode, groupNode, access = null ) {
  44176. super( name, textureNode, groupNode, access );
  44177. /**
  44178. * This flag can be used for type testing.
  44179. *
  44180. * @type {boolean}
  44181. * @readonly
  44182. * @default true
  44183. */
  44184. this.isSampledCubeTexture = true;
  44185. }
  44186. }
  44187. /**
  44188. * A special form of sampled 3D texture binding type.
  44189. * It's texture value is managed by a node object.
  44190. *
  44191. * @private
  44192. * @augments NodeSampledTexture
  44193. */
  44194. class NodeSampledTexture3D extends NodeSampledTexture {
  44195. /**
  44196. * Constructs a new node-based sampled 3D texture.
  44197. *
  44198. * @param {string} name - The textures's name.
  44199. * @param {TextureNode} textureNode - The texture node.
  44200. * @param {UniformGroupNode} groupNode - The uniform group node.
  44201. * @param {?string} [access=null] - The access type.
  44202. */
  44203. constructor( name, textureNode, groupNode, access = null ) {
  44204. super( name, textureNode, groupNode, access );
  44205. /**
  44206. * This flag can be used for type testing.
  44207. *
  44208. * @type {boolean}
  44209. * @readonly
  44210. * @default true
  44211. */
  44212. this.isSampledTexture3D = true;
  44213. }
  44214. }
  44215. const glslPolyfills = {
  44216. bitcast_int_uint: new CodeNode( /* glsl */'uint tsl_bitcast_int_to_uint ( int x ) { return floatBitsToUint( intBitsToFloat ( x ) ); }' ),
  44217. bitcast_uint_int: new CodeNode( /* glsl */'uint tsl_bitcast_uint_to_int ( uint x ) { return floatBitsToInt( uintBitsToFloat ( x ) ); }' )
  44218. };
  44219. const glslMethods = {
  44220. textureDimensions: 'textureSize',
  44221. equals: 'equal',
  44222. bitcast_float_int: 'floatBitsToInt',
  44223. bitcast_int_float: 'intBitsToFloat',
  44224. bitcast_uint_float: 'uintBitsToFloat',
  44225. bitcast_float_uint: 'floatBitsToUint',
  44226. bitcast_uint_int: 'tsl_bitcast_uint_to_int',
  44227. bitcast_int_uint: 'tsl_bitcast_int_to_uint',
  44228. floatpack_snorm_2x16: 'packSnorm2x16',
  44229. floatpack_unorm_2x16: 'packUnorm2x16',
  44230. floatpack_float16_2x16: 'packHalf2x16',
  44231. floatunpack_snorm_2x16: 'unpackSnorm2x16',
  44232. floatunpack_unorm_2x16: 'unpackUnorm2x16',
  44233. floatunpack_float16_2x16: 'unpackHalf2x16'
  44234. };
  44235. const precisionLib = {
  44236. low: 'lowp',
  44237. medium: 'mediump',
  44238. high: 'highp'
  44239. };
  44240. const supports$1 = {
  44241. swizzleAssign: true,
  44242. storageBuffer: false
  44243. };
  44244. const interpolationTypeMap = {
  44245. perspective: 'smooth',
  44246. linear: 'noperspective'
  44247. };
  44248. const interpolationModeMap = {
  44249. 'centroid': 'centroid'
  44250. };
  44251. const defaultPrecisions = `
  44252. precision highp float;
  44253. precision highp int;
  44254. precision highp sampler2D;
  44255. precision highp sampler3D;
  44256. precision highp samplerCube;
  44257. precision highp sampler2DArray;
  44258. precision highp usampler2D;
  44259. precision highp usampler3D;
  44260. precision highp usamplerCube;
  44261. precision highp usampler2DArray;
  44262. precision highp isampler2D;
  44263. precision highp isampler3D;
  44264. precision highp isamplerCube;
  44265. precision highp isampler2DArray;
  44266. precision lowp sampler2DShadow;
  44267. precision lowp sampler2DArrayShadow;
  44268. precision lowp samplerCubeShadow;
  44269. `;
  44270. /**
  44271. * A node builder targeting GLSL.
  44272. *
  44273. * This module generates GLSL shader code from node materials and also
  44274. * generates the respective bindings and vertex buffer definitions. These
  44275. * data are later used by the renderer to create render and compute pipelines
  44276. * for render objects.
  44277. *
  44278. * @augments NodeBuilder
  44279. */
  44280. class GLSLNodeBuilder extends NodeBuilder {
  44281. /**
  44282. * Constructs a new GLSL node builder renderer.
  44283. *
  44284. * @param {Object3D} object - The 3D object.
  44285. * @param {Renderer} renderer - The renderer.
  44286. */
  44287. constructor( object, renderer ) {
  44288. super( object, renderer, new GLSLNodeParser() );
  44289. /**
  44290. * A dictionary holds for each shader stage ('vertex', 'fragment', 'compute')
  44291. * another dictionary which manages UBOs per group ('render','frame','object').
  44292. *
  44293. * @type {Object<string,Object<string,NodeUniformsGroup>>}
  44294. */
  44295. this.uniformGroups = {};
  44296. /**
  44297. * An array that holds objects defining the varying and attribute data in
  44298. * context of Transform Feedback.
  44299. *
  44300. * @type {Array<Object<string,AttributeNode|string>>}
  44301. */
  44302. this.transforms = [];
  44303. /**
  44304. * A dictionary that holds for each shader stage a Map of used extensions.
  44305. *
  44306. * @type {Object<string,Map<string,Object>>}
  44307. */
  44308. this.extensions = {};
  44309. /**
  44310. * A dictionary that holds for each shader stage an Array of used builtins.
  44311. *
  44312. * @type {Object<string,Array<string>>}
  44313. */
  44314. this.builtins = { vertex: [], fragment: [], compute: [] };
  44315. }
  44316. /**
  44317. * Checks if the given texture requires a manual conversion to the working color space.
  44318. *
  44319. * @param {Texture} texture - The texture to check.
  44320. * @return {boolean} Whether the given texture requires a conversion to working color space or not.
  44321. */
  44322. needsToWorkingColorSpace( texture ) {
  44323. return texture.isVideoTexture === true && texture.colorSpace !== NoColorSpace;
  44324. }
  44325. /**
  44326. * Includes the given method name into the current
  44327. * function node.
  44328. *
  44329. * @private
  44330. * @param {string} name - The method name to include.
  44331. * @return {CodeNode} The respective code node.
  44332. */
  44333. _include( name ) {
  44334. const codeNode = glslPolyfills[ name ];
  44335. codeNode.build( this );
  44336. this.addInclude( codeNode );
  44337. return codeNode;
  44338. }
  44339. /**
  44340. * Returns the native shader method name for a given generic name.
  44341. *
  44342. * @param {string} method - The method name to resolve.
  44343. * @return {string} The resolved GLSL method name.
  44344. */
  44345. getMethod( method ) {
  44346. if ( glslPolyfills[ method ] !== undefined ) {
  44347. this._include( method );
  44348. }
  44349. return glslMethods[ method ] || method;
  44350. }
  44351. /**
  44352. * Returns the bitcast method name for a given input and outputType.
  44353. *
  44354. * @param {string} type - The output type to bitcast to.
  44355. * @param {string} inputType - The input type of the.
  44356. * @return {string} The resolved WGSL bitcast invocation.
  44357. */
  44358. getBitcastMethod( type, inputType ) {
  44359. return this.getMethod( `bitcast_${ inputType }_${ type }` );
  44360. }
  44361. /**
  44362. * Returns the float packing method name for a given numeric encoding.
  44363. *
  44364. * @param {string} encoding - The numeric encoding that describes how the float values are mapped to the integer range.
  44365. * @returns {string} The resolved GLSL float packing method name.
  44366. */
  44367. getFloatPackingMethod( encoding ) {
  44368. return this.getMethod( `floatpack_${ encoding }_2x16` );
  44369. }
  44370. /**
  44371. * Returns the float unpacking method name for a given numeric encoding.
  44372. *
  44373. * @param {string} encoding - The numeric encoding that describes how the integer values are mapped to the float range.
  44374. * @returns {string} The resolved GLSL float unpacking method name.
  44375. */
  44376. getFloatUnpackingMethod( encoding ) {
  44377. return this.getMethod( `floatunpack_${ encoding }_2x16` );
  44378. }
  44379. /**
  44380. * Returns the native snippet for a ternary operation.
  44381. *
  44382. * @param {string} condSnippet - The condition determining which expression gets resolved.
  44383. * @param {string} ifSnippet - The expression to resolve to if the condition is true.
  44384. * @param {string} elseSnippet - The expression to resolve to if the condition is false.
  44385. * @return {string} The resolved method name.
  44386. */
  44387. getTernary( condSnippet, ifSnippet, elseSnippet ) {
  44388. return `${condSnippet} ? ${ifSnippet} : ${elseSnippet}`;
  44389. }
  44390. /**
  44391. * Returns the output struct name. Not relevant for GLSL.
  44392. *
  44393. * @return {string}
  44394. */
  44395. getOutputStructName() {
  44396. return '';
  44397. }
  44398. /**
  44399. * Builds the given shader node.
  44400. *
  44401. * @param {ShaderNodeInternal} shaderNode - The shader node.
  44402. * @return {string} The GLSL function code.
  44403. */
  44404. buildFunctionCode( shaderNode ) {
  44405. const layout = shaderNode.layout;
  44406. const flowData = this.flowShaderNode( shaderNode );
  44407. const parameters = [];
  44408. for ( const input of layout.inputs ) {
  44409. parameters.push( this.getType( input.type ) + ' ' + input.name );
  44410. }
  44411. //
  44412. const code = `${ this.getType( layout.type ) } ${ layout.name }( ${ parameters.join( ', ' ) } ) {
  44413. ${ flowData.vars }
  44414. ${ flowData.code }
  44415. return ${ flowData.result };
  44416. }`;
  44417. //
  44418. return code;
  44419. }
  44420. /**
  44421. * Setups the Pixel Buffer Object (PBO) for the given storage
  44422. * buffer node.
  44423. *
  44424. * @param {StorageBufferNode} storageBufferNode - The storage buffer node.
  44425. */
  44426. setupPBO( storageBufferNode ) {
  44427. const attribute = storageBufferNode.value;
  44428. if ( attribute.pbo === undefined ) {
  44429. const originalArray = attribute.array;
  44430. const numElements = attribute.count * attribute.itemSize;
  44431. const { itemSize } = attribute;
  44432. const isInteger = attribute.array.constructor.name.toLowerCase().includes( 'int' );
  44433. let format = isInteger ? RedIntegerFormat : RedFormat;
  44434. if ( itemSize === 2 ) {
  44435. format = isInteger ? RGIntegerFormat : RGFormat;
  44436. } else if ( itemSize === 3 ) {
  44437. format = isInteger ? RGBIntegerFormat : RGBFormat;
  44438. } else if ( itemSize === 4 ) {
  44439. format = isInteger ? RGBAIntegerFormat : RGBAFormat;
  44440. }
  44441. const typeMap = {
  44442. Float32Array: FloatType,
  44443. Uint8Array: UnsignedByteType,
  44444. Uint16Array: UnsignedShortType,
  44445. Uint32Array: UnsignedIntType,
  44446. Int8Array: ByteType,
  44447. Int16Array: ShortType,
  44448. Int32Array: IntType,
  44449. Uint8ClampedArray: UnsignedByteType,
  44450. };
  44451. const width = Math.pow( 2, Math.ceil( Math.log2( Math.sqrt( numElements / itemSize ) ) ) );
  44452. let height = Math.ceil( ( numElements / itemSize ) / width );
  44453. if ( width * height * itemSize < numElements ) height ++; // Ensure enough space
  44454. const newSize = width * height * itemSize;
  44455. const newArray = new originalArray.constructor( newSize );
  44456. newArray.set( originalArray, 0 );
  44457. attribute.array = newArray;
  44458. const pboTexture = new DataTexture( attribute.array, width, height, format, typeMap[ attribute.array.constructor.name ] || FloatType );
  44459. pboTexture.needsUpdate = true;
  44460. pboTexture.isPBOTexture = true;
  44461. const pbo = new TextureNode( pboTexture, null, null );
  44462. pbo.setPrecision( 'high' );
  44463. attribute.pboNode = pbo;
  44464. attribute.pbo = pbo.value;
  44465. this.getUniformFromNode( attribute.pboNode, 'texture', this.shaderStage, this.context.nodeName );
  44466. }
  44467. }
  44468. /**
  44469. * Returns a GLSL snippet that represents the property name of the given node.
  44470. *
  44471. * @param {Node} node - The node.
  44472. * @param {string} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  44473. * @return {string} The property name.
  44474. */
  44475. getPropertyName( node, shaderStage = this.shaderStage ) {
  44476. if ( node.isNodeUniform && node.node.isTextureNode !== true && node.node.isBufferNode !== true ) {
  44477. return shaderStage.charAt( 0 ) + '_' + node.name;
  44478. }
  44479. return super.getPropertyName( node, shaderStage );
  44480. }
  44481. /**
  44482. * Setups the Pixel Buffer Object (PBO) for the given storage
  44483. * buffer node.
  44484. *
  44485. * @param {StorageArrayElementNode} storageArrayElementNode - The storage array element node.
  44486. * @return {string} The property name.
  44487. */
  44488. generatePBO( storageArrayElementNode ) {
  44489. const { node, indexNode } = storageArrayElementNode;
  44490. const attribute = node.value;
  44491. if ( this.renderer.backend.has( attribute ) ) {
  44492. const attributeData = this.renderer.backend.get( attribute );
  44493. attributeData.pbo = attribute.pbo;
  44494. }
  44495. const nodeUniform = this.getUniformFromNode( attribute.pboNode, 'texture', this.shaderStage, this.context.nodeName );
  44496. const textureName = this.getPropertyName( nodeUniform );
  44497. this.increaseUsage( indexNode ); // force cache generate to be used as index in x,y
  44498. const indexSnippet = indexNode.build( this, 'uint' );
  44499. const elementNodeData = this.getDataFromNode( storageArrayElementNode );
  44500. let propertyName = elementNodeData.propertyName;
  44501. if ( propertyName === undefined ) {
  44502. // property element
  44503. const nodeVar = this.getVarFromNode( storageArrayElementNode );
  44504. propertyName = this.getPropertyName( nodeVar );
  44505. // property size
  44506. const bufferNodeData = this.getDataFromNode( node );
  44507. let propertySizeName = bufferNodeData.propertySizeName;
  44508. if ( propertySizeName === undefined ) {
  44509. propertySizeName = propertyName + 'Size';
  44510. this.getVarFromNode( node, propertySizeName, 'uint' );
  44511. this.addLineFlowCode( `${ propertySizeName } = uint( textureSize( ${ textureName }, 0 ).x )`, storageArrayElementNode );
  44512. bufferNodeData.propertySizeName = propertySizeName;
  44513. }
  44514. //
  44515. const { itemSize } = attribute;
  44516. const channel = '.' + vectorComponents.join( '' ).slice( 0, itemSize );
  44517. const uvSnippet = `ivec2(${indexSnippet} % ${ propertySizeName }, ${indexSnippet} / ${ propertySizeName })`;
  44518. const snippet = this.generateTextureLoad( null, textureName, uvSnippet, '0', null, null );
  44519. //
  44520. let prefix = 'vec4';
  44521. if ( attribute.pbo.type === UnsignedIntType ) {
  44522. prefix = 'uvec4';
  44523. } else if ( attribute.pbo.type === IntType ) {
  44524. prefix = 'ivec4';
  44525. }
  44526. this.addLineFlowCode( `${ propertyName } = ${prefix}(${ snippet })${channel}`, storageArrayElementNode );
  44527. elementNodeData.propertyName = propertyName;
  44528. }
  44529. return propertyName;
  44530. }
  44531. /**
  44532. * Generates the GLSL snippet that reads a single texel from a texture without sampling or filtering.
  44533. *
  44534. * @param {?Texture} texture - The texture.
  44535. * @param {string} textureProperty - The name of the texture uniform in the shader.
  44536. * @param {string} uvIndexSnippet - A GLSL snippet that represents texture coordinates used for sampling.
  44537. * @param {?string} levelSnippet - A GLSL snippet that represents the mip level, with level 0 containing a full size version of the texture.
  44538. * @param {?string} depthSnippet - A GLSL snippet that represents the 0-based texture array index to sample.
  44539. * @param {?string} offsetSnippet - A GLSL snippet that represents the offset that will be applied to the unnormalized texture coordinate before sampling the texture.
  44540. * @return {string} The GLSL snippet.
  44541. */
  44542. generateTextureLoad( texture, textureProperty, uvIndexSnippet, levelSnippet, depthSnippet, offsetSnippet ) {
  44543. if ( levelSnippet === null ) levelSnippet = '0';
  44544. let snippet;
  44545. if ( depthSnippet ) {
  44546. if ( offsetSnippet ) {
  44547. snippet = `texelFetchOffset( ${ textureProperty }, ivec3( ${ uvIndexSnippet }, ${ depthSnippet } ), ${ levelSnippet }, ${ offsetSnippet } )`;
  44548. } else {
  44549. snippet = `texelFetch( ${ textureProperty }, ivec3( ${ uvIndexSnippet }, ${ depthSnippet } ), ${ levelSnippet } )`;
  44550. }
  44551. } else {
  44552. if ( offsetSnippet ) {
  44553. snippet = `texelFetchOffset( ${ textureProperty }, ${ uvIndexSnippet }, ${ levelSnippet }, ${ offsetSnippet } )`;
  44554. } else {
  44555. snippet = `texelFetch( ${ textureProperty }, ${ uvIndexSnippet }, ${ levelSnippet } )`;
  44556. }
  44557. }
  44558. if ( texture !== null && texture.isDepthTexture ) {
  44559. snippet += '.x';
  44560. }
  44561. return snippet;
  44562. }
  44563. /**
  44564. * Generates the GLSL snippet for sampling/loading the given texture.
  44565. *
  44566. * @param {Texture} texture - The texture.
  44567. * @param {string} textureProperty - The name of the texture uniform in the shader.
  44568. * @param {string} uvSnippet - A GLSL snippet that represents texture coordinates used for sampling.
  44569. * @param {?string} depthSnippet - A GLSL snippet that represents the 0-based texture array index to sample.
  44570. * @param {?string} offsetSnippet - A GLSL snippet that represents the offset that will be applied to the unnormalized texture coordinate before sampling the texture.
  44571. * @return {string} The GLSL snippet.
  44572. */
  44573. generateTexture( texture, textureProperty, uvSnippet, depthSnippet, offsetSnippet ) {
  44574. if ( depthSnippet ) uvSnippet = `vec3( ${ uvSnippet }, ${ depthSnippet } )`;
  44575. if ( texture.isDepthTexture ) {
  44576. if ( offsetSnippet ) return `textureOffset( ${ textureProperty }, ${ uvSnippet }, ${ offsetSnippet } ).x`;
  44577. return `texture( ${ textureProperty }, ${ uvSnippet } ).x`;
  44578. }
  44579. if ( offsetSnippet ) return `textureOffset( ${ textureProperty }, ${ uvSnippet }, ${ offsetSnippet } )`;
  44580. return `texture( ${ textureProperty }, ${ uvSnippet } )`;
  44581. }
  44582. /**
  44583. * Generates the GLSL snippet when sampling textures with explicit mip level.
  44584. *
  44585. * @param {Texture} texture - The texture.
  44586. * @param {string} textureProperty - The name of the texture uniform in the shader.
  44587. * @param {string} uvSnippet - A GLSL snippet that represents texture coordinates used for sampling.
  44588. * @param {string} levelSnippet - A GLSL snippet that represents the mip level, with level 0 containing a full size version of the texture.
  44589. * @param {?string} offsetSnippet - A GLSL snippet that represents the offset that will be applied to the unnormalized texture coordinate before sampling the texture.
  44590. * @return {string} The GLSL snippet.
  44591. */
  44592. generateTextureLevel( texture, textureProperty, uvSnippet, levelSnippet, offsetSnippet ) {
  44593. if ( offsetSnippet ) {
  44594. return `textureLodOffset( ${ textureProperty }, ${ uvSnippet }, ${ levelSnippet }, ${ offsetSnippet } )`;
  44595. }
  44596. return `textureLod( ${ textureProperty }, ${ uvSnippet }, ${ levelSnippet } )`;
  44597. }
  44598. /**
  44599. * Generates the GLSL snippet when sampling textures with a bias to the mip level.
  44600. *
  44601. * @param {Texture} texture - The texture.
  44602. * @param {string} textureProperty - The name of the texture uniform in the shader.
  44603. * @param {string} uvSnippet - A GLSL snippet that represents texture coordinates used for sampling.
  44604. * @param {string} biasSnippet - A GLSL snippet that represents the bias to apply to the mip level before sampling.
  44605. * @param {?string} offsetSnippet - A GLSL snippet that represents the offset that will be applied to the unnormalized texture coordinate before sampling the texture.
  44606. * @return {string} The GLSL snippet.
  44607. */
  44608. generateTextureBias( texture, textureProperty, uvSnippet, biasSnippet, offsetSnippet ) {
  44609. if ( offsetSnippet ) {
  44610. return `textureOffset( ${ textureProperty }, ${ uvSnippet }, ${ offsetSnippet }, ${ biasSnippet } )`;
  44611. }
  44612. return `texture( ${ textureProperty }, ${ uvSnippet }, ${ biasSnippet } )`;
  44613. }
  44614. /**
  44615. * Generates the GLSL snippet for sampling/loading the given texture using explicit gradients.
  44616. *
  44617. * @param {Texture} texture - The texture.
  44618. * @param {string} textureProperty - The name of the texture uniform in the shader.
  44619. * @param {string} uvSnippet - A GLSL snippet that represents texture coordinates used for sampling.
  44620. * @param {Array<string>} gradSnippet - An array holding both gradient GLSL snippets.
  44621. * @param {?string} offsetSnippet - A GLSL snippet that represents the offset that will be applied to the unnormalized texture coordinate before sampling the texture.
  44622. * @return {string} The GLSL snippet.
  44623. */
  44624. generateTextureGrad( texture, textureProperty, uvSnippet, gradSnippet, offsetSnippet ) {
  44625. if ( offsetSnippet ) {
  44626. return `textureGradOffset( ${ textureProperty }, ${ uvSnippet }, ${ gradSnippet[ 0 ] }, ${ gradSnippet[ 1 ] }, ${ offsetSnippet } )`;
  44627. }
  44628. return `textureGrad( ${ textureProperty }, ${ uvSnippet }, ${ gradSnippet[ 0 ] }, ${ gradSnippet[ 1 ] } )`;
  44629. }
  44630. /**
  44631. * Generates the GLSL snippet for sampling a depth texture and comparing the sampled depth values
  44632. * against a reference value.
  44633. *
  44634. * @param {Texture} texture - The texture.
  44635. * @param {string} textureProperty - The name of the texture uniform in the shader.
  44636. * @param {string} uvSnippet - A GLSL snippet that represents texture coordinates used for sampling.
  44637. * @param {string} compareSnippet - A GLSL snippet that represents the reference value.
  44638. * @param {?string} depthSnippet - A GLSL snippet that represents 0-based texture array index to sample.
  44639. * @param {?string} offsetSnippet - A GLSL snippet that represents the offset that will be applied to the unnormalized texture coordinate before sampling the texture.
  44640. * @param {string} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  44641. * @return {string} The GLSL snippet.
  44642. */
  44643. generateTextureCompare( texture, textureProperty, uvSnippet, compareSnippet, depthSnippet, offsetSnippet, shaderStage = this.shaderStage ) {
  44644. if ( shaderStage === 'fragment' ) {
  44645. // Cube shadow maps use vec4(direction, compareValue)
  44646. if ( texture.isCubeTexture ) {
  44647. return `texture( ${ textureProperty }, vec4( ${ uvSnippet }, ${ compareSnippet } ) )`;
  44648. }
  44649. if ( depthSnippet ) {
  44650. if ( offsetSnippet ) {
  44651. return `textureOffset( ${ textureProperty }, vec4( ${ uvSnippet }, ${ depthSnippet }, ${ compareSnippet } ), ${ offsetSnippet } )`;
  44652. }
  44653. return `texture( ${ textureProperty }, vec4( ${ uvSnippet }, ${ depthSnippet }, ${ compareSnippet } ) )`;
  44654. }
  44655. if ( offsetSnippet ) {
  44656. return `textureOffset( ${ textureProperty }, vec3( ${ uvSnippet }, ${ compareSnippet } ), ${ offsetSnippet } )`;
  44657. }
  44658. return `texture( ${ textureProperty }, vec3( ${ uvSnippet }, ${ compareSnippet } ) )`;
  44659. } else {
  44660. error( `WebGPURenderer: THREE.DepthTexture.compareFunction() does not support ${ shaderStage } shader.` );
  44661. }
  44662. }
  44663. /**
  44664. * Returns the variables of the given shader stage as a GLSL string.
  44665. *
  44666. * @param {string} shaderStage - The shader stage.
  44667. * @return {string} The GLSL snippet that defines the variables.
  44668. */
  44669. getVars( shaderStage ) {
  44670. const snippets = [];
  44671. const vars = this.vars[ shaderStage ];
  44672. if ( vars !== undefined ) {
  44673. for ( const variable of vars ) {
  44674. snippets.push( `${ this.getVar( variable.type, variable.name, variable.count ) };` );
  44675. }
  44676. }
  44677. return snippets.join( '\n\t' );
  44678. }
  44679. /**
  44680. * Returns the uniforms of the given shader stage as a GLSL string.
  44681. *
  44682. * @param {string} shaderStage - The shader stage.
  44683. * @return {string} The GLSL snippet that defines the uniforms.
  44684. */
  44685. getUniforms( shaderStage ) {
  44686. const uniforms = this.uniforms[ shaderStage ];
  44687. const bindingSnippets = [];
  44688. const uniformGroups = {};
  44689. for ( const uniform of uniforms ) {
  44690. let snippet = null;
  44691. let group = false;
  44692. if ( uniform.type === 'texture' || uniform.type === 'texture3D' ) {
  44693. const texture = uniform.node.value;
  44694. let typePrefix = '';
  44695. if ( texture.isDataTexture === true || texture.isData3DTexture === true ) {
  44696. if ( texture.type === UnsignedIntType ) {
  44697. typePrefix = 'u';
  44698. } else if ( texture.type === IntType ) {
  44699. typePrefix = 'i';
  44700. }
  44701. }
  44702. if ( uniform.type === 'texture3D' && texture.isArrayTexture === false ) {
  44703. snippet = `${typePrefix}sampler3D ${ uniform.name };`;
  44704. } else if ( texture.compareFunction ) {
  44705. if ( texture.isArrayTexture === true ) {
  44706. snippet = `sampler2DArrayShadow ${ uniform.name };`;
  44707. } else {
  44708. snippet = `sampler2DShadow ${ uniform.name };`;
  44709. }
  44710. } else if ( texture.isArrayTexture === true || texture.isDataArrayTexture === true || texture.isCompressedArrayTexture === true ) {
  44711. snippet = `${typePrefix}sampler2DArray ${ uniform.name };`;
  44712. } else {
  44713. snippet = `${typePrefix}sampler2D ${ uniform.name };`;
  44714. }
  44715. } else if ( uniform.type === 'cubeTexture' ) {
  44716. snippet = `samplerCube ${ uniform.name };`;
  44717. } else if ( uniform.type === 'cubeDepthTexture' ) {
  44718. snippet = `samplerCubeShadow ${ uniform.name };`;
  44719. } else if ( uniform.type === 'buffer' ) {
  44720. const bufferNode = uniform.node;
  44721. const bufferType = this.getType( bufferNode.bufferType );
  44722. const bufferCount = bufferNode.bufferCount;
  44723. const bufferCountSnippet = bufferCount > 0 ? bufferCount : '';
  44724. snippet = `${bufferNode.name} {\n\t${ bufferType } ${ uniform.name }[${ bufferCountSnippet }];\n};\n`;
  44725. } else {
  44726. const vectorType = this.getVectorType( uniform.type );
  44727. snippet = `${ vectorType } ${ this.getPropertyName( uniform, shaderStage ) };`;
  44728. group = true;
  44729. }
  44730. const precision = uniform.node.precision;
  44731. if ( precision !== null ) {
  44732. snippet = precisionLib[ precision ] + ' ' + snippet;
  44733. }
  44734. if ( group ) {
  44735. snippet = '\t' + snippet;
  44736. const groupName = uniform.groupNode.name;
  44737. const groupSnippets = uniformGroups[ groupName ] || ( uniformGroups[ groupName ] = [] );
  44738. groupSnippets.push( snippet );
  44739. } else {
  44740. snippet = 'uniform ' + snippet;
  44741. bindingSnippets.push( snippet );
  44742. }
  44743. }
  44744. let output = '';
  44745. for ( const name in uniformGroups ) {
  44746. const groupSnippets = uniformGroups[ name ];
  44747. output += this._getGLSLUniformStruct( shaderStage + '_' + name, groupSnippets.join( '\n' ) ) + '\n';
  44748. }
  44749. output += bindingSnippets.join( '\n' );
  44750. return output;
  44751. }
  44752. /**
  44753. * Returns the type for a given buffer attribute.
  44754. *
  44755. * @param {BufferAttribute} attribute - The buffer attribute.
  44756. * @return {string} The type.
  44757. */
  44758. getTypeFromAttribute( attribute ) {
  44759. let nodeType = super.getTypeFromAttribute( attribute );
  44760. if ( /^[iu]/.test( nodeType ) && attribute.gpuType !== IntType ) {
  44761. let dataAttribute = attribute;
  44762. if ( attribute.isInterleavedBufferAttribute ) dataAttribute = attribute.data;
  44763. const array = dataAttribute.array;
  44764. if ( ( array instanceof Uint32Array || array instanceof Int32Array ) === false ) {
  44765. nodeType = nodeType.slice( 1 );
  44766. }
  44767. }
  44768. return nodeType;
  44769. }
  44770. /**
  44771. * Returns the shader attributes of the given shader stage as a GLSL string.
  44772. *
  44773. * @param {string} shaderStage - The shader stage.
  44774. * @return {string} The GLSL snippet that defines the shader attributes.
  44775. */
  44776. getAttributes( shaderStage ) {
  44777. let snippet = '';
  44778. if ( shaderStage === 'vertex' || shaderStage === 'compute' ) {
  44779. const attributes = this.getAttributesArray();
  44780. let location = 0;
  44781. for ( const attribute of attributes ) {
  44782. snippet += `layout( location = ${ location ++ } ) in ${ attribute.type } ${ attribute.name };\n`;
  44783. }
  44784. }
  44785. return snippet;
  44786. }
  44787. /**
  44788. * Returns the members of the given struct type node as a GLSL string.
  44789. *
  44790. * @param {StructTypeNode} struct - The struct type node.
  44791. * @return {string} The GLSL snippet that defines the struct members.
  44792. */
  44793. getStructMembers( struct ) {
  44794. const snippets = [];
  44795. for ( const member of struct.members ) {
  44796. snippets.push( `\t${ member.type } ${ member.name };` );
  44797. }
  44798. return snippets.join( '\n' );
  44799. }
  44800. /**
  44801. * Returns the structs of the given shader stage as a GLSL string.
  44802. *
  44803. * @param {string} shaderStage - The shader stage.
  44804. * @return {string} The GLSL snippet that defines the structs.
  44805. */
  44806. getStructs( shaderStage ) {
  44807. const snippets = [];
  44808. const structs = this.structs[ shaderStage ];
  44809. const outputSnippet = [];
  44810. for ( const struct of structs ) {
  44811. if ( struct.output ) {
  44812. for ( const member of struct.members ) {
  44813. outputSnippet.push( `layout( location = ${ member.index } ) out ${ member.type } ${ member.name };` );
  44814. }
  44815. } else {
  44816. let snippet = 'struct ' + struct.name + ' {\n';
  44817. snippet += this.getStructMembers( struct );
  44818. snippet += '\n};\n';
  44819. snippets.push( snippet );
  44820. }
  44821. }
  44822. if ( outputSnippet.length === 0 ) {
  44823. outputSnippet.push( 'layout( location = 0 ) out vec4 fragColor;' );
  44824. }
  44825. return '\n' + outputSnippet.join( '\n' ) + '\n\n' + snippets.join( '\n' );
  44826. }
  44827. /**
  44828. * Returns the varyings of the given shader stage as a GLSL string.
  44829. *
  44830. * @param {string} shaderStage - The shader stage.
  44831. * @return {string} The GLSL snippet that defines the varyings.
  44832. */
  44833. getVaryings( shaderStage ) {
  44834. let snippet = '';
  44835. const varyings = this.varyings;
  44836. if ( shaderStage === 'vertex' || shaderStage === 'compute' ) {
  44837. for ( const varying of varyings ) {
  44838. if ( shaderStage === 'compute' ) varying.needsInterpolation = true;
  44839. const type = this.getType( varying.type );
  44840. if ( varying.needsInterpolation ) {
  44841. if ( varying.interpolationType ) {
  44842. const interpolationType = interpolationTypeMap[ varying.interpolationType ] || varying.interpolationType;
  44843. const sampling = interpolationModeMap[ varying.interpolationSampling ] || '';
  44844. snippet += `${ interpolationType } ${ sampling } out ${ type } ${ varying.name };\n`;
  44845. } else {
  44846. const flat = type.includes( 'int' ) || type.includes( 'uv' ) || type.includes( 'iv' ) ? 'flat ' : '';
  44847. snippet += `${ flat }out ${ type } ${ varying.name };\n`;
  44848. }
  44849. } else {
  44850. snippet += `${type} ${varying.name};\n`; // generate variable (no varying required)
  44851. }
  44852. }
  44853. } else if ( shaderStage === 'fragment' ) {
  44854. for ( const varying of varyings ) {
  44855. if ( varying.needsInterpolation ) {
  44856. const type = this.getType( varying.type );
  44857. if ( varying.interpolationType ) {
  44858. const interpolationType = interpolationTypeMap[ varying.interpolationType ] || varying.interpolationType;
  44859. const sampling = interpolationModeMap[ varying.interpolationSampling ] || '';
  44860. snippet += `${ interpolationType } ${ sampling } in ${ type } ${ varying.name };\n`;
  44861. } else {
  44862. const flat = type.includes( 'int' ) || type.includes( 'uv' ) || type.includes( 'iv' ) ? 'flat ' : '';
  44863. snippet += `${ flat }in ${ type } ${ varying.name };\n`;
  44864. }
  44865. }
  44866. }
  44867. }
  44868. for ( const builtin of this.builtins[ shaderStage ] ) {
  44869. snippet += `${builtin};\n`;
  44870. }
  44871. return snippet;
  44872. }
  44873. /**
  44874. * Returns the vertex index builtin.
  44875. *
  44876. * @return {string} The vertex index.
  44877. */
  44878. getVertexIndex() {
  44879. return 'uint( gl_VertexID )';
  44880. }
  44881. /**
  44882. * Contextually returns either the vertex stage instance index builtin
  44883. * or the linearized index of an compute invocation within a grid of workgroups.
  44884. *
  44885. * @return {string} The instance index.
  44886. */
  44887. getInstanceIndex() {
  44888. return 'uint( gl_InstanceID )';
  44889. }
  44890. /**
  44891. * Returns a builtin representing the index of an invocation within its workgroup.
  44892. *
  44893. * @return {string} The invocation local index.
  44894. */
  44895. getInvocationLocalIndex() {
  44896. const workgroupSize = this.object.workgroupSize;
  44897. const size = workgroupSize.reduce( ( acc, curr ) => acc * curr, 1 );
  44898. return `uint( gl_InstanceID ) % ${size}u`;
  44899. }
  44900. /**
  44901. * Returns a builtin representing the size of a subgroup within the current shader.
  44902. */
  44903. getSubgroupSize() {
  44904. error( 'GLSLNodeBuilder: WebGLBackend does not support the subgroupSize node' );
  44905. }
  44906. /**
  44907. * Returns a builtin representing the index of an invocation within its subgroup.
  44908. */
  44909. getInvocationSubgroupIndex() {
  44910. error( 'GLSLNodeBuilder: WebGLBackend does not support the invocationSubgroupIndex node' );
  44911. }
  44912. /**
  44913. * Returns a builtin representing the index of the current invocation's subgroup within its workgroup.
  44914. */
  44915. getSubgroupIndex() {
  44916. error( 'GLSLNodeBuilder: WebGLBackend does not support the subgroupIndex node' );
  44917. }
  44918. /**
  44919. * Returns the draw index builtin.
  44920. *
  44921. * @return {?string} The drawIndex shader string. Returns `null` if `WEBGL_multi_draw` isn't supported by the device.
  44922. */
  44923. getDrawIndex() {
  44924. const extensions = this.renderer.backend.extensions;
  44925. if ( extensions.has( 'WEBGL_multi_draw' ) ) {
  44926. return 'uint( gl_DrawID )';
  44927. }
  44928. return null;
  44929. }
  44930. /**
  44931. * Returns the front facing builtin.
  44932. *
  44933. * @return {string} The front facing builtin.
  44934. */
  44935. getFrontFacing() {
  44936. return 'gl_FrontFacing';
  44937. }
  44938. /**
  44939. * Returns the frag coord builtin.
  44940. *
  44941. * @return {string} The frag coord builtin.
  44942. */
  44943. getFragCoord() {
  44944. return 'gl_FragCoord.xy';
  44945. }
  44946. /**
  44947. * Returns the frag depth builtin.
  44948. *
  44949. * @return {string} The frag depth builtin.
  44950. */
  44951. getFragDepth() {
  44952. return 'gl_FragDepth';
  44953. }
  44954. /**
  44955. * Enables the given extension.
  44956. *
  44957. * @param {string} name - The extension name.
  44958. * @param {string} behavior - The extension behavior.
  44959. * @param {string} [shaderStage=this.shaderStage] - The shader stage.
  44960. */
  44961. enableExtension( name, behavior, shaderStage = this.shaderStage ) {
  44962. const map = this.extensions[ shaderStage ] || ( this.extensions[ shaderStage ] = new Map() );
  44963. if ( map.has( name ) === false ) {
  44964. map.set( name, {
  44965. name,
  44966. behavior
  44967. } );
  44968. }
  44969. }
  44970. /**
  44971. * Returns the enabled extensions of the given shader stage as a GLSL string.
  44972. *
  44973. * @param {string} shaderStage - The shader stage.
  44974. * @return {string} The GLSL snippet that defines the enabled extensions.
  44975. */
  44976. getExtensions( shaderStage ) {
  44977. const snippets = [];
  44978. if ( shaderStage === 'vertex' ) {
  44979. const ext = this.renderer.backend.extensions;
  44980. const isBatchedMesh = this.object.isBatchedMesh;
  44981. if ( isBatchedMesh && ext.has( 'WEBGL_multi_draw' ) ) {
  44982. this.enableExtension( 'GL_ANGLE_multi_draw', 'require', shaderStage );
  44983. }
  44984. }
  44985. const extensions = this.extensions[ shaderStage ];
  44986. if ( extensions !== undefined ) {
  44987. for ( const { name, behavior } of extensions.values() ) {
  44988. snippets.push( `#extension ${name} : ${behavior}` );
  44989. }
  44990. }
  44991. return snippets.join( '\n' );
  44992. }
  44993. /**
  44994. * Returns the clip distances builtin.
  44995. *
  44996. * @return {string} The clip distances builtin.
  44997. */
  44998. getClipDistance() {
  44999. return 'gl_ClipDistance';
  45000. }
  45001. /**
  45002. * Whether the requested feature is available or not.
  45003. *
  45004. * @param {string} name - The requested feature.
  45005. * @return {boolean} Whether the requested feature is supported or not.
  45006. */
  45007. isAvailable( name ) {
  45008. let result = supports$1[ name ];
  45009. if ( result === undefined ) {
  45010. let extensionName;
  45011. result = false;
  45012. switch ( name ) {
  45013. case 'float32Filterable':
  45014. extensionName = 'OES_texture_float_linear';
  45015. break;
  45016. case 'clipDistance':
  45017. extensionName = 'WEBGL_clip_cull_distance';
  45018. break;
  45019. }
  45020. if ( extensionName !== undefined ) {
  45021. const extensions = this.renderer.backend.extensions;
  45022. if ( extensions.has( extensionName ) ) {
  45023. extensions.get( extensionName );
  45024. result = true;
  45025. }
  45026. }
  45027. supports$1[ name ] = result;
  45028. }
  45029. return result;
  45030. }
  45031. /**
  45032. * Whether to flip texture data along its vertical axis or not.
  45033. *
  45034. * @return {boolean} Returns always `true` in context of GLSL.
  45035. */
  45036. isFlipY() {
  45037. return true;
  45038. }
  45039. /**
  45040. * Enables hardware clipping.
  45041. *
  45042. * @param {string} planeCount - The clipping plane count.
  45043. */
  45044. enableHardwareClipping( planeCount ) {
  45045. this.enableExtension( 'GL_ANGLE_clip_cull_distance', 'require' );
  45046. this.builtins[ 'vertex' ].push( `out float gl_ClipDistance[ ${ planeCount } ]` );
  45047. }
  45048. /**
  45049. * Enables multiview.
  45050. */
  45051. enableMultiview() {
  45052. this.enableExtension( 'GL_OVR_multiview2', 'require', 'fragment' );
  45053. this.enableExtension( 'GL_OVR_multiview2', 'require', 'vertex' );
  45054. this.builtins[ 'vertex' ].push( 'layout(num_views = 2) in' );
  45055. }
  45056. /**
  45057. * Registers a transform in context of Transform Feedback.
  45058. *
  45059. * @param {string} varyingName - The varying name.
  45060. * @param {AttributeNode} attributeNode - The attribute node.
  45061. */
  45062. registerTransform( varyingName, attributeNode ) {
  45063. this.transforms.push( { varyingName, attributeNode } );
  45064. }
  45065. /**
  45066. * Returns the transforms of the given shader stage as a GLSL string.
  45067. *
  45068. * @param {string} shaderStage - The shader stage.
  45069. * @return {string} The GLSL snippet that defines the transforms.
  45070. */
  45071. getTransforms( /* shaderStage */ ) {
  45072. const transforms = this.transforms;
  45073. let snippet = '';
  45074. for ( let i = 0; i < transforms.length; i ++ ) {
  45075. const transform = transforms[ i ];
  45076. const attributeName = this.getPropertyName( transform.attributeNode );
  45077. if ( attributeName ) snippet += `${ transform.varyingName } = ${ attributeName };\n\t`;
  45078. }
  45079. return snippet;
  45080. }
  45081. /**
  45082. * Returns a GLSL struct based on the given name and variables.
  45083. *
  45084. * @private
  45085. * @param {string} name - The struct name.
  45086. * @param {string} vars - The struct variables.
  45087. * @return {string} The GLSL snippet representing a struct.
  45088. */
  45089. _getGLSLUniformStruct( name, vars ) {
  45090. return `
  45091. layout( std140 ) uniform ${name} {
  45092. ${vars}
  45093. };`;
  45094. }
  45095. /**
  45096. * Returns a GLSL vertex shader based on the given shader data.
  45097. *
  45098. * @private
  45099. * @param {Object} shaderData - The shader data.
  45100. * @return {string} The vertex shader.
  45101. */
  45102. _getGLSLVertexCode( shaderData ) {
  45103. return `#version 300 es
  45104. ${ this.getSignature() }
  45105. // extensions
  45106. ${shaderData.extensions}
  45107. // precision
  45108. ${ defaultPrecisions }
  45109. // uniforms
  45110. ${shaderData.uniforms}
  45111. // varyings
  45112. ${shaderData.varyings}
  45113. // attributes
  45114. ${shaderData.attributes}
  45115. // codes
  45116. ${shaderData.codes}
  45117. void main() {
  45118. // vars
  45119. ${shaderData.vars}
  45120. // transforms
  45121. ${shaderData.transforms}
  45122. // flow
  45123. ${shaderData.flow}
  45124. gl_PointSize = 1.0;
  45125. }
  45126. `;
  45127. }
  45128. /**
  45129. * Returns a GLSL fragment shader based on the given shader data.
  45130. *
  45131. * @private
  45132. * @param {Object} shaderData - The shader data.
  45133. * @return {string} The vertex shader.
  45134. */
  45135. _getGLSLFragmentCode( shaderData ) {
  45136. return `#version 300 es
  45137. ${ this.getSignature() }
  45138. // extensions
  45139. ${shaderData.extensions}
  45140. // precision
  45141. ${ defaultPrecisions }
  45142. // structs
  45143. ${shaderData.structs}
  45144. // uniforms
  45145. ${shaderData.uniforms}
  45146. // varyings
  45147. ${shaderData.varyings}
  45148. // codes
  45149. ${shaderData.codes}
  45150. void main() {
  45151. // vars
  45152. ${shaderData.vars}
  45153. // flow
  45154. ${shaderData.flow}
  45155. }
  45156. `;
  45157. }
  45158. /**
  45159. * Controls the code build of the shader stages.
  45160. */
  45161. buildCode() {
  45162. const shadersData = this.material !== null ? { fragment: {}, vertex: {} } : { compute: {} };
  45163. this.sortBindingGroups();
  45164. for ( const shaderStage in shadersData ) {
  45165. let flow = '// code\n\n';
  45166. flow += this.flowCode[ shaderStage ];
  45167. const flowNodes = this.flowNodes[ shaderStage ];
  45168. const mainNode = flowNodes[ flowNodes.length - 1 ];
  45169. for ( const node of flowNodes ) {
  45170. const flowSlotData = this.getFlowData( node/*, shaderStage*/ );
  45171. const slotName = node.name;
  45172. if ( slotName ) {
  45173. if ( flow.length > 0 ) flow += '\n';
  45174. flow += `\t// flow -> ${ slotName }\n\t`;
  45175. }
  45176. flow += `${ flowSlotData.code }\n\t`;
  45177. if ( node === mainNode && shaderStage !== 'compute' ) {
  45178. flow += '// result\n\t';
  45179. if ( shaderStage === 'vertex' ) {
  45180. flow += 'gl_Position = ';
  45181. flow += `${ flowSlotData.result };`;
  45182. } else if ( shaderStage === 'fragment' ) {
  45183. if ( ! node.outputNode.isOutputStructNode ) {
  45184. flow += 'fragColor = ';
  45185. flow += `${ flowSlotData.result };`;
  45186. }
  45187. }
  45188. }
  45189. }
  45190. const stageData = shadersData[ shaderStage ];
  45191. stageData.extensions = this.getExtensions( shaderStage );
  45192. stageData.uniforms = this.getUniforms( shaderStage );
  45193. stageData.attributes = this.getAttributes( shaderStage );
  45194. stageData.varyings = this.getVaryings( shaderStage );
  45195. stageData.vars = this.getVars( shaderStage );
  45196. stageData.structs = this.getStructs( shaderStage );
  45197. stageData.codes = this.getCodes( shaderStage );
  45198. stageData.transforms = this.getTransforms( shaderStage );
  45199. stageData.flow = flow;
  45200. }
  45201. if ( this.material !== null ) {
  45202. this.vertexShader = this._getGLSLVertexCode( shadersData.vertex );
  45203. this.fragmentShader = this._getGLSLFragmentCode( shadersData.fragment );
  45204. } else {
  45205. this.computeShader = this._getGLSLVertexCode( shadersData.compute );
  45206. }
  45207. }
  45208. /**
  45209. * This method is one of the more important ones since it's responsible
  45210. * for generating a matching binding instance for the given uniform node.
  45211. *
  45212. * These bindings are later used in the renderer to create bind groups
  45213. * and layouts.
  45214. *
  45215. * @param {UniformNode} node - The uniform node.
  45216. * @param {string} type - The node data type.
  45217. * @param {string} shaderStage - The shader stage.
  45218. * @param {?string} [name=null] - An optional uniform name.
  45219. * @return {NodeUniform} The node uniform object.
  45220. */
  45221. getUniformFromNode( node, type, shaderStage, name = null ) {
  45222. const uniformNode = super.getUniformFromNode( node, type, shaderStage, name );
  45223. const nodeData = this.getDataFromNode( node, shaderStage, this.globalCache );
  45224. let uniformGPU = nodeData.uniformGPU;
  45225. if ( uniformGPU === undefined ) {
  45226. const group = node.groupNode;
  45227. const groupName = group.name;
  45228. const bindings = this.getBindGroupArray( groupName, shaderStage );
  45229. if ( type === 'texture' ) {
  45230. uniformGPU = new NodeSampledTexture( uniformNode.name, uniformNode.node, group );
  45231. bindings.push( uniformGPU );
  45232. } else if ( type === 'cubeTexture' || type === 'cubeDepthTexture' ) {
  45233. uniformGPU = new NodeSampledCubeTexture( uniformNode.name, uniformNode.node, group );
  45234. bindings.push( uniformGPU );
  45235. } else if ( type === 'texture3D' ) {
  45236. uniformGPU = new NodeSampledTexture3D( uniformNode.name, uniformNode.node, group );
  45237. bindings.push( uniformGPU );
  45238. } else if ( type === 'buffer' ) {
  45239. uniformNode.name = `buffer${ node.id }`;
  45240. const sharedData = this.getSharedDataFromNode( node );
  45241. let buffer = sharedData.buffer;
  45242. if ( buffer === undefined ) {
  45243. node.name = `NodeBuffer_${ node.id }`;
  45244. buffer = new NodeUniformBuffer( node, group );
  45245. buffer.name = node.name;
  45246. sharedData.buffer = buffer;
  45247. }
  45248. bindings.push( buffer );
  45249. uniformGPU = buffer;
  45250. } else {
  45251. const uniformsStage = this.uniformGroups[ shaderStage ] || ( this.uniformGroups[ shaderStage ] = {} );
  45252. let uniformsGroup = uniformsStage[ groupName ];
  45253. if ( uniformsGroup === undefined ) {
  45254. uniformsGroup = new NodeUniformsGroup( shaderStage + '_' + groupName, group );
  45255. //uniformsGroup.setVisibility( gpuShaderStageLib[ shaderStage ] );
  45256. uniformsStage[ groupName ] = uniformsGroup;
  45257. bindings.push( uniformsGroup );
  45258. }
  45259. uniformGPU = this.getNodeUniform( uniformNode, type );
  45260. uniformsGroup.addUniform( uniformGPU );
  45261. }
  45262. nodeData.uniformGPU = uniformGPU;
  45263. }
  45264. return uniformNode;
  45265. }
  45266. }
  45267. let _vector2 = null;
  45268. let _color4 = null;
  45269. /**
  45270. * Most of the rendering related logic is implemented in the
  45271. * {@link Renderer} module and related management components.
  45272. * Sometimes it is required though to execute commands which are
  45273. * specific to the current 3D backend (which is WebGPU or WebGL 2).
  45274. * This abstract base class defines an interface that encapsulates
  45275. * all backend-related logic. Derived classes for each backend must
  45276. * implement the interface.
  45277. *
  45278. * @abstract
  45279. * @private
  45280. */
  45281. class Backend {
  45282. /**
  45283. * Constructs a new backend.
  45284. *
  45285. * @param {Object} parameters - An object holding parameters for the backend.
  45286. */
  45287. constructor( parameters = {} ) {
  45288. /**
  45289. * The parameters of the backend.
  45290. *
  45291. * @type {Object}
  45292. */
  45293. this.parameters = Object.assign( {}, parameters );
  45294. /**
  45295. * This weak map holds backend-specific data of objects
  45296. * like textures, attributes or render targets.
  45297. *
  45298. * @type {WeakMap<Object, Object>}
  45299. */
  45300. this.data = new WeakMap();
  45301. /**
  45302. * A reference to the renderer.
  45303. *
  45304. * @type {?Renderer}
  45305. * @default null
  45306. */
  45307. this.renderer = null;
  45308. /**
  45309. * A reference to the canvas element the renderer is drawing to.
  45310. *
  45311. * @type {?(HTMLCanvasElement|OffscreenCanvas)}
  45312. * @default null
  45313. */
  45314. this.domElement = null;
  45315. /**
  45316. * A reference to the timestamp query pool.
  45317. *
  45318. * @type {{render: ?TimestampQueryPool, compute: ?TimestampQueryPool}}
  45319. */
  45320. this.timestampQueryPool = {
  45321. [ TimestampQuery.RENDER ]: null,
  45322. [ TimestampQuery.COMPUTE ]: null
  45323. };
  45324. /**
  45325. * Whether to track timestamps with a Timestamp Query API or not.
  45326. *
  45327. * @type {boolean}
  45328. * @default false
  45329. */
  45330. this.trackTimestamp = ( parameters.trackTimestamp === true );
  45331. }
  45332. /**
  45333. * Initializes the backend so it is ready for usage. Concrete backends
  45334. * are supposed to implement their rendering context creation and related
  45335. * operations in this method.
  45336. *
  45337. * @async
  45338. * @param {Renderer} renderer - The renderer.
  45339. * @return {Promise} A Promise that resolves when the backend has been initialized.
  45340. */
  45341. async init( renderer ) {
  45342. this.renderer = renderer;
  45343. }
  45344. /**
  45345. * The coordinate system of the backend.
  45346. *
  45347. * @abstract
  45348. * @type {number}
  45349. * @readonly
  45350. */
  45351. get coordinateSystem() {}
  45352. // render context
  45353. /**
  45354. * This method is executed at the beginning of a render call and
  45355. * can be used by the backend to prepare the state for upcoming
  45356. * draw calls.
  45357. *
  45358. * @abstract
  45359. * @param {RenderContext} renderContext - The render context.
  45360. */
  45361. beginRender( /*renderContext*/ ) {}
  45362. /**
  45363. * This method is executed at the end of a render call and
  45364. * can be used by the backend to finalize work after draw
  45365. * calls.
  45366. *
  45367. * @abstract
  45368. * @param {RenderContext} renderContext - The render context.
  45369. */
  45370. finishRender( /*renderContext*/ ) {}
  45371. /**
  45372. * This method is executed at the beginning of a compute call and
  45373. * can be used by the backend to prepare the state for upcoming
  45374. * compute tasks.
  45375. *
  45376. * @abstract
  45377. * @param {Node|Array<Node>} computeGroup - The compute node(s).
  45378. */
  45379. beginCompute( /*computeGroup*/ ) {}
  45380. /**
  45381. * This method is executed at the end of a compute call and
  45382. * can be used by the backend to finalize work after compute
  45383. * tasks.
  45384. *
  45385. * @abstract
  45386. * @param {Node|Array<Node>} computeGroup - The compute node(s).
  45387. */
  45388. finishCompute( /*computeGroup*/ ) {}
  45389. // render object
  45390. /**
  45391. * Executes a draw command for the given render object.
  45392. *
  45393. * @abstract
  45394. * @param {RenderObject} renderObject - The render object to draw.
  45395. * @param {Info} info - Holds a series of statistical information about the GPU memory and the rendering process.
  45396. */
  45397. draw( /*renderObject, info*/ ) { }
  45398. // compute node
  45399. /**
  45400. * Executes a compute command for the given compute node.
  45401. *
  45402. * @abstract
  45403. * @param {Node|Array<Node>} computeGroup - The group of compute nodes of a compute call. Can be a single compute node.
  45404. * @param {Node} computeNode - The compute node.
  45405. * @param {Array<BindGroup>} bindings - The bindings.
  45406. * @param {ComputePipeline} computePipeline - The compute pipeline.
  45407. */
  45408. compute( /*computeGroup, computeNode, computeBindings, computePipeline*/ ) { }
  45409. // program
  45410. /**
  45411. * Creates a shader program from the given programmable stage.
  45412. *
  45413. * @abstract
  45414. * @param {ProgrammableStage} program - The programmable stage.
  45415. */
  45416. createProgram( /*program*/ ) { }
  45417. /**
  45418. * Destroys the shader program of the given programmable stage.
  45419. *
  45420. * @abstract
  45421. * @param {ProgrammableStage} program - The programmable stage.
  45422. */
  45423. destroyProgram( /*program*/ ) { }
  45424. // bindings
  45425. /**
  45426. * Creates bindings from the given bind group definition.
  45427. *
  45428. * @abstract
  45429. * @param {BindGroup} bindGroup - The bind group.
  45430. * @param {Array<BindGroup>} bindings - Array of bind groups.
  45431. * @param {number} cacheIndex - The cache index.
  45432. * @param {number} version - The version.
  45433. */
  45434. createBindings( /*bindGroup, bindings, cacheIndex, version*/ ) { }
  45435. /**
  45436. * Updates the given bind group definition.
  45437. *
  45438. * @abstract
  45439. * @param {BindGroup} bindGroup - The bind group.
  45440. * @param {Array<BindGroup>} bindings - Array of bind groups.
  45441. * @param {number} cacheIndex - The cache index.
  45442. * @param {number} version - The version.
  45443. */
  45444. updateBindings( /*bindGroup, bindings, cacheIndex, version*/ ) { }
  45445. /**
  45446. * Updates a buffer binding.
  45447. *
  45448. * @abstract
  45449. * @param {Buffer} binding - The buffer binding to update.
  45450. */
  45451. updateBinding( /*binding*/ ) { }
  45452. // pipeline
  45453. /**
  45454. * Creates a render pipeline for the given render object.
  45455. *
  45456. * @abstract
  45457. * @param {RenderObject} renderObject - The render object.
  45458. * @param {Array<Promise>} promises - An array of compilation promises which are used in `compileAsync()`.
  45459. */
  45460. createRenderPipeline( /*renderObject, promises*/ ) { }
  45461. /**
  45462. * Creates a compute pipeline for the given compute node.
  45463. *
  45464. * @abstract
  45465. * @param {ComputePipeline} computePipeline - The compute pipeline.
  45466. * @param {Array<BindGroup>} bindings - The bindings.
  45467. */
  45468. createComputePipeline( /*computePipeline, bindings*/ ) { }
  45469. // cache key
  45470. /**
  45471. * Returns `true` if the render pipeline requires an update.
  45472. *
  45473. * @abstract
  45474. * @param {RenderObject} renderObject - The render object.
  45475. * @return {boolean} Whether the render pipeline requires an update or not.
  45476. */
  45477. needsRenderUpdate( /*renderObject*/ ) { }
  45478. /**
  45479. * Returns a cache key that is used to identify render pipelines.
  45480. *
  45481. * @abstract
  45482. * @param {RenderObject} renderObject - The render object.
  45483. * @return {string} The cache key.
  45484. */
  45485. getRenderCacheKey( /*renderObject*/ ) { }
  45486. // node builder
  45487. /**
  45488. * Returns a node builder for the given render object.
  45489. *
  45490. * @abstract
  45491. * @param {RenderObject} renderObject - The render object.
  45492. * @param {Renderer} renderer - The renderer.
  45493. * @return {NodeBuilder} The node builder.
  45494. */
  45495. createNodeBuilder( /*renderObject, renderer*/ ) { }
  45496. // textures
  45497. /**
  45498. * Updates a GPU sampler for the given texture.
  45499. *
  45500. * @abstract
  45501. * @param {Texture} texture - The texture to update the sampler for.
  45502. * @return {string} The current sampler key.
  45503. */
  45504. updateSampler( /*texture*/ ) { }
  45505. /**
  45506. * Creates a default texture for the given texture that can be used
  45507. * as a placeholder until the actual texture is ready for usage.
  45508. *
  45509. * @abstract
  45510. * @param {Texture} texture - The texture to create a default texture for.
  45511. */
  45512. createDefaultTexture( /*texture*/ ) { }
  45513. /**
  45514. * Defines a texture on the GPU for the given texture object.
  45515. *
  45516. * @abstract
  45517. * @param {Texture} texture - The texture.
  45518. * @param {Object} [options={}] - Optional configuration parameter.
  45519. */
  45520. createTexture( /*texture, options={}*/ ) { }
  45521. /**
  45522. * Uploads the updated texture data to the GPU.
  45523. *
  45524. * @abstract
  45525. * @param {Texture} texture - The texture.
  45526. * @param {Object} [options={}] - Optional configuration parameter.
  45527. */
  45528. updateTexture( /*texture, options = {}*/ ) { }
  45529. /**
  45530. * Generates mipmaps for the given texture.
  45531. *
  45532. * @abstract
  45533. * @param {Texture} texture - The texture.
  45534. */
  45535. generateMipmaps( /*texture*/ ) { }
  45536. /**
  45537. * Destroys the GPU data for the given texture object.
  45538. *
  45539. * @abstract
  45540. * @param {Texture} texture - The texture.
  45541. * @param {boolean} [isDefaultTexture=false] - Whether the texture uses a default GPU texture or not.
  45542. */
  45543. destroyTexture( /*texture, isDefaultTexture*/ ) { }
  45544. /**
  45545. * Returns texture data as a typed array.
  45546. *
  45547. * @abstract
  45548. * @async
  45549. * @param {Texture} texture - The texture to copy.
  45550. * @param {number} x - The x coordinate of the copy origin.
  45551. * @param {number} y - The y coordinate of the copy origin.
  45552. * @param {number} width - The width of the copy.
  45553. * @param {number} height - The height of the copy.
  45554. * @param {number} faceIndex - The face index.
  45555. * @return {Promise<TypedArray>} A Promise that resolves with a typed array when the copy operation has finished.
  45556. */
  45557. async copyTextureToBuffer( /*texture, x, y, width, height, faceIndex*/ ) {}
  45558. /**
  45559. * Copies data of the given source texture to the given destination texture.
  45560. *
  45561. * @abstract
  45562. * @param {Texture} srcTexture - The source texture.
  45563. * @param {Texture} dstTexture - The destination texture.
  45564. * @param {?(Box3|Box2)} [srcRegion=null] - The region of the source texture to copy.
  45565. * @param {?(Vector2|Vector3)} [dstPosition=null] - The destination position of the copy.
  45566. * @param {number} [srcLevel=0] - The source mip level to copy from.
  45567. * @param {number} [dstLevel=0] - The destination mip level to copy to.
  45568. */
  45569. copyTextureToTexture( /*srcTexture, dstTexture, srcRegion = null, dstPosition = null, srcLevel = 0, dstLevel = 0*/ ) {}
  45570. /**
  45571. * Copies the current bound framebuffer to the given texture.
  45572. *
  45573. * @abstract
  45574. * @param {Texture} texture - The destination texture.
  45575. * @param {RenderContext} renderContext - The render context.
  45576. * @param {Vector4} rectangle - A four dimensional vector defining the origin and dimension of the copy.
  45577. */
  45578. copyFramebufferToTexture( /*texture, renderContext, rectangle*/ ) {}
  45579. // attributes
  45580. /**
  45581. * Creates the GPU buffer of a shader attribute.
  45582. *
  45583. * @abstract
  45584. * @param {BufferAttribute} attribute - The buffer attribute.
  45585. */
  45586. createAttribute( /*attribute*/ ) { }
  45587. /**
  45588. * Creates the GPU buffer of an indexed shader attribute.
  45589. *
  45590. * @abstract
  45591. * @param {BufferAttribute} attribute - The indexed buffer attribute.
  45592. */
  45593. createIndexAttribute( /*attribute*/ ) { }
  45594. /**
  45595. * Creates the GPU buffer of a storage attribute.
  45596. *
  45597. * @abstract
  45598. * @param {BufferAttribute} attribute - The buffer attribute.
  45599. */
  45600. createStorageAttribute( /*attribute*/ ) { }
  45601. /**
  45602. * Updates the GPU buffer of a shader attribute.
  45603. *
  45604. * @abstract
  45605. * @param {BufferAttribute} attribute - The buffer attribute to update.
  45606. */
  45607. updateAttribute( /*attribute*/ ) { }
  45608. /**
  45609. * Destroys the GPU buffer of a shader attribute.
  45610. *
  45611. * @abstract
  45612. * @param {BufferAttribute} attribute - The buffer attribute to destroy.
  45613. */
  45614. destroyAttribute( /*attribute*/ ) { }
  45615. // canvas
  45616. /**
  45617. * Returns the backend's rendering context.
  45618. *
  45619. * @abstract
  45620. * @return {Object} The rendering context.
  45621. */
  45622. getContext() { }
  45623. /**
  45624. * Backends can use this method if they have to run
  45625. * logic when the renderer gets resized.
  45626. *
  45627. * @abstract
  45628. */
  45629. updateSize() { }
  45630. /**
  45631. * Updates the viewport with the values from the given render context.
  45632. *
  45633. * @abstract
  45634. * @param {RenderContext} renderContext - The render context.
  45635. */
  45636. updateViewport( /*renderContext*/ ) {}
  45637. // utils
  45638. /**
  45639. * Updates a unique identifier for the given render context that can be used
  45640. * to allocate resources like occlusion queries or timestamp queries.
  45641. *
  45642. * @param {RenderContext|ComputeNode} abstractRenderContext - The render context.
  45643. */
  45644. updateTimeStampUID( abstractRenderContext ) {
  45645. const contextData = this.get( abstractRenderContext );
  45646. const frame = this.renderer.info.frame;
  45647. let prefix;
  45648. if ( abstractRenderContext.isComputeNode === true ) {
  45649. prefix = 'c:' + this.renderer.info.compute.frameCalls;
  45650. } else {
  45651. prefix = 'r:' + this.renderer.info.render.frameCalls;
  45652. }
  45653. contextData.timestampUID = prefix + ':' + abstractRenderContext.id + ':f' + frame;
  45654. }
  45655. /**
  45656. * Returns a unique identifier for the given render context that can be used
  45657. * to allocate resources like occlusion queries or timestamp queries.
  45658. *
  45659. * @param {RenderContext|ComputeNode} abstractRenderContext - The render context.
  45660. * @return {string} The unique identifier.
  45661. */
  45662. getTimestampUID( abstractRenderContext ) {
  45663. return this.get( abstractRenderContext ).timestampUID;
  45664. }
  45665. /**
  45666. * Returns all timestamp frames for the given type.
  45667. *
  45668. * @param {string} type - The type of the time stamp.
  45669. * @return {Array<number>} The timestamp frames.
  45670. */
  45671. getTimestampFrames( type ) {
  45672. const queryPool = this.timestampQueryPool[ type ];
  45673. return queryPool ? queryPool.getTimestampFrames() : [];
  45674. }
  45675. /**
  45676. * Returns the query pool for the given uid.
  45677. *
  45678. * @param {string} uid - The unique identifier.
  45679. * @return {TimestampQueryPool} The query pool.
  45680. */
  45681. _getQueryPool( uid ) {
  45682. const type = uid.startsWith( 'c:' ) ? TimestampQuery.COMPUTE : TimestampQuery.RENDER;
  45683. const queryPool = this.timestampQueryPool[ type ];
  45684. return queryPool;
  45685. }
  45686. /**
  45687. * Returns the timestamp for the given uid.
  45688. *
  45689. * @param {string} uid - The unique identifier.
  45690. * @return {number} The timestamp.
  45691. */
  45692. getTimestamp( uid ) {
  45693. const queryPool = this._getQueryPool( uid );
  45694. return queryPool.getTimestamp( uid );
  45695. }
  45696. /**
  45697. * Returns `true` if a timestamp for the given uid is available.
  45698. *
  45699. * @param {string} uid - The unique identifier.
  45700. * @return {boolean} Whether the timestamp is available or not.
  45701. */
  45702. hasTimestamp( uid ) {
  45703. const queryPool = this._getQueryPool( uid );
  45704. return queryPool.hasTimestamp( uid );
  45705. }
  45706. /**
  45707. * Returns `true` if the given 3D object is fully occluded by other
  45708. * 3D objects in the scene. Backends must implement this method by using
  45709. * a Occlusion Query API.
  45710. *
  45711. * @abstract
  45712. * @param {RenderContext} renderContext - The render context.
  45713. * @param {Object3D} object - The 3D object to test.
  45714. * @return {boolean} Whether the 3D object is fully occluded or not.
  45715. */
  45716. isOccluded( /*renderContext, object*/ ) {}
  45717. /**
  45718. * Resolves the time stamp for the given render context and type.
  45719. *
  45720. * @async
  45721. * @abstract
  45722. * @param {string} [type='render'] - The type of the time stamp.
  45723. * @return {Promise<number>} A Promise that resolves with the time stamp.
  45724. */
  45725. async resolveTimestampsAsync( type = 'render' ) {
  45726. if ( ! this.trackTimestamp ) {
  45727. warnOnce( 'WebGPURenderer: Timestamp tracking is disabled.' );
  45728. return;
  45729. }
  45730. const queryPool = this.timestampQueryPool[ type ];
  45731. if ( ! queryPool ) {
  45732. return;
  45733. }
  45734. const duration = await queryPool.resolveQueriesAsync();
  45735. this.renderer.info[ type ].timestamp = duration;
  45736. return duration;
  45737. }
  45738. /**
  45739. * This method performs a readback operation by moving buffer data from
  45740. * a storage buffer attribute from the GPU to the CPU.
  45741. *
  45742. * @async
  45743. * @param {StorageBufferAttribute} attribute - The storage buffer attribute.
  45744. * @return {Promise<ArrayBuffer>} A promise that resolves with the buffer data when the data are ready.
  45745. */
  45746. async getArrayBufferAsync( /* attribute */ ) {}
  45747. /**
  45748. * Checks if the given feature is supported by the backend.
  45749. *
  45750. * @async
  45751. * @abstract
  45752. * @param {string} name - The feature's name.
  45753. * @return {Promise<boolean>} A Promise that resolves with a bool that indicates whether the feature is supported or not.
  45754. */
  45755. async hasFeatureAsync( /*name*/ ) { }
  45756. /**
  45757. * Checks if the given feature is supported by the backend.
  45758. *
  45759. * @abstract
  45760. * @param {string} name - The feature's name.
  45761. * @return {boolean} Whether the feature is supported or not.
  45762. */
  45763. hasFeature( /*name*/ ) {}
  45764. /**
  45765. * Returns the maximum anisotropy texture filtering value.
  45766. *
  45767. * @abstract
  45768. * @return {number} The maximum anisotropy texture filtering value.
  45769. */
  45770. getMaxAnisotropy() {}
  45771. /**
  45772. * Returns the drawing buffer size.
  45773. *
  45774. * @return {Vector2} The drawing buffer size.
  45775. */
  45776. getDrawingBufferSize() {
  45777. _vector2 = _vector2 || new Vector2();
  45778. return this.renderer.getDrawingBufferSize( _vector2 );
  45779. }
  45780. /**
  45781. * Defines the scissor test.
  45782. *
  45783. * @abstract
  45784. * @param {boolean} boolean - Whether the scissor test should be enabled or not.
  45785. */
  45786. setScissorTest( /*boolean*/ ) { }
  45787. /**
  45788. * Returns the clear color and alpha into a single
  45789. * color object.
  45790. *
  45791. * @return {Color4} The clear color.
  45792. */
  45793. getClearColor() {
  45794. const renderer = this.renderer;
  45795. _color4 = _color4 || new Color4();
  45796. renderer.getClearColor( _color4 );
  45797. _color4.getRGB( _color4 );
  45798. return _color4;
  45799. }
  45800. /**
  45801. * Returns the DOM element. If no DOM element exists, the backend
  45802. * creates a new one.
  45803. *
  45804. * @return {HTMLCanvasElement} The DOM element.
  45805. */
  45806. getDomElement() {
  45807. let domElement = this.domElement;
  45808. if ( domElement === null ) {
  45809. domElement = ( this.parameters.canvas !== undefined ) ? this.parameters.canvas : createCanvasElement();
  45810. // OffscreenCanvas does not have setAttribute, see #22811
  45811. if ( 'setAttribute' in domElement ) domElement.setAttribute( 'data-engine', `three.js r${REVISION} webgpu` );
  45812. this.domElement = domElement;
  45813. }
  45814. return domElement;
  45815. }
  45816. /**
  45817. * Sets a dictionary for the given object into the
  45818. * internal data structure.
  45819. *
  45820. * @param {Object} object - The object.
  45821. * @param {Object} value - The dictionary to set.
  45822. */
  45823. set( object, value ) {
  45824. this.data.set( object, value );
  45825. }
  45826. /**
  45827. * Returns the dictionary for the given object.
  45828. *
  45829. * @param {Object} object - The object.
  45830. * @return {Object} The object's dictionary.
  45831. */
  45832. get( object ) {
  45833. let map = this.data.get( object );
  45834. if ( map === undefined ) {
  45835. map = {};
  45836. this.data.set( object, map );
  45837. }
  45838. return map;
  45839. }
  45840. /**
  45841. * Checks if the given object has a dictionary
  45842. * with data defined.
  45843. *
  45844. * @param {Object} object - The object.
  45845. * @return {boolean} Whether a dictionary for the given object as been defined or not.
  45846. */
  45847. has( object ) {
  45848. return this.data.has( object );
  45849. }
  45850. /**
  45851. * Deletes an object from the internal data structure.
  45852. *
  45853. * @param {Object} object - The object to delete.
  45854. */
  45855. delete( object ) {
  45856. this.data.delete( object );
  45857. }
  45858. /**
  45859. * Delete GPU data associated with a bind group.
  45860. *
  45861. * @abstract
  45862. * @param {BindGroup} bindGroup - The bind group.
  45863. */
  45864. deleteBindGroupData( /*bindGroup*/ ) { }
  45865. /**
  45866. * Frees internal resources.
  45867. *
  45868. * @abstract
  45869. */
  45870. dispose() { }
  45871. }
  45872. let _id$1 = 0;
  45873. /**
  45874. * This module is internally used in context of compute shaders.
  45875. * This type of shader is not natively supported in WebGL 2 and
  45876. * thus implemented via Transform Feedback. `DualAttributeData`
  45877. * manages the related data.
  45878. *
  45879. * @private
  45880. */
  45881. class DualAttributeData {
  45882. constructor( attributeData, dualBuffer ) {
  45883. this.buffers = [ attributeData.bufferGPU, dualBuffer ];
  45884. this.type = attributeData.type;
  45885. this.bufferType = attributeData.bufferType;
  45886. this.pbo = attributeData.pbo;
  45887. this.byteLength = attributeData.byteLength;
  45888. this.bytesPerElement = attributeData.BYTES_PER_ELEMENT;
  45889. this.version = attributeData.version;
  45890. this.isInteger = attributeData.isInteger;
  45891. this.activeBufferIndex = 0;
  45892. this.baseId = attributeData.id;
  45893. }
  45894. get id() {
  45895. return `${ this.baseId }|${ this.activeBufferIndex }`;
  45896. }
  45897. get bufferGPU() {
  45898. return this.buffers[ this.activeBufferIndex ];
  45899. }
  45900. get transformBuffer() {
  45901. return this.buffers[ this.activeBufferIndex ^ 1 ];
  45902. }
  45903. switchBuffers() {
  45904. this.activeBufferIndex ^= 1;
  45905. }
  45906. }
  45907. /**
  45908. * A WebGL 2 backend utility module for managing shader attributes.
  45909. *
  45910. * @private
  45911. */
  45912. class WebGLAttributeUtils {
  45913. /**
  45914. * Constructs a new utility object.
  45915. *
  45916. * @param {WebGLBackend} backend - The WebGL 2 backend.
  45917. */
  45918. constructor( backend ) {
  45919. /**
  45920. * A reference to the WebGL 2 backend.
  45921. *
  45922. * @type {WebGLBackend}
  45923. */
  45924. this.backend = backend;
  45925. }
  45926. /**
  45927. * Creates the GPU buffer for the given buffer attribute.
  45928. *
  45929. * @param {BufferAttribute} attribute - The buffer attribute.
  45930. * @param {GLenum } bufferType - A flag that indicates the buffer type and thus binding point target.
  45931. */
  45932. createAttribute( attribute, bufferType ) {
  45933. const backend = this.backend;
  45934. const { gl } = backend;
  45935. const array = attribute.array;
  45936. const usage = attribute.usage || gl.STATIC_DRAW;
  45937. const bufferAttribute = attribute.isInterleavedBufferAttribute ? attribute.data : attribute;
  45938. const bufferData = backend.get( bufferAttribute );
  45939. let bufferGPU = bufferData.bufferGPU;
  45940. if ( bufferGPU === undefined ) {
  45941. bufferGPU = this._createBuffer( gl, bufferType, array, usage );
  45942. bufferData.bufferGPU = bufferGPU;
  45943. bufferData.bufferType = bufferType;
  45944. bufferData.version = bufferAttribute.version;
  45945. }
  45946. //attribute.onUploadCallback();
  45947. let type;
  45948. if ( array instanceof Float32Array ) {
  45949. type = gl.FLOAT;
  45950. } else if ( typeof Float16Array !== 'undefined' && array instanceof Float16Array ) {
  45951. type = gl.HALF_FLOAT;
  45952. } else if ( array instanceof Uint16Array ) {
  45953. if ( attribute.isFloat16BufferAttribute ) {
  45954. type = gl.HALF_FLOAT;
  45955. } else {
  45956. type = gl.UNSIGNED_SHORT;
  45957. }
  45958. } else if ( array instanceof Int16Array ) {
  45959. type = gl.SHORT;
  45960. } else if ( array instanceof Uint32Array ) {
  45961. type = gl.UNSIGNED_INT;
  45962. } else if ( array instanceof Int32Array ) {
  45963. type = gl.INT;
  45964. } else if ( array instanceof Int8Array ) {
  45965. type = gl.BYTE;
  45966. } else if ( array instanceof Uint8Array ) {
  45967. type = gl.UNSIGNED_BYTE;
  45968. } else if ( array instanceof Uint8ClampedArray ) {
  45969. type = gl.UNSIGNED_BYTE;
  45970. } else {
  45971. throw new Error( 'THREE.WebGLBackend: Unsupported buffer data format: ' + array );
  45972. }
  45973. let attributeData = {
  45974. bufferGPU,
  45975. bufferType,
  45976. type,
  45977. byteLength: array.byteLength,
  45978. bytesPerElement: array.BYTES_PER_ELEMENT,
  45979. version: attribute.version,
  45980. pbo: attribute.pbo,
  45981. isInteger: type === gl.INT || type === gl.UNSIGNED_INT || attribute.gpuType === IntType,
  45982. id: _id$1 ++
  45983. };
  45984. if ( attribute.isStorageBufferAttribute || attribute.isStorageInstancedBufferAttribute ) {
  45985. // create buffer for transform feedback use
  45986. const bufferGPUDual = this._createBuffer( gl, bufferType, array, usage );
  45987. attributeData = new DualAttributeData( attributeData, bufferGPUDual );
  45988. }
  45989. backend.set( attribute, attributeData );
  45990. }
  45991. /**
  45992. * Updates the GPU buffer of the given buffer attribute.
  45993. *
  45994. * @param {BufferAttribute} attribute - The buffer attribute.
  45995. */
  45996. updateAttribute( attribute ) {
  45997. const backend = this.backend;
  45998. const { gl } = backend;
  45999. const array = attribute.array;
  46000. const bufferAttribute = attribute.isInterleavedBufferAttribute ? attribute.data : attribute;
  46001. const bufferData = backend.get( bufferAttribute );
  46002. const bufferType = bufferData.bufferType;
  46003. const updateRanges = attribute.isInterleavedBufferAttribute ? attribute.data.updateRanges : attribute.updateRanges;
  46004. gl.bindBuffer( bufferType, bufferData.bufferGPU );
  46005. if ( updateRanges.length === 0 ) {
  46006. // Not using update ranges
  46007. gl.bufferSubData( bufferType, 0, array );
  46008. } else {
  46009. for ( let i = 0, l = updateRanges.length; i < l; i ++ ) {
  46010. const range = updateRanges[ i ];
  46011. gl.bufferSubData( bufferType, range.start * array.BYTES_PER_ELEMENT,
  46012. array, range.start, range.count );
  46013. }
  46014. bufferAttribute.clearUpdateRanges();
  46015. }
  46016. gl.bindBuffer( bufferType, null );
  46017. bufferData.version = bufferAttribute.version;
  46018. }
  46019. /**
  46020. * Destroys the GPU buffer of the given buffer attribute.
  46021. *
  46022. * @param {BufferAttribute} attribute - The buffer attribute.
  46023. */
  46024. destroyAttribute( attribute ) {
  46025. const backend = this.backend;
  46026. const { gl } = backend;
  46027. if ( attribute.isInterleavedBufferAttribute ) {
  46028. backend.delete( attribute.data );
  46029. }
  46030. const attributeData = backend.get( attribute );
  46031. gl.deleteBuffer( attributeData.bufferGPU );
  46032. backend.delete( attribute );
  46033. }
  46034. /**
  46035. * This method performs a readback operation by moving buffer data from
  46036. * a storage buffer attribute from the GPU to the CPU.
  46037. *
  46038. * @async
  46039. * @param {StorageBufferAttribute} attribute - The storage buffer attribute.
  46040. * @return {Promise<ArrayBuffer>} A promise that resolves with the buffer data when the data are ready.
  46041. */
  46042. async getArrayBufferAsync( attribute ) {
  46043. const backend = this.backend;
  46044. const { gl } = backend;
  46045. const bufferAttribute = attribute.isInterleavedBufferAttribute ? attribute.data : attribute;
  46046. const { bufferGPU } = backend.get( bufferAttribute );
  46047. const array = attribute.array;
  46048. const byteLength = array.byteLength;
  46049. gl.bindBuffer( gl.COPY_READ_BUFFER, bufferGPU );
  46050. const writeBuffer = gl.createBuffer();
  46051. gl.bindBuffer( gl.COPY_WRITE_BUFFER, writeBuffer );
  46052. gl.bufferData( gl.COPY_WRITE_BUFFER, byteLength, gl.STREAM_READ );
  46053. gl.copyBufferSubData( gl.COPY_READ_BUFFER, gl.COPY_WRITE_BUFFER, 0, 0, byteLength );
  46054. await backend.utils._clientWaitAsync();
  46055. const dstBuffer = new attribute.array.constructor( array.length );
  46056. // Ensure the buffer is bound before reading
  46057. gl.bindBuffer( gl.COPY_WRITE_BUFFER, writeBuffer );
  46058. gl.getBufferSubData( gl.COPY_WRITE_BUFFER, 0, dstBuffer );
  46059. gl.deleteBuffer( writeBuffer );
  46060. gl.bindBuffer( gl.COPY_READ_BUFFER, null );
  46061. gl.bindBuffer( gl.COPY_WRITE_BUFFER, null );
  46062. return dstBuffer.buffer;
  46063. }
  46064. /**
  46065. * Creates a WebGL buffer with the given data.
  46066. *
  46067. * @private
  46068. * @param {WebGL2RenderingContext} gl - The rendering context.
  46069. * @param {GLenum } bufferType - A flag that indicates the buffer type and thus binding point target.
  46070. * @param {TypedArray} array - The array of the buffer attribute.
  46071. * @param {GLenum} usage - The usage.
  46072. * @return {WebGLBuffer} The WebGL buffer.
  46073. */
  46074. _createBuffer( gl, bufferType, array, usage ) {
  46075. const bufferGPU = gl.createBuffer();
  46076. gl.bindBuffer( bufferType, bufferGPU );
  46077. gl.bufferData( bufferType, array, usage );
  46078. gl.bindBuffer( bufferType, null );
  46079. return bufferGPU;
  46080. }
  46081. }
  46082. let equationToGL, factorToGL;
  46083. /**
  46084. * A WebGL 2 backend utility module for managing the WebGL state.
  46085. *
  46086. * The major goal of this module is to reduce the number of state changes
  46087. * by caching the WEbGL state with a series of variables. In this way, the
  46088. * renderer only executes state change commands when necessary which
  46089. * improves the overall performance.
  46090. *
  46091. * @private
  46092. */
  46093. class WebGLState {
  46094. /**
  46095. * Constructs a new utility object.
  46096. *
  46097. * @param {WebGLBackend} backend - The WebGL 2 backend.
  46098. */
  46099. constructor( backend ) {
  46100. /**
  46101. * A reference to the WebGL 2 backend.
  46102. *
  46103. * @type {WebGLBackend}
  46104. */
  46105. this.backend = backend;
  46106. /**
  46107. * A reference to the rendering context.
  46108. *
  46109. * @type {WebGL2RenderingContext}
  46110. */
  46111. this.gl = this.backend.gl;
  46112. // Below properties are intended to cache
  46113. // the WebGL state and are not explicitly
  46114. // documented for convenience reasons.
  46115. this.enabled = {};
  46116. this.currentFlipSided = null;
  46117. this.currentCullFace = null;
  46118. this.currentProgram = null;
  46119. this.currentBlendingEnabled = false;
  46120. this.currentBlending = null;
  46121. this.currentBlendSrc = null;
  46122. this.currentBlendDst = null;
  46123. this.currentBlendSrcAlpha = null;
  46124. this.currentBlendDstAlpha = null;
  46125. this.currentPremultipledAlpha = null;
  46126. this.currentPolygonOffsetFactor = null;
  46127. this.currentPolygonOffsetUnits = null;
  46128. this.currentColorMask = null;
  46129. this.currentDepthFunc = null;
  46130. this.currentDepthMask = null;
  46131. this.currentStencilFunc = null;
  46132. this.currentStencilRef = null;
  46133. this.currentStencilFuncMask = null;
  46134. this.currentStencilFail = null;
  46135. this.currentStencilZFail = null;
  46136. this.currentStencilZPass = null;
  46137. this.currentStencilMask = null;
  46138. this.currentLineWidth = null;
  46139. this.currentClippingPlanes = 0;
  46140. this.currentVAO = null;
  46141. this.currentIndex = null;
  46142. this.currentBoundFramebuffers = {};
  46143. this.currentDrawbuffers = new WeakMap();
  46144. this.maxTextures = this.gl.getParameter( this.gl.MAX_TEXTURE_IMAGE_UNITS );
  46145. this.currentTextureSlot = null;
  46146. this.currentBoundTextures = {};
  46147. this.currentBoundBufferBases = {};
  46148. this._init();
  46149. }
  46150. /**
  46151. * Inits the state of the utility.
  46152. *
  46153. * @private
  46154. */
  46155. _init() {
  46156. const gl = this.gl;
  46157. // Store only WebGL constants here.
  46158. equationToGL = {
  46159. [ AddEquation ]: gl.FUNC_ADD,
  46160. [ SubtractEquation ]: gl.FUNC_SUBTRACT,
  46161. [ ReverseSubtractEquation ]: gl.FUNC_REVERSE_SUBTRACT
  46162. };
  46163. factorToGL = {
  46164. [ ZeroFactor ]: gl.ZERO,
  46165. [ OneFactor ]: gl.ONE,
  46166. [ SrcColorFactor ]: gl.SRC_COLOR,
  46167. [ SrcAlphaFactor ]: gl.SRC_ALPHA,
  46168. [ SrcAlphaSaturateFactor ]: gl.SRC_ALPHA_SATURATE,
  46169. [ DstColorFactor ]: gl.DST_COLOR,
  46170. [ DstAlphaFactor ]: gl.DST_ALPHA,
  46171. [ OneMinusSrcColorFactor ]: gl.ONE_MINUS_SRC_COLOR,
  46172. [ OneMinusSrcAlphaFactor ]: gl.ONE_MINUS_SRC_ALPHA,
  46173. [ OneMinusDstColorFactor ]: gl.ONE_MINUS_DST_COLOR,
  46174. [ OneMinusDstAlphaFactor ]: gl.ONE_MINUS_DST_ALPHA
  46175. };
  46176. const scissorParam = gl.getParameter( gl.SCISSOR_BOX );
  46177. const viewportParam = gl.getParameter( gl.VIEWPORT );
  46178. this.currentScissor = new Vector4().fromArray( scissorParam );
  46179. this.currentViewport = new Vector4().fromArray( viewportParam );
  46180. this._tempVec4 = new Vector4();
  46181. }
  46182. /**
  46183. * Enables the given WebGL capability.
  46184. *
  46185. * This method caches the capability state so
  46186. * `gl.enable()` is only called when necessary.
  46187. *
  46188. * @param {GLenum} id - The capability to enable.
  46189. */
  46190. enable( id ) {
  46191. const { enabled } = this;
  46192. if ( enabled[ id ] !== true ) {
  46193. this.gl.enable( id );
  46194. enabled[ id ] = true;
  46195. }
  46196. }
  46197. /**
  46198. * Disables the given WebGL capability.
  46199. *
  46200. * This method caches the capability state so
  46201. * `gl.disable()` is only called when necessary.
  46202. *
  46203. * @param {GLenum} id - The capability to enable.
  46204. */
  46205. disable( id ) {
  46206. const { enabled } = this;
  46207. if ( enabled[ id ] !== false ) {
  46208. this.gl.disable( id );
  46209. enabled[ id ] = false;
  46210. }
  46211. }
  46212. /**
  46213. * Specifies whether polygons are front- or back-facing
  46214. * by setting the winding orientation.
  46215. *
  46216. * This method caches the state so `gl.frontFace()` is only
  46217. * called when necessary.
  46218. *
  46219. * @param {boolean} flipSided - Whether triangles flipped their sides or not.
  46220. */
  46221. setFlipSided( flipSided ) {
  46222. if ( this.currentFlipSided !== flipSided ) {
  46223. const { gl } = this;
  46224. if ( flipSided ) {
  46225. gl.frontFace( gl.CW );
  46226. } else {
  46227. gl.frontFace( gl.CCW );
  46228. }
  46229. this.currentFlipSided = flipSided;
  46230. }
  46231. }
  46232. /**
  46233. * Specifies whether or not front- and/or back-facing
  46234. * polygons can be culled.
  46235. *
  46236. * This method caches the state so `gl.cullFace()` is only
  46237. * called when necessary.
  46238. *
  46239. * @param {number} cullFace - Defines which polygons are candidates for culling.
  46240. */
  46241. setCullFace( cullFace ) {
  46242. const { gl } = this;
  46243. if ( cullFace !== CullFaceNone ) {
  46244. this.enable( gl.CULL_FACE );
  46245. if ( cullFace !== this.currentCullFace ) {
  46246. if ( cullFace === CullFaceBack ) {
  46247. gl.cullFace( gl.BACK );
  46248. } else if ( cullFace === CullFaceFront ) {
  46249. gl.cullFace( gl.FRONT );
  46250. } else {
  46251. gl.cullFace( gl.FRONT_AND_BACK );
  46252. }
  46253. }
  46254. } else {
  46255. this.disable( gl.CULL_FACE );
  46256. }
  46257. this.currentCullFace = cullFace;
  46258. }
  46259. /**
  46260. * Specifies the width of line primitives.
  46261. *
  46262. * This method caches the state so `gl.lineWidth()` is only
  46263. * called when necessary.
  46264. *
  46265. * @param {number} width - The line width.
  46266. */
  46267. setLineWidth( width ) {
  46268. const { currentLineWidth, gl } = this;
  46269. if ( width !== currentLineWidth ) {
  46270. gl.lineWidth( width );
  46271. this.currentLineWidth = width;
  46272. }
  46273. }
  46274. setMRTBlending( textures ) {
  46275. const gl = this.gl;
  46276. const drawBuffersIndexedExt = this.backend.drawBuffersIndexedExt;
  46277. if ( ! drawBuffersIndexedExt ) return;
  46278. for ( let i = 1; i < textures.length; i ++ ) {
  46279. // use opaque blending for additional render targets
  46280. drawBuffersIndexedExt.blendFuncSeparateiOES( i, gl.ONE, gl.ZERO, gl.ONE, gl.ZERO );
  46281. }
  46282. }
  46283. /**
  46284. * Defines the blending.
  46285. *
  46286. * This method caches the state so `gl.blendEquation()`, `gl.blendEquationSeparate()`,
  46287. * `gl.blendFunc()` and `gl.blendFuncSeparate()` are only called when necessary.
  46288. *
  46289. * @param {number} blending - The blending type.
  46290. * @param {number} blendEquation - The blending equation.
  46291. * @param {number} blendSrc - Only relevant for custom blending. The RGB source blending factor.
  46292. * @param {number} blendDst - Only relevant for custom blending. The RGB destination blending factor.
  46293. * @param {number} blendEquationAlpha - Only relevant for custom blending. The blending equation for alpha.
  46294. * @param {number} blendSrcAlpha - Only relevant for custom blending. The alpha source blending factor.
  46295. * @param {number} blendDstAlpha - Only relevant for custom blending. The alpha destination blending factor.
  46296. * @param {boolean} premultipliedAlpha - Whether premultiplied alpha is enabled or not.
  46297. */
  46298. setBlending( blending, blendEquation, blendSrc, blendDst, blendEquationAlpha, blendSrcAlpha, blendDstAlpha, premultipliedAlpha ) {
  46299. const { gl } = this;
  46300. if ( blending === NoBlending ) {
  46301. if ( this.currentBlendingEnabled === true ) {
  46302. this.disable( gl.BLEND );
  46303. this.currentBlendingEnabled = false;
  46304. }
  46305. return;
  46306. }
  46307. if ( this.currentBlendingEnabled === false ) {
  46308. this.enable( gl.BLEND );
  46309. this.currentBlendingEnabled = true;
  46310. }
  46311. if ( blending !== CustomBlending ) {
  46312. if ( blending !== this.currentBlending || premultipliedAlpha !== this.currentPremultipledAlpha ) {
  46313. if ( this.currentBlendEquation !== AddEquation || this.currentBlendEquationAlpha !== AddEquation ) {
  46314. gl.blendEquation( gl.FUNC_ADD );
  46315. this.currentBlendEquation = AddEquation;
  46316. this.currentBlendEquationAlpha = AddEquation;
  46317. }
  46318. if ( premultipliedAlpha ) {
  46319. switch ( blending ) {
  46320. case NormalBlending:
  46321. gl.blendFuncSeparate( gl.ONE, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA );
  46322. break;
  46323. case AdditiveBlending:
  46324. gl.blendFunc( gl.ONE, gl.ONE );
  46325. break;
  46326. case SubtractiveBlending:
  46327. gl.blendFuncSeparate( gl.ZERO, gl.ONE_MINUS_SRC_COLOR, gl.ZERO, gl.ONE );
  46328. break;
  46329. case MultiplyBlending:
  46330. gl.blendFuncSeparate( gl.DST_COLOR, gl.ONE_MINUS_SRC_ALPHA, gl.ZERO, gl.ONE );
  46331. break;
  46332. default:
  46333. error( 'WebGLState: Invalid blending: ', blending );
  46334. break;
  46335. }
  46336. } else {
  46337. switch ( blending ) {
  46338. case NormalBlending:
  46339. gl.blendFuncSeparate( gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA );
  46340. break;
  46341. case AdditiveBlending:
  46342. gl.blendFuncSeparate( gl.SRC_ALPHA, gl.ONE, gl.ONE, gl.ONE );
  46343. break;
  46344. case SubtractiveBlending:
  46345. error( 'WebGLState: SubtractiveBlending requires material.premultipliedAlpha = true' );
  46346. break;
  46347. case MultiplyBlending:
  46348. error( 'WebGLState: MultiplyBlending requires material.premultipliedAlpha = true' );
  46349. break;
  46350. default:
  46351. error( 'WebGLState: Invalid blending: ', blending );
  46352. break;
  46353. }
  46354. }
  46355. this.currentBlendSrc = null;
  46356. this.currentBlendDst = null;
  46357. this.currentBlendSrcAlpha = null;
  46358. this.currentBlendDstAlpha = null;
  46359. this.currentBlending = blending;
  46360. this.currentPremultipledAlpha = premultipliedAlpha;
  46361. }
  46362. return;
  46363. }
  46364. // custom blending
  46365. blendEquationAlpha = blendEquationAlpha || blendEquation;
  46366. blendSrcAlpha = blendSrcAlpha || blendSrc;
  46367. blendDstAlpha = blendDstAlpha || blendDst;
  46368. if ( blendEquation !== this.currentBlendEquation || blendEquationAlpha !== this.currentBlendEquationAlpha ) {
  46369. gl.blendEquationSeparate( equationToGL[ blendEquation ], equationToGL[ blendEquationAlpha ] );
  46370. this.currentBlendEquation = blendEquation;
  46371. this.currentBlendEquationAlpha = blendEquationAlpha;
  46372. }
  46373. if ( blendSrc !== this.currentBlendSrc || blendDst !== this.currentBlendDst || blendSrcAlpha !== this.currentBlendSrcAlpha || blendDstAlpha !== this.currentBlendDstAlpha ) {
  46374. gl.blendFuncSeparate( factorToGL[ blendSrc ], factorToGL[ blendDst ], factorToGL[ blendSrcAlpha ], factorToGL[ blendDstAlpha ] );
  46375. this.currentBlendSrc = blendSrc;
  46376. this.currentBlendDst = blendDst;
  46377. this.currentBlendSrcAlpha = blendSrcAlpha;
  46378. this.currentBlendDstAlpha = blendDstAlpha;
  46379. }
  46380. this.currentBlending = blending;
  46381. this.currentPremultipledAlpha = false;
  46382. }
  46383. /**
  46384. * Specifies whether colors can be written when rendering
  46385. * into a framebuffer or not.
  46386. *
  46387. * This method caches the state so `gl.colorMask()` is only
  46388. * called when necessary.
  46389. *
  46390. * @param {boolean} colorMask - The color mask.
  46391. */
  46392. setColorMask( colorMask ) {
  46393. if ( this.currentColorMask !== colorMask ) {
  46394. this.gl.colorMask( colorMask, colorMask, colorMask, colorMask );
  46395. this.currentColorMask = colorMask;
  46396. }
  46397. }
  46398. /**
  46399. * Specifies whether the depth test is enabled or not.
  46400. *
  46401. * @param {boolean} depthTest - Whether the depth test is enabled or not.
  46402. */
  46403. setDepthTest( depthTest ) {
  46404. const { gl } = this;
  46405. if ( depthTest ) {
  46406. this.enable( gl.DEPTH_TEST );
  46407. } else {
  46408. this.disable( gl.DEPTH_TEST );
  46409. }
  46410. }
  46411. /**
  46412. * Specifies whether depth values can be written when rendering
  46413. * into a framebuffer or not.
  46414. *
  46415. * This method caches the state so `gl.depthMask()` is only
  46416. * called when necessary.
  46417. *
  46418. * @param {boolean} depthMask - The depth mask.
  46419. */
  46420. setDepthMask( depthMask ) {
  46421. if ( this.currentDepthMask !== depthMask ) {
  46422. this.gl.depthMask( depthMask );
  46423. this.currentDepthMask = depthMask;
  46424. }
  46425. }
  46426. /**
  46427. * Specifies the depth compare function.
  46428. *
  46429. * This method caches the state so `gl.depthFunc()` is only
  46430. * called when necessary.
  46431. *
  46432. * @param {number} depthFunc - The depth compare function.
  46433. */
  46434. setDepthFunc( depthFunc ) {
  46435. if ( this.currentDepthFunc !== depthFunc ) {
  46436. const { gl } = this;
  46437. switch ( depthFunc ) {
  46438. case NeverDepth:
  46439. gl.depthFunc( gl.NEVER );
  46440. break;
  46441. case AlwaysDepth:
  46442. gl.depthFunc( gl.ALWAYS );
  46443. break;
  46444. case LessDepth:
  46445. gl.depthFunc( gl.LESS );
  46446. break;
  46447. case LessEqualDepth:
  46448. gl.depthFunc( gl.LEQUAL );
  46449. break;
  46450. case EqualDepth:
  46451. gl.depthFunc( gl.EQUAL );
  46452. break;
  46453. case GreaterEqualDepth:
  46454. gl.depthFunc( gl.GEQUAL );
  46455. break;
  46456. case GreaterDepth:
  46457. gl.depthFunc( gl.GREATER );
  46458. break;
  46459. case NotEqualDepth:
  46460. gl.depthFunc( gl.NOTEQUAL );
  46461. break;
  46462. default:
  46463. gl.depthFunc( gl.LEQUAL );
  46464. }
  46465. this.currentDepthFunc = depthFunc;
  46466. }
  46467. }
  46468. /**
  46469. * Specifies the scissor box.
  46470. *
  46471. * @param {number} x - The x-coordinate of the lower left corner of the viewport.
  46472. * @param {number} y - The y-coordinate of the lower left corner of the viewport.
  46473. * @param {number} width - The width of the viewport.
  46474. * @param {number} height - The height of the viewport.
  46475. *
  46476. */
  46477. scissor( x, y, width, height ) {
  46478. const scissor = this._tempVec4.set( x, y, width, height );
  46479. if ( this.currentScissor.equals( scissor ) === false ) {
  46480. const { gl } = this;
  46481. gl.scissor( scissor.x, scissor.y, scissor.z, scissor.w );
  46482. this.currentScissor.copy( scissor );
  46483. }
  46484. }
  46485. /**
  46486. * Specifies the viewport.
  46487. *
  46488. * @param {number} x - The x-coordinate of the lower left corner of the viewport.
  46489. * @param {number} y - The y-coordinate of the lower left corner of the viewport.
  46490. * @param {number} width - The width of the viewport.
  46491. * @param {number} height - The height of the viewport.
  46492. *
  46493. */
  46494. viewport( x, y, width, height ) {
  46495. const viewport = this._tempVec4.set( x, y, width, height );
  46496. if ( this.currentViewport.equals( viewport ) === false ) {
  46497. const { gl } = this;
  46498. gl.viewport( viewport.x, viewport.y, viewport.z, viewport.w );
  46499. this.currentViewport.copy( viewport );
  46500. }
  46501. }
  46502. /**
  46503. * Defines the scissor test.
  46504. *
  46505. * @param {boolean} boolean - Whether the scissor test should be enabled or not.
  46506. */
  46507. setScissorTest( boolean ) {
  46508. const gl = this.gl;
  46509. if ( boolean ) {
  46510. this.enable( gl.SCISSOR_TEST );
  46511. } else {
  46512. this.disable( gl.SCISSOR_TEST );
  46513. }
  46514. }
  46515. /**
  46516. * Specifies whether the stencil test is enabled or not.
  46517. *
  46518. * @param {boolean} stencilTest - Whether the stencil test is enabled or not.
  46519. */
  46520. setStencilTest( stencilTest ) {
  46521. const { gl } = this;
  46522. if ( stencilTest ) {
  46523. this.enable( gl.STENCIL_TEST );
  46524. } else {
  46525. this.disable( gl.STENCIL_TEST );
  46526. }
  46527. }
  46528. /**
  46529. * Specifies whether stencil values can be written when rendering
  46530. * into a framebuffer or not.
  46531. *
  46532. * This method caches the state so `gl.stencilMask()` is only
  46533. * called when necessary.
  46534. *
  46535. * @param {boolean} stencilMask - The stencil mask.
  46536. */
  46537. setStencilMask( stencilMask ) {
  46538. if ( this.currentStencilMask !== stencilMask ) {
  46539. this.gl.stencilMask( stencilMask );
  46540. this.currentStencilMask = stencilMask;
  46541. }
  46542. }
  46543. /**
  46544. * Specifies whether the stencil test functions.
  46545. *
  46546. * This method caches the state so `gl.stencilFunc()` is only
  46547. * called when necessary.
  46548. *
  46549. * @param {number} stencilFunc - The stencil compare function.
  46550. * @param {number} stencilRef - The reference value for the stencil test.
  46551. * @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.
  46552. */
  46553. setStencilFunc( stencilFunc, stencilRef, stencilMask ) {
  46554. if ( this.currentStencilFunc !== stencilFunc ||
  46555. this.currentStencilRef !== stencilRef ||
  46556. this.currentStencilFuncMask !== stencilMask ) {
  46557. this.gl.stencilFunc( stencilFunc, stencilRef, stencilMask );
  46558. this.currentStencilFunc = stencilFunc;
  46559. this.currentStencilRef = stencilRef;
  46560. this.currentStencilFuncMask = stencilMask;
  46561. }
  46562. }
  46563. /**
  46564. * Specifies whether the stencil test operation.
  46565. *
  46566. * This method caches the state so `gl.stencilOp()` is only
  46567. * called when necessary.
  46568. *
  46569. * @param {number} stencilFail - The function to use when the stencil test fails.
  46570. * @param {number} stencilZFail - The function to use when the stencil test passes, but the depth test fail.
  46571. * @param {number} stencilZPass - The function to use when both the stencil test and the depth test pass,
  46572. * or when the stencil test passes and there is no depth buffer or depth testing is disabled.
  46573. */
  46574. setStencilOp( stencilFail, stencilZFail, stencilZPass ) {
  46575. if ( this.currentStencilFail !== stencilFail ||
  46576. this.currentStencilZFail !== stencilZFail ||
  46577. this.currentStencilZPass !== stencilZPass ) {
  46578. this.gl.stencilOp( stencilFail, stencilZFail, stencilZPass );
  46579. this.currentStencilFail = stencilFail;
  46580. this.currentStencilZFail = stencilZFail;
  46581. this.currentStencilZPass = stencilZPass;
  46582. }
  46583. }
  46584. /**
  46585. * Configures the WebGL state for the given material.
  46586. *
  46587. * @param {Material} material - The material to configure the state for.
  46588. * @param {number} frontFaceCW - Whether the front faces are counter-clockwise or not.
  46589. * @param {number} hardwareClippingPlanes - The number of hardware clipping planes.
  46590. */
  46591. setMaterial( material, frontFaceCW, hardwareClippingPlanes ) {
  46592. const { gl } = this;
  46593. material.side === DoubleSide
  46594. ? this.disable( gl.CULL_FACE )
  46595. : this.enable( gl.CULL_FACE );
  46596. let flipSided = ( material.side === BackSide );
  46597. if ( frontFaceCW ) flipSided = ! flipSided;
  46598. this.setFlipSided( flipSided );
  46599. ( material.blending === NormalBlending && material.transparent === false )
  46600. ? this.setBlending( NoBlending )
  46601. : this.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst, material.blendEquationAlpha, material.blendSrcAlpha, material.blendDstAlpha, material.premultipliedAlpha );
  46602. this.setDepthFunc( material.depthFunc );
  46603. this.setDepthTest( material.depthTest );
  46604. this.setDepthMask( material.depthWrite );
  46605. this.setColorMask( material.colorWrite );
  46606. const stencilWrite = material.stencilWrite;
  46607. this.setStencilTest( stencilWrite );
  46608. if ( stencilWrite ) {
  46609. this.setStencilMask( material.stencilWriteMask );
  46610. this.setStencilFunc( material.stencilFunc, material.stencilRef, material.stencilFuncMask );
  46611. this.setStencilOp( material.stencilFail, material.stencilZFail, material.stencilZPass );
  46612. }
  46613. this.setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits );
  46614. material.alphaToCoverage === true && this.backend.renderer.currentSamples > 0
  46615. ? this.enable( gl.SAMPLE_ALPHA_TO_COVERAGE )
  46616. : this.disable( gl.SAMPLE_ALPHA_TO_COVERAGE );
  46617. if ( hardwareClippingPlanes > 0 ) {
  46618. if ( this.currentClippingPlanes !== hardwareClippingPlanes ) {
  46619. const CLIP_DISTANCE0_WEBGL = 0x3000;
  46620. for ( let i = 0; i < 8; i ++ ) {
  46621. if ( i < hardwareClippingPlanes ) {
  46622. this.enable( CLIP_DISTANCE0_WEBGL + i );
  46623. } else {
  46624. this.disable( CLIP_DISTANCE0_WEBGL + i );
  46625. }
  46626. }
  46627. }
  46628. }
  46629. }
  46630. /**
  46631. * Specifies the polygon offset.
  46632. *
  46633. * This method caches the state so `gl.polygonOffset()` is only
  46634. * called when necessary.
  46635. *
  46636. * @param {boolean} polygonOffset - Whether polygon offset is enabled or not.
  46637. * @param {number} factor - The scale factor for the variable depth offset for each polygon.
  46638. * @param {number} units - The multiplier by which an implementation-specific value is multiplied with to create a constant depth offset.
  46639. */
  46640. setPolygonOffset( polygonOffset, factor, units ) {
  46641. const { gl } = this;
  46642. if ( polygonOffset ) {
  46643. this.enable( gl.POLYGON_OFFSET_FILL );
  46644. if ( this.currentPolygonOffsetFactor !== factor || this.currentPolygonOffsetUnits !== units ) {
  46645. gl.polygonOffset( factor, units );
  46646. this.currentPolygonOffsetFactor = factor;
  46647. this.currentPolygonOffsetUnits = units;
  46648. }
  46649. } else {
  46650. this.disable( gl.POLYGON_OFFSET_FILL );
  46651. }
  46652. }
  46653. /**
  46654. * Defines the usage of the given WebGL program.
  46655. *
  46656. * This method caches the state so `gl.useProgram()` is only
  46657. * called when necessary.
  46658. *
  46659. * @param {WebGLProgram} program - The WebGL program to use.
  46660. * @return {boolean} Whether a program change has been executed or not.
  46661. */
  46662. useProgram( program ) {
  46663. if ( this.currentProgram !== program ) {
  46664. this.gl.useProgram( program );
  46665. this.currentProgram = program;
  46666. return true;
  46667. }
  46668. return false;
  46669. }
  46670. /**
  46671. * Sets the vertex state by binding the given VAO and element buffer.
  46672. *
  46673. * @param {WebGLVertexArrayObject} vao - The VAO.
  46674. * @param {?WebGLBuffer} indexBuffer - The index buffer.
  46675. * @return {boolean} Whether a vertex state has been changed or not.
  46676. */
  46677. setVertexState( vao, indexBuffer = null ) {
  46678. const gl = this.gl;
  46679. if ( this.currentVAO !== vao || this.currentIndex !== indexBuffer ) {
  46680. gl.bindVertexArray( vao );
  46681. if ( indexBuffer !== null ) {
  46682. gl.bindBuffer( gl.ELEMENT_ARRAY_BUFFER, indexBuffer );
  46683. }
  46684. this.currentVAO = vao;
  46685. this.currentIndex = indexBuffer;
  46686. return true;
  46687. }
  46688. return false;
  46689. }
  46690. /**
  46691. * Resets the vertex array state by resetting the VAO and element buffer.
  46692. */
  46693. resetVertexState() {
  46694. const gl = this.gl;
  46695. gl.bindVertexArray( null );
  46696. gl.bindBuffer( gl.ELEMENT_ARRAY_BUFFER, null );
  46697. this.currentVAO = null;
  46698. this.currentIndex = null;
  46699. }
  46700. // framebuffer
  46701. /**
  46702. * Binds the given framebuffer.
  46703. *
  46704. * This method caches the state so `gl.bindFramebuffer()` is only
  46705. * called when necessary.
  46706. *
  46707. * @param {number} target - The binding point (target).
  46708. * @param {WebGLFramebuffer} framebuffer - The WebGL framebuffer to bind.
  46709. * @return {boolean} Whether a bind has been executed or not.
  46710. */
  46711. bindFramebuffer( target, framebuffer ) {
  46712. const { gl, currentBoundFramebuffers } = this;
  46713. if ( currentBoundFramebuffers[ target ] !== framebuffer ) {
  46714. gl.bindFramebuffer( target, framebuffer );
  46715. currentBoundFramebuffers[ target ] = framebuffer;
  46716. // gl.DRAW_FRAMEBUFFER is equivalent to gl.FRAMEBUFFER
  46717. if ( target === gl.DRAW_FRAMEBUFFER ) {
  46718. currentBoundFramebuffers[ gl.FRAMEBUFFER ] = framebuffer;
  46719. }
  46720. if ( target === gl.FRAMEBUFFER ) {
  46721. currentBoundFramebuffers[ gl.DRAW_FRAMEBUFFER ] = framebuffer;
  46722. }
  46723. return true;
  46724. }
  46725. return false;
  46726. }
  46727. /**
  46728. * Defines draw buffers to which fragment colors are written into.
  46729. * Configures the MRT setup of custom framebuffers.
  46730. *
  46731. * This method caches the state so `gl.drawBuffers()` is only
  46732. * called when necessary.
  46733. *
  46734. * @param {RenderContext} renderContext - The render context.
  46735. * @param {WebGLFramebuffer} framebuffer - The WebGL framebuffer.
  46736. */
  46737. drawBuffers( renderContext, framebuffer ) {
  46738. const { gl } = this;
  46739. let drawBuffers = [];
  46740. let needsUpdate = false;
  46741. if ( renderContext.textures !== null ) {
  46742. drawBuffers = this.currentDrawbuffers.get( framebuffer );
  46743. if ( drawBuffers === undefined ) {
  46744. drawBuffers = [];
  46745. this.currentDrawbuffers.set( framebuffer, drawBuffers );
  46746. }
  46747. const textures = renderContext.textures;
  46748. if ( drawBuffers.length !== textures.length || drawBuffers[ 0 ] !== gl.COLOR_ATTACHMENT0 ) {
  46749. for ( let i = 0, il = textures.length; i < il; i ++ ) {
  46750. drawBuffers[ i ] = gl.COLOR_ATTACHMENT0 + i;
  46751. }
  46752. drawBuffers.length = textures.length;
  46753. needsUpdate = true;
  46754. }
  46755. } else {
  46756. if ( drawBuffers[ 0 ] !== gl.BACK ) {
  46757. drawBuffers[ 0 ] = gl.BACK;
  46758. needsUpdate = true;
  46759. }
  46760. }
  46761. if ( needsUpdate ) {
  46762. gl.drawBuffers( drawBuffers );
  46763. }
  46764. }
  46765. // texture
  46766. /**
  46767. * Makes the given texture unit active.
  46768. *
  46769. * This method caches the state so `gl.activeTexture()` is only
  46770. * called when necessary.
  46771. *
  46772. * @param {number} webglSlot - The texture unit to make active.
  46773. */
  46774. activeTexture( webglSlot ) {
  46775. const { gl, currentTextureSlot, maxTextures } = this;
  46776. if ( webglSlot === undefined ) webglSlot = gl.TEXTURE0 + maxTextures - 1;
  46777. if ( currentTextureSlot !== webglSlot ) {
  46778. gl.activeTexture( webglSlot );
  46779. this.currentTextureSlot = webglSlot;
  46780. }
  46781. }
  46782. /**
  46783. * Binds the given WebGL texture to a target.
  46784. *
  46785. * This method caches the state so `gl.bindTexture()` is only
  46786. * called when necessary.
  46787. *
  46788. * @param {number} webglType - The binding point (target).
  46789. * @param {WebGLTexture} webglTexture - The WebGL texture to bind.
  46790. * @param {number} webglSlot - The texture.
  46791. */
  46792. bindTexture( webglType, webglTexture, webglSlot ) {
  46793. const { gl, currentTextureSlot, currentBoundTextures, maxTextures } = this;
  46794. if ( webglSlot === undefined ) {
  46795. if ( currentTextureSlot === null ) {
  46796. webglSlot = gl.TEXTURE0 + maxTextures - 1;
  46797. } else {
  46798. webglSlot = currentTextureSlot;
  46799. }
  46800. }
  46801. let boundTexture = currentBoundTextures[ webglSlot ];
  46802. if ( boundTexture === undefined ) {
  46803. boundTexture = { type: undefined, texture: undefined };
  46804. currentBoundTextures[ webglSlot ] = boundTexture;
  46805. }
  46806. if ( boundTexture.type !== webglType || boundTexture.texture !== webglTexture ) {
  46807. if ( currentTextureSlot !== webglSlot ) {
  46808. gl.activeTexture( webglSlot );
  46809. this.currentTextureSlot = webglSlot;
  46810. }
  46811. gl.bindTexture( webglType, webglTexture );
  46812. boundTexture.type = webglType;
  46813. boundTexture.texture = webglTexture;
  46814. }
  46815. }
  46816. /**
  46817. * Binds a given WebGL buffer to a given binding point (target) at a given index.
  46818. *
  46819. * This method caches the state so `gl.bindBufferBase()` is only
  46820. * called when necessary.
  46821. *
  46822. * @param {number} target - The target for the bind operation.
  46823. * @param {number} index - The index of the target.
  46824. * @param {WebGLBuffer} buffer - The WebGL buffer.
  46825. * @return {boolean} Whether a bind has been executed or not.
  46826. */
  46827. bindBufferBase( target, index, buffer ) {
  46828. const { gl } = this;
  46829. const key = `${target}-${index}`;
  46830. if ( this.currentBoundBufferBases[ key ] !== buffer ) {
  46831. gl.bindBufferBase( target, index, buffer );
  46832. this.currentBoundBufferBases[ key ] = buffer;
  46833. return true;
  46834. }
  46835. return false;
  46836. }
  46837. /**
  46838. * Unbinds the current bound texture.
  46839. *
  46840. * This method caches the state so `gl.bindTexture()` is only
  46841. * called when necessary.
  46842. */
  46843. unbindTexture() {
  46844. const { gl, currentTextureSlot, currentBoundTextures } = this;
  46845. const boundTexture = currentBoundTextures[ currentTextureSlot ];
  46846. if ( boundTexture !== undefined && boundTexture.type !== undefined ) {
  46847. gl.bindTexture( boundTexture.type, null );
  46848. boundTexture.type = undefined;
  46849. boundTexture.texture = undefined;
  46850. }
  46851. }
  46852. }
  46853. /**
  46854. * A WebGL 2 backend utility module with common helpers.
  46855. *
  46856. * @private
  46857. */
  46858. class WebGLUtils {
  46859. /**
  46860. * Constructs a new utility object.
  46861. *
  46862. * @param {WebGLBackend} backend - The WebGL 2 backend.
  46863. */
  46864. constructor( backend ) {
  46865. /**
  46866. * A reference to the WebGL 2 backend.
  46867. *
  46868. * @type {WebGLBackend}
  46869. */
  46870. this.backend = backend;
  46871. /**
  46872. * A reference to the rendering context.
  46873. *
  46874. * @type {WebGL2RenderingContext}
  46875. */
  46876. this.gl = this.backend.gl;
  46877. /**
  46878. * A reference to a backend module holding extension-related
  46879. * utility functions.
  46880. *
  46881. * @type {WebGLExtensions}
  46882. */
  46883. this.extensions = backend.extensions;
  46884. }
  46885. /**
  46886. * Converts the given three.js constant into a WebGL constant.
  46887. * The method currently supports the conversion of texture formats
  46888. * and types.
  46889. *
  46890. * @param {number} p - The three.js constant.
  46891. * @param {string} [colorSpace=NoColorSpace] - The color space.
  46892. * @return {?number} The corresponding WebGL constant.
  46893. */
  46894. convert( p, colorSpace = NoColorSpace ) {
  46895. const { gl, extensions } = this;
  46896. let extension;
  46897. const transfer = ColorManagement.getTransfer( colorSpace );
  46898. if ( p === UnsignedByteType ) return gl.UNSIGNED_BYTE;
  46899. if ( p === UnsignedShort4444Type ) return gl.UNSIGNED_SHORT_4_4_4_4;
  46900. if ( p === UnsignedShort5551Type ) return gl.UNSIGNED_SHORT_5_5_5_1;
  46901. if ( p === UnsignedInt5999Type ) return gl.UNSIGNED_INT_5_9_9_9_REV;
  46902. if ( p === UnsignedInt101111Type ) return gl.UNSIGNED_INT_10F_11F_11F_REV;
  46903. if ( p === ByteType ) return gl.BYTE;
  46904. if ( p === ShortType ) return gl.SHORT;
  46905. if ( p === UnsignedShortType ) return gl.UNSIGNED_SHORT;
  46906. if ( p === IntType ) return gl.INT;
  46907. if ( p === UnsignedIntType ) return gl.UNSIGNED_INT;
  46908. if ( p === FloatType ) return gl.FLOAT;
  46909. if ( p === HalfFloatType ) {
  46910. return gl.HALF_FLOAT;
  46911. }
  46912. if ( p === AlphaFormat ) return gl.ALPHA;
  46913. if ( p === RGBFormat ) return gl.RGB;
  46914. if ( p === RGBAFormat ) return gl.RGBA;
  46915. if ( p === DepthFormat ) return gl.DEPTH_COMPONENT;
  46916. if ( p === DepthStencilFormat ) return gl.DEPTH_STENCIL;
  46917. // WebGL2 formats.
  46918. if ( p === RedFormat ) return gl.RED;
  46919. if ( p === RedIntegerFormat ) return gl.RED_INTEGER;
  46920. if ( p === RGFormat ) return gl.RG;
  46921. if ( p === RGIntegerFormat ) return gl.RG_INTEGER;
  46922. if ( p === RGBAIntegerFormat ) return gl.RGBA_INTEGER;
  46923. // S3TC
  46924. if ( p === RGB_S3TC_DXT1_Format || p === RGBA_S3TC_DXT1_Format || p === RGBA_S3TC_DXT3_Format || p === RGBA_S3TC_DXT5_Format ) {
  46925. if ( transfer === SRGBTransfer ) {
  46926. extension = extensions.get( 'WEBGL_compressed_texture_s3tc_srgb' );
  46927. if ( extension !== null ) {
  46928. if ( p === RGB_S3TC_DXT1_Format ) return extension.COMPRESSED_SRGB_S3TC_DXT1_EXT;
  46929. if ( p === RGBA_S3TC_DXT1_Format ) return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT;
  46930. if ( p === RGBA_S3TC_DXT3_Format ) return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT;
  46931. if ( p === RGBA_S3TC_DXT5_Format ) return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT;
  46932. } else {
  46933. return null;
  46934. }
  46935. } else {
  46936. extension = extensions.get( 'WEBGL_compressed_texture_s3tc' );
  46937. if ( extension !== null ) {
  46938. if ( p === RGB_S3TC_DXT1_Format ) return extension.COMPRESSED_RGB_S3TC_DXT1_EXT;
  46939. if ( p === RGBA_S3TC_DXT1_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  46940. if ( p === RGBA_S3TC_DXT3_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  46941. if ( p === RGBA_S3TC_DXT5_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  46942. } else {
  46943. return null;
  46944. }
  46945. }
  46946. }
  46947. // PVRTC
  46948. if ( p === RGB_PVRTC_4BPPV1_Format || p === RGB_PVRTC_2BPPV1_Format || p === RGBA_PVRTC_4BPPV1_Format || p === RGBA_PVRTC_2BPPV1_Format ) {
  46949. extension = extensions.get( 'WEBGL_compressed_texture_pvrtc' );
  46950. if ( extension !== null ) {
  46951. if ( p === RGB_PVRTC_4BPPV1_Format ) return extension.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;
  46952. if ( p === RGB_PVRTC_2BPPV1_Format ) return extension.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;
  46953. if ( p === RGBA_PVRTC_4BPPV1_Format ) return extension.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;
  46954. if ( p === RGBA_PVRTC_2BPPV1_Format ) return extension.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG;
  46955. } else {
  46956. return null;
  46957. }
  46958. }
  46959. // ETC
  46960. if ( p === RGB_ETC1_Format || p === RGB_ETC2_Format || p === RGBA_ETC2_EAC_Format || p === R11_EAC_Format || p === SIGNED_R11_EAC_Format || p === RG11_EAC_Format || p === SIGNED_RG11_EAC_Format ) {
  46961. extension = extensions.get( 'WEBGL_compressed_texture_etc' );
  46962. if ( extension !== null ) {
  46963. if ( p === RGB_ETC1_Format || p === RGB_ETC2_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ETC2 : extension.COMPRESSED_RGB8_ETC2;
  46964. if ( p === RGBA_ETC2_EAC_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC : extension.COMPRESSED_RGBA8_ETC2_EAC;
  46965. if ( p === R11_EAC_Format ) return extension.COMPRESSED_R11_EAC;
  46966. if ( p === SIGNED_R11_EAC_Format ) return extension.COMPRESSED_SIGNED_R11_EAC;
  46967. if ( p === RG11_EAC_Format ) return extension.COMPRESSED_RG11_EAC;
  46968. if ( p === SIGNED_RG11_EAC_Format ) return extension.COMPRESSED_SIGNED_RG11_EAC;
  46969. } else {
  46970. return null;
  46971. }
  46972. }
  46973. // ASTC
  46974. if ( p === RGBA_ASTC_4x4_Format || p === RGBA_ASTC_5x4_Format || p === RGBA_ASTC_5x5_Format ||
  46975. p === RGBA_ASTC_6x5_Format || p === RGBA_ASTC_6x6_Format || p === RGBA_ASTC_8x5_Format ||
  46976. p === RGBA_ASTC_8x6_Format || p === RGBA_ASTC_8x8_Format || p === RGBA_ASTC_10x5_Format ||
  46977. p === RGBA_ASTC_10x6_Format || p === RGBA_ASTC_10x8_Format || p === RGBA_ASTC_10x10_Format ||
  46978. p === RGBA_ASTC_12x10_Format || p === RGBA_ASTC_12x12_Format ) {
  46979. extension = extensions.get( 'WEBGL_compressed_texture_astc' );
  46980. if ( extension !== null ) {
  46981. if ( p === RGBA_ASTC_4x4_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR : extension.COMPRESSED_RGBA_ASTC_4x4_KHR;
  46982. if ( p === RGBA_ASTC_5x4_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR : extension.COMPRESSED_RGBA_ASTC_5x4_KHR;
  46983. if ( p === RGBA_ASTC_5x5_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR : extension.COMPRESSED_RGBA_ASTC_5x5_KHR;
  46984. if ( p === RGBA_ASTC_6x5_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR : extension.COMPRESSED_RGBA_ASTC_6x5_KHR;
  46985. if ( p === RGBA_ASTC_6x6_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR : extension.COMPRESSED_RGBA_ASTC_6x6_KHR;
  46986. if ( p === RGBA_ASTC_8x5_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR : extension.COMPRESSED_RGBA_ASTC_8x5_KHR;
  46987. if ( p === RGBA_ASTC_8x6_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR : extension.COMPRESSED_RGBA_ASTC_8x6_KHR;
  46988. if ( p === RGBA_ASTC_8x8_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR : extension.COMPRESSED_RGBA_ASTC_8x8_KHR;
  46989. if ( p === RGBA_ASTC_10x5_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR : extension.COMPRESSED_RGBA_ASTC_10x5_KHR;
  46990. if ( p === RGBA_ASTC_10x6_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR : extension.COMPRESSED_RGBA_ASTC_10x6_KHR;
  46991. if ( p === RGBA_ASTC_10x8_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR : extension.COMPRESSED_RGBA_ASTC_10x8_KHR;
  46992. if ( p === RGBA_ASTC_10x10_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR : extension.COMPRESSED_RGBA_ASTC_10x10_KHR;
  46993. if ( p === RGBA_ASTC_12x10_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR : extension.COMPRESSED_RGBA_ASTC_12x10_KHR;
  46994. if ( p === RGBA_ASTC_12x12_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR : extension.COMPRESSED_RGBA_ASTC_12x12_KHR;
  46995. } else {
  46996. return null;
  46997. }
  46998. }
  46999. // BPTC
  47000. if ( p === RGBA_BPTC_Format ) {
  47001. extension = extensions.get( 'EXT_texture_compression_bptc' );
  47002. if ( extension !== null ) {
  47003. if ( p === RGBA_BPTC_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT : extension.COMPRESSED_RGBA_BPTC_UNORM_EXT;
  47004. } else {
  47005. return null;
  47006. }
  47007. }
  47008. // RGTC
  47009. if ( p === RED_RGTC1_Format || p === SIGNED_RED_RGTC1_Format || p === RED_GREEN_RGTC2_Format || p === SIGNED_RED_GREEN_RGTC2_Format ) {
  47010. extension = extensions.get( 'EXT_texture_compression_rgtc' );
  47011. if ( extension !== null ) {
  47012. if ( p === RED_RGTC1_Format ) return extension.COMPRESSED_RED_RGTC1_EXT;
  47013. if ( p === SIGNED_RED_RGTC1_Format ) return extension.COMPRESSED_SIGNED_RED_RGTC1_EXT;
  47014. if ( p === RED_GREEN_RGTC2_Format ) return extension.COMPRESSED_RED_GREEN_RGTC2_EXT;
  47015. if ( p === SIGNED_RED_GREEN_RGTC2_Format ) return extension.COMPRESSED_SIGNED_RED_GREEN_RGTC2_EXT;
  47016. } else {
  47017. return null;
  47018. }
  47019. }
  47020. //
  47021. if ( p === UnsignedInt248Type ) {
  47022. return gl.UNSIGNED_INT_24_8;
  47023. }
  47024. // if "p" can't be resolved, assume the user defines a WebGL constant as a string (fallback/workaround for packed RGB formats)
  47025. return ( gl[ p ] !== undefined ) ? gl[ p ] : null;
  47026. }
  47027. /**
  47028. * This method can be used to synchronize the CPU with the GPU by waiting until
  47029. * ongoing GPU commands have been completed.
  47030. *
  47031. * @private
  47032. * @return {Promise} A promise that resolves when all ongoing GPU commands have been completed.
  47033. */
  47034. _clientWaitAsync() {
  47035. const { gl } = this;
  47036. const sync = gl.fenceSync( gl.SYNC_GPU_COMMANDS_COMPLETE, 0 );
  47037. gl.flush();
  47038. return new Promise( ( resolve, reject ) => {
  47039. function test() {
  47040. const res = gl.clientWaitSync( sync, gl.SYNC_FLUSH_COMMANDS_BIT, 0 );
  47041. if ( res === gl.WAIT_FAILED ) {
  47042. gl.deleteSync( sync );
  47043. reject();
  47044. return;
  47045. }
  47046. if ( res === gl.TIMEOUT_EXPIRED ) {
  47047. requestAnimationFrame( test );
  47048. return;
  47049. }
  47050. gl.deleteSync( sync );
  47051. resolve();
  47052. }
  47053. test();
  47054. } );
  47055. }
  47056. }
  47057. let initialized = false, wrappingToGL, filterToGL, compareToGL;
  47058. /**
  47059. * A WebGL 2 backend utility module for managing textures.
  47060. *
  47061. * @private
  47062. */
  47063. class WebGLTextureUtils {
  47064. /**
  47065. * Constructs a new utility object.
  47066. *
  47067. * @param {WebGLBackend} backend - The WebGL 2 backend.
  47068. */
  47069. constructor( backend ) {
  47070. /**
  47071. * A reference to the WebGL 2 backend.
  47072. *
  47073. * @type {WebGLBackend}
  47074. */
  47075. this.backend = backend;
  47076. /**
  47077. * A reference to the rendering context.
  47078. *
  47079. * @type {WebGL2RenderingContext}
  47080. */
  47081. this.gl = backend.gl;
  47082. /**
  47083. * A reference to a backend module holding extension-related
  47084. * utility functions.
  47085. *
  47086. * @type {WebGLExtensions}
  47087. */
  47088. this.extensions = backend.extensions;
  47089. /**
  47090. * A dictionary for managing default textures. The key
  47091. * is the binding point (target), the value the WEbGL texture object.
  47092. *
  47093. * @type {Object<GLenum,WebGLTexture>}
  47094. */
  47095. this.defaultTextures = {};
  47096. /**
  47097. * A scratch framebuffer used for attaching the source texture in
  47098. * {@link copyTextureToTexture}.
  47099. *
  47100. * @private
  47101. * @type {?WebGLFramebuffer}
  47102. */
  47103. this._srcFramebuffer = null;
  47104. /**
  47105. * A scratch framebuffer used for attaching the destination texture in
  47106. * {@link copyTextureToTexture}.
  47107. *
  47108. * @private
  47109. * @type {?WebGLFramebuffer}
  47110. */
  47111. this._dstFramebuffer = null;
  47112. if ( initialized === false ) {
  47113. this._init();
  47114. initialized = true;
  47115. }
  47116. }
  47117. /**
  47118. * Inits the state of the utility.
  47119. *
  47120. * @private
  47121. */
  47122. _init() {
  47123. const gl = this.gl;
  47124. // Store only WebGL constants here.
  47125. wrappingToGL = {
  47126. [ RepeatWrapping ]: gl.REPEAT,
  47127. [ ClampToEdgeWrapping ]: gl.CLAMP_TO_EDGE,
  47128. [ MirroredRepeatWrapping ]: gl.MIRRORED_REPEAT
  47129. };
  47130. filterToGL = {
  47131. [ NearestFilter ]: gl.NEAREST,
  47132. [ NearestMipmapNearestFilter ]: gl.NEAREST_MIPMAP_NEAREST,
  47133. [ NearestMipmapLinearFilter ]: gl.NEAREST_MIPMAP_LINEAR,
  47134. [ LinearFilter ]: gl.LINEAR,
  47135. [ LinearMipmapNearestFilter ]: gl.LINEAR_MIPMAP_NEAREST,
  47136. [ LinearMipmapLinearFilter ]: gl.LINEAR_MIPMAP_LINEAR
  47137. };
  47138. compareToGL = {
  47139. [ NeverCompare ]: gl.NEVER,
  47140. [ AlwaysCompare ]: gl.ALWAYS,
  47141. [ LessCompare ]: gl.LESS,
  47142. [ LessEqualCompare ]: gl.LEQUAL,
  47143. [ EqualCompare ]: gl.EQUAL,
  47144. [ GreaterEqualCompare ]: gl.GEQUAL,
  47145. [ GreaterCompare ]: gl.GREATER,
  47146. [ NotEqualCompare ]: gl.NOTEQUAL
  47147. };
  47148. }
  47149. /**
  47150. * Returns the native texture type for the given texture.
  47151. *
  47152. * @param {Texture} texture - The texture.
  47153. * @return {GLenum} The native texture type.
  47154. */
  47155. getGLTextureType( texture ) {
  47156. const { gl } = this;
  47157. let glTextureType;
  47158. if ( texture.isCubeTexture === true ) {
  47159. glTextureType = gl.TEXTURE_CUBE_MAP;
  47160. } else if ( texture.isArrayTexture === true || texture.isDataArrayTexture === true || texture.isCompressedArrayTexture === true ) {
  47161. glTextureType = gl.TEXTURE_2D_ARRAY;
  47162. } else if ( texture.isData3DTexture === true ) { // TODO: isCompressed3DTexture, wait for #26642
  47163. glTextureType = gl.TEXTURE_3D;
  47164. } else {
  47165. glTextureType = gl.TEXTURE_2D;
  47166. }
  47167. return glTextureType;
  47168. }
  47169. /**
  47170. * Returns the native texture type for the given texture.
  47171. *
  47172. * @param {?string} internalFormatName - The internal format name. When `null`, the internal format is derived from the subsequent parameters.
  47173. * @param {GLenum} glFormat - The WebGL format.
  47174. * @param {GLenum} glType - The WebGL type.
  47175. * @param {string} colorSpace - The texture's color space.
  47176. * @param {boolean} [forceLinearTransfer=false] - Whether to force a linear transfer or not.
  47177. * @return {GLenum} The internal format.
  47178. */
  47179. getInternalFormat( internalFormatName, glFormat, glType, colorSpace, forceLinearTransfer = false ) {
  47180. const { gl, extensions } = this;
  47181. if ( internalFormatName !== null ) {
  47182. if ( gl[ internalFormatName ] !== undefined ) return gl[ internalFormatName ];
  47183. warn( 'WebGLBackend: Attempt to use non-existing WebGL internal format \'' + internalFormatName + '\'' );
  47184. }
  47185. let internalFormat = glFormat;
  47186. if ( glFormat === gl.RED ) {
  47187. if ( glType === gl.FLOAT ) internalFormat = gl.R32F;
  47188. if ( glType === gl.HALF_FLOAT ) internalFormat = gl.R16F;
  47189. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.R8;
  47190. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.R16;
  47191. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.R32UI;
  47192. if ( glType === gl.BYTE ) internalFormat = gl.R8I;
  47193. if ( glType === gl.SHORT ) internalFormat = gl.R16I;
  47194. if ( glType === gl.INT ) internalFormat = gl.R32I;
  47195. }
  47196. if ( glFormat === gl.RED_INTEGER ) {
  47197. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.R8UI;
  47198. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.R16UI;
  47199. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.R32UI;
  47200. if ( glType === gl.BYTE ) internalFormat = gl.R8I;
  47201. if ( glType === gl.SHORT ) internalFormat = gl.R16I;
  47202. if ( glType === gl.INT ) internalFormat = gl.R32I;
  47203. }
  47204. if ( glFormat === gl.RG ) {
  47205. if ( glType === gl.FLOAT ) internalFormat = gl.RG32F;
  47206. if ( glType === gl.HALF_FLOAT ) internalFormat = gl.RG16F;
  47207. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RG8;
  47208. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RG16;
  47209. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RG32UI;
  47210. if ( glType === gl.BYTE ) internalFormat = gl.RG8I;
  47211. if ( glType === gl.SHORT ) internalFormat = gl.RG16I;
  47212. if ( glType === gl.INT ) internalFormat = gl.RG32I;
  47213. }
  47214. if ( glFormat === gl.RG_INTEGER ) {
  47215. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RG8UI;
  47216. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RG16UI;
  47217. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RG32UI;
  47218. if ( glType === gl.BYTE ) internalFormat = gl.RG8I;
  47219. if ( glType === gl.SHORT ) internalFormat = gl.RG16I;
  47220. if ( glType === gl.INT ) internalFormat = gl.RG32I;
  47221. }
  47222. if ( glFormat === gl.RGB ) {
  47223. const transfer = forceLinearTransfer ? LinearTransfer : ColorManagement.getTransfer( colorSpace );
  47224. if ( glType === gl.FLOAT ) internalFormat = gl.RGB32F;
  47225. if ( glType === gl.HALF_FLOAT ) internalFormat = gl.RGB16F;
  47226. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RGB8;
  47227. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RGB16;
  47228. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RGB32UI;
  47229. if ( glType === gl.BYTE ) internalFormat = gl.RGB8I;
  47230. if ( glType === gl.SHORT ) internalFormat = gl.RGB16I;
  47231. if ( glType === gl.INT ) internalFormat = gl.RGB32I;
  47232. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = ( transfer === SRGBTransfer ) ? gl.SRGB8 : gl.RGB8;
  47233. if ( glType === gl.UNSIGNED_SHORT_5_6_5 ) internalFormat = gl.RGB565;
  47234. if ( glType === gl.UNSIGNED_SHORT_5_5_5_1 ) internalFormat = gl.RGB5_A1;
  47235. if ( glType === gl.UNSIGNED_SHORT_4_4_4_4 ) internalFormat = gl.RGB4;
  47236. if ( glType === gl.UNSIGNED_INT_5_9_9_9_REV ) internalFormat = gl.RGB9_E5;
  47237. if ( glType === gl.UNSIGNED_INT_10F_11F_11F_REV ) internalFormat = gl.R11F_G11F_B10F;
  47238. }
  47239. if ( glFormat === gl.RGB_INTEGER ) {
  47240. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RGB8UI;
  47241. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RGB16UI;
  47242. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RGB32UI;
  47243. if ( glType === gl.BYTE ) internalFormat = gl.RGB8I;
  47244. if ( glType === gl.SHORT ) internalFormat = gl.RGB16I;
  47245. if ( glType === gl.INT ) internalFormat = gl.RGB32I;
  47246. }
  47247. if ( glFormat === gl.RGBA ) {
  47248. const transfer = forceLinearTransfer ? LinearTransfer : ColorManagement.getTransfer( colorSpace );
  47249. if ( glType === gl.FLOAT ) internalFormat = gl.RGBA32F;
  47250. if ( glType === gl.HALF_FLOAT ) internalFormat = gl.RGBA16F;
  47251. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RGBA8;
  47252. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RGBA16;
  47253. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RGBA32UI;
  47254. if ( glType === gl.BYTE ) internalFormat = gl.RGBA8I;
  47255. if ( glType === gl.SHORT ) internalFormat = gl.RGBA16I;
  47256. if ( glType === gl.INT ) internalFormat = gl.RGBA32I;
  47257. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = ( transfer === SRGBTransfer ) ? gl.SRGB8_ALPHA8 : gl.RGBA8;
  47258. if ( glType === gl.UNSIGNED_SHORT_4_4_4_4 ) internalFormat = gl.RGBA4;
  47259. if ( glType === gl.UNSIGNED_SHORT_5_5_5_1 ) internalFormat = gl.RGB5_A1;
  47260. }
  47261. if ( glFormat === gl.RGBA_INTEGER ) {
  47262. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RGBA8UI;
  47263. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RGBA16UI;
  47264. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RGBA32UI;
  47265. if ( glType === gl.BYTE ) internalFormat = gl.RGBA8I;
  47266. if ( glType === gl.SHORT ) internalFormat = gl.RGBA16I;
  47267. if ( glType === gl.INT ) internalFormat = gl.RGBA32I;
  47268. }
  47269. if ( glFormat === gl.DEPTH_COMPONENT ) {
  47270. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.DEPTH_COMPONENT16;
  47271. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.DEPTH_COMPONENT24;
  47272. if ( glType === gl.FLOAT ) internalFormat = gl.DEPTH_COMPONENT32F;
  47273. }
  47274. if ( glFormat === gl.DEPTH_STENCIL ) {
  47275. if ( glType === gl.UNSIGNED_INT_24_8 ) internalFormat = gl.DEPTH24_STENCIL8;
  47276. }
  47277. if ( internalFormat === gl.R16F || internalFormat === gl.R32F ||
  47278. internalFormat === gl.RG16F || internalFormat === gl.RG32F ||
  47279. internalFormat === gl.RGBA16F || internalFormat === gl.RGBA32F ) {
  47280. extensions.get( 'EXT_color_buffer_float' );
  47281. }
  47282. return internalFormat;
  47283. }
  47284. /**
  47285. * Sets the texture parameters for the given texture.
  47286. *
  47287. * @param {GLenum} textureType - The texture type.
  47288. * @param {Texture} texture - The texture.
  47289. */
  47290. setTextureParameters( textureType, texture ) {
  47291. const { gl, extensions, backend } = this;
  47292. const workingPrimaries = ColorManagement.getPrimaries( ColorManagement.workingColorSpace );
  47293. const texturePrimaries = texture.colorSpace === NoColorSpace ? null : ColorManagement.getPrimaries( texture.colorSpace );
  47294. const unpackConversion = texture.colorSpace === NoColorSpace || workingPrimaries === texturePrimaries ? gl.NONE : gl.BROWSER_DEFAULT_WEBGL;
  47295. gl.pixelStorei( gl.UNPACK_FLIP_Y_WEBGL, texture.flipY );
  47296. gl.pixelStorei( gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, texture.premultiplyAlpha );
  47297. gl.pixelStorei( gl.UNPACK_ALIGNMENT, texture.unpackAlignment );
  47298. gl.pixelStorei( gl.UNPACK_COLORSPACE_CONVERSION_WEBGL, unpackConversion );
  47299. gl.texParameteri( textureType, gl.TEXTURE_WRAP_S, wrappingToGL[ texture.wrapS ] );
  47300. gl.texParameteri( textureType, gl.TEXTURE_WRAP_T, wrappingToGL[ texture.wrapT ] );
  47301. if ( textureType === gl.TEXTURE_3D || textureType === gl.TEXTURE_2D_ARRAY ) {
  47302. // WebGL 2 does not support wrapping for depth 2D array textures
  47303. if ( ! texture.isArrayTexture ) {
  47304. gl.texParameteri( textureType, gl.TEXTURE_WRAP_R, wrappingToGL[ texture.wrapR ] );
  47305. }
  47306. }
  47307. gl.texParameteri( textureType, gl.TEXTURE_MAG_FILTER, filterToGL[ texture.magFilter ] );
  47308. const hasMipmaps = texture.mipmaps !== undefined && texture.mipmaps.length > 0;
  47309. // follow WebGPU backend mapping for texture filtering
  47310. const minFilter = texture.minFilter === LinearFilter && hasMipmaps ? LinearMipmapLinearFilter : texture.minFilter;
  47311. gl.texParameteri( textureType, gl.TEXTURE_MIN_FILTER, filterToGL[ minFilter ] );
  47312. if ( texture.compareFunction ) {
  47313. gl.texParameteri( textureType, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE );
  47314. gl.texParameteri( textureType, gl.TEXTURE_COMPARE_FUNC, compareToGL[ texture.compareFunction ] );
  47315. }
  47316. if ( extensions.has( 'EXT_texture_filter_anisotropic' ) === true ) {
  47317. if ( texture.magFilter === NearestFilter ) return;
  47318. if ( texture.minFilter !== NearestMipmapLinearFilter && texture.minFilter !== LinearMipmapLinearFilter ) return;
  47319. if ( texture.type === FloatType && extensions.has( 'OES_texture_float_linear' ) === false ) return; // verify extension for WebGL 1 and WebGL 2
  47320. if ( texture.anisotropy > 1 ) {
  47321. const extension = extensions.get( 'EXT_texture_filter_anisotropic' );
  47322. gl.texParameterf( textureType, extension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min( texture.anisotropy, backend.getMaxAnisotropy() ) );
  47323. }
  47324. }
  47325. }
  47326. /**
  47327. * Creates a default texture for the given texture that can be used
  47328. * as a placeholder until the actual texture is ready for usage.
  47329. *
  47330. * @param {Texture} texture - The texture to create a default texture for.
  47331. */
  47332. createDefaultTexture( texture ) {
  47333. const { gl, backend, defaultTextures } = this;
  47334. const glTextureType = this.getGLTextureType( texture );
  47335. let textureGPU = defaultTextures[ glTextureType ];
  47336. if ( textureGPU === undefined ) {
  47337. textureGPU = gl.createTexture();
  47338. backend.state.bindTexture( glTextureType, textureGPU );
  47339. gl.texParameteri( glTextureType, gl.TEXTURE_MIN_FILTER, gl.NEAREST );
  47340. gl.texParameteri( glTextureType, gl.TEXTURE_MAG_FILTER, gl.NEAREST );
  47341. // gl.texImage2D( glTextureType, 0, gl.RGBA, 1, 1, 0, gl.RGBA, gl.UNSIGNED_BYTE, data );
  47342. defaultTextures[ glTextureType ] = textureGPU;
  47343. }
  47344. backend.set( texture, {
  47345. textureGPU,
  47346. glTextureType
  47347. } );
  47348. }
  47349. /**
  47350. * Defines a texture on the GPU for the given texture object.
  47351. *
  47352. * @param {Texture} texture - The texture.
  47353. * @param {Object} [options={}] - Optional configuration parameter.
  47354. * @return {undefined}
  47355. */
  47356. createTexture( texture, options ) {
  47357. const { gl, backend } = this;
  47358. const { levels, width, height, depth } = options;
  47359. const glFormat = backend.utils.convert( texture.format, texture.colorSpace );
  47360. const glType = backend.utils.convert( texture.type );
  47361. const glInternalFormat = this.getInternalFormat( texture.internalFormat, glFormat, glType, texture.colorSpace, texture.isVideoTexture );
  47362. const textureGPU = gl.createTexture();
  47363. const glTextureType = this.getGLTextureType( texture );
  47364. backend.state.bindTexture( glTextureType, textureGPU );
  47365. this.setTextureParameters( glTextureType, texture );
  47366. if ( texture.isArrayTexture || texture.isDataArrayTexture || texture.isCompressedArrayTexture ) {
  47367. gl.texStorage3D( gl.TEXTURE_2D_ARRAY, levels, glInternalFormat, width, height, depth );
  47368. } else if ( texture.isData3DTexture ) {
  47369. gl.texStorage3D( gl.TEXTURE_3D, levels, glInternalFormat, width, height, depth );
  47370. } else if ( ! texture.isVideoTexture ) {
  47371. gl.texStorage2D( glTextureType, levels, glInternalFormat, width, height );
  47372. }
  47373. backend.set( texture, {
  47374. textureGPU,
  47375. glTextureType,
  47376. glFormat,
  47377. glType,
  47378. glInternalFormat
  47379. } );
  47380. }
  47381. /**
  47382. * Uploads texture buffer data to the GPU memory.
  47383. *
  47384. * @param {WebGLBuffer} buffer - The buffer data.
  47385. * @param {Texture} texture - The texture,
  47386. */
  47387. copyBufferToTexture( buffer, texture ) {
  47388. const { gl, backend } = this;
  47389. const { textureGPU, glTextureType, glFormat, glType } = backend.get( texture );
  47390. const { width, height } = texture.source.data;
  47391. gl.bindBuffer( gl.PIXEL_UNPACK_BUFFER, buffer );
  47392. backend.state.bindTexture( glTextureType, textureGPU );
  47393. gl.pixelStorei( gl.UNPACK_FLIP_Y_WEBGL, false );
  47394. gl.pixelStorei( gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, false );
  47395. gl.texSubImage2D( glTextureType, 0, 0, 0, width, height, glFormat, glType, 0 );
  47396. gl.bindBuffer( gl.PIXEL_UNPACK_BUFFER, null );
  47397. backend.state.unbindTexture();
  47398. // debug
  47399. // const framebuffer = gl.createFramebuffer();
  47400. // backend.state.bindFramebuffer( gl.FRAMEBUFFER, framebuffer );
  47401. // gl.framebufferTexture2D( gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, glTextureType, textureGPU, 0 );
  47402. // const readout = new Float32Array( width * height * 4 );
  47403. // const altFormat = gl.getParameter( gl.IMPLEMENTATION_COLOR_READ_FORMAT );
  47404. // const altType = gl.getParameter( gl.IMPLEMENTATION_COLOR_READ_TYPE );
  47405. // gl.readPixels( 0, 0, width, height, altFormat, altType, readout );
  47406. // backend.state.bindFramebuffer( gl.FRAMEBUFFER, null );
  47407. // log( readout );
  47408. }
  47409. /**
  47410. * Uploads the updated texture data to the GPU.
  47411. *
  47412. * @param {Texture} texture - The texture.
  47413. * @param {Object} [options={}] - Optional configuration parameter.
  47414. */
  47415. updateTexture( texture, options ) {
  47416. const { gl } = this;
  47417. const { width, height } = options;
  47418. const { textureGPU, glTextureType, glFormat, glType, glInternalFormat } = this.backend.get( texture );
  47419. if ( texture.isRenderTargetTexture || ( textureGPU === undefined /* unsupported texture format */ ) )
  47420. return;
  47421. this.backend.state.bindTexture( glTextureType, textureGPU );
  47422. this.setTextureParameters( glTextureType, texture );
  47423. if ( texture.isCompressedTexture ) {
  47424. const mipmaps = texture.mipmaps;
  47425. const image = options.image;
  47426. for ( let i = 0; i < mipmaps.length; i ++ ) {
  47427. const mipmap = mipmaps[ i ];
  47428. if ( texture.isCompressedArrayTexture ) {
  47429. if ( texture.format !== gl.RGBA ) {
  47430. if ( glFormat !== null ) {
  47431. gl.compressedTexSubImage3D( gl.TEXTURE_2D_ARRAY, i, 0, 0, 0, mipmap.width, mipmap.height, image.depth, glFormat, mipmap.data );
  47432. } else {
  47433. warn( 'WebGLBackend: Attempt to load unsupported compressed texture format in .uploadTexture()' );
  47434. }
  47435. } else {
  47436. gl.texSubImage3D( gl.TEXTURE_2D_ARRAY, i, 0, 0, 0, mipmap.width, mipmap.height, image.depth, glFormat, glType, mipmap.data );
  47437. }
  47438. } else {
  47439. if ( glFormat !== null ) {
  47440. gl.compressedTexSubImage2D( gl.TEXTURE_2D, i, 0, 0, mipmap.width, mipmap.height, glFormat, mipmap.data );
  47441. } else {
  47442. warn( 'WebGLBackend: Unsupported compressed texture format' );
  47443. }
  47444. }
  47445. }
  47446. } else if ( texture.isCubeTexture ) {
  47447. const images = options.images;
  47448. const mipmaps = texture.mipmaps;
  47449. for ( let i = 0; i < 6; i ++ ) {
  47450. const image = getImage( images[ i ] );
  47451. gl.texSubImage2D( gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, 0, 0, width, height, glFormat, glType, image );
  47452. for ( let j = 0; j < mipmaps.length; j ++ ) {
  47453. const mipmap = mipmaps[ j ];
  47454. const image = getImage( mipmap.images[ i ] );
  47455. gl.texSubImage2D( gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j + 1, 0, 0, image.width, image.height, glFormat, glType, image );
  47456. }
  47457. }
  47458. } else if ( texture.isDataArrayTexture || texture.isArrayTexture ) {
  47459. const image = options.image;
  47460. if ( texture.layerUpdates.size > 0 ) {
  47461. const layerByteLength = getByteLength( image.width, image.height, texture.format, texture.type );
  47462. for ( const layerIndex of texture.layerUpdates ) {
  47463. const layerData = image.data.subarray(
  47464. layerIndex * layerByteLength / image.data.BYTES_PER_ELEMENT,
  47465. ( layerIndex + 1 ) * layerByteLength / image.data.BYTES_PER_ELEMENT
  47466. );
  47467. gl.texSubImage3D( gl.TEXTURE_2D_ARRAY, 0, 0, 0, layerIndex, image.width, image.height, 1, glFormat, glType, layerData );
  47468. }
  47469. texture.clearLayerUpdates();
  47470. } else {
  47471. gl.texSubImage3D( gl.TEXTURE_2D_ARRAY, 0, 0, 0, 0, image.width, image.height, image.depth, glFormat, glType, image.data );
  47472. }
  47473. } else if ( texture.isData3DTexture ) {
  47474. const image = options.image;
  47475. gl.texSubImage3D( gl.TEXTURE_3D, 0, 0, 0, 0, image.width, image.height, image.depth, glFormat, glType, image.data );
  47476. } else if ( texture.isVideoTexture ) {
  47477. texture.update();
  47478. gl.texImage2D( glTextureType, 0, glInternalFormat, glFormat, glType, options.image );
  47479. } else {
  47480. const mipmaps = texture.mipmaps;
  47481. if ( mipmaps.length > 0 ) {
  47482. for ( let i = 0, il = mipmaps.length; i < il; i ++ ) {
  47483. const mipmap = mipmaps[ i ];
  47484. const image = getImage( mipmap );
  47485. gl.texSubImage2D( glTextureType, i, 0, 0, mipmap.width, mipmap.height, glFormat, glType, image );
  47486. }
  47487. } else {
  47488. const image = getImage( options.image );
  47489. gl.texSubImage2D( glTextureType, 0, 0, 0, width, height, glFormat, glType, image );
  47490. }
  47491. }
  47492. }
  47493. /**
  47494. * Generates mipmaps for the given texture.
  47495. *
  47496. * @param {Texture} texture - The texture.
  47497. */
  47498. generateMipmaps( texture ) {
  47499. const { gl, backend } = this;
  47500. const { textureGPU, glTextureType } = backend.get( texture );
  47501. backend.state.bindTexture( glTextureType, textureGPU );
  47502. gl.generateMipmap( glTextureType );
  47503. }
  47504. /**
  47505. * Deallocates the render buffers of the given render target.
  47506. *
  47507. * @param {RenderTarget} renderTarget - The render target.
  47508. */
  47509. deallocateRenderBuffers( renderTarget ) {
  47510. const { gl, backend } = this;
  47511. // remove framebuffer reference
  47512. if ( renderTarget ) {
  47513. const renderContextData = backend.get( renderTarget );
  47514. renderContextData.renderBufferStorageSetup = undefined;
  47515. if ( renderContextData.framebuffers ) {
  47516. for ( const cacheKey in renderContextData.framebuffers ) {
  47517. gl.deleteFramebuffer( renderContextData.framebuffers[ cacheKey ] );
  47518. }
  47519. delete renderContextData.framebuffers;
  47520. }
  47521. if ( renderContextData.depthRenderbuffer ) {
  47522. gl.deleteRenderbuffer( renderContextData.depthRenderbuffer );
  47523. delete renderContextData.depthRenderbuffer;
  47524. }
  47525. if ( renderContextData.stencilRenderbuffer ) {
  47526. gl.deleteRenderbuffer( renderContextData.stencilRenderbuffer );
  47527. delete renderContextData.stencilRenderbuffer;
  47528. }
  47529. if ( renderContextData.msaaFrameBuffer ) {
  47530. gl.deleteFramebuffer( renderContextData.msaaFrameBuffer );
  47531. delete renderContextData.msaaFrameBuffer;
  47532. }
  47533. if ( renderContextData.msaaRenderbuffers ) {
  47534. for ( let i = 0; i < renderContextData.msaaRenderbuffers.length; i ++ ) {
  47535. gl.deleteRenderbuffer( renderContextData.msaaRenderbuffers[ i ] );
  47536. }
  47537. delete renderContextData.msaaRenderbuffers;
  47538. }
  47539. }
  47540. }
  47541. /**
  47542. * Destroys the GPU data for the given texture object.
  47543. *
  47544. * @param {Texture} texture - The texture.
  47545. * @param {boolean} [isDefaultTexture=false] - Whether the texture uses a default GPU texture or not.
  47546. */
  47547. destroyTexture( texture, isDefaultTexture = false ) {
  47548. const { gl, backend } = this;
  47549. const { textureGPU, renderTarget } = backend.get( texture );
  47550. this.deallocateRenderBuffers( renderTarget );
  47551. if ( isDefaultTexture === false ) {
  47552. gl.deleteTexture( textureGPU );
  47553. }
  47554. backend.delete( texture );
  47555. }
  47556. /**
  47557. * Copies data of the given source texture to the given destination texture.
  47558. *
  47559. * @param {Texture} srcTexture - The source texture.
  47560. * @param {Texture} dstTexture - The destination texture.
  47561. * @param {?(Box3|Box2)} [srcRegion=null] - The region of the source texture to copy.
  47562. * @param {?(Vector2|Vector3)} [dstPosition=null] - The destination position of the copy.
  47563. * @param {number} [srcLevel=0] - The source mip level to copy from.
  47564. * @param {number} [dstLevel=0] - The destination mip level to copy to.
  47565. */
  47566. copyTextureToTexture( srcTexture, dstTexture, srcRegion = null, dstPosition = null, srcLevel = 0, dstLevel = 0 ) {
  47567. const { gl, backend } = this;
  47568. const { state } = this.backend;
  47569. const { textureGPU: dstTextureGPU, glTextureType, glType, glFormat } = backend.get( dstTexture );
  47570. state.bindTexture( glTextureType, dstTextureGPU );
  47571. // gather the necessary dimensions to copy
  47572. let width, height, depth, minX, minY, minZ;
  47573. let dstX, dstY, dstZ;
  47574. const image = srcTexture.isCompressedTexture ? srcTexture.mipmaps[ dstLevel ] : srcTexture.image;
  47575. if ( srcRegion !== null ) {
  47576. width = srcRegion.max.x - srcRegion.min.x;
  47577. height = srcRegion.max.y - srcRegion.min.y;
  47578. depth = srcRegion.isBox3 ? srcRegion.max.z - srcRegion.min.z : 1;
  47579. minX = srcRegion.min.x;
  47580. minY = srcRegion.min.y;
  47581. minZ = srcRegion.isBox3 ? srcRegion.min.z : 0;
  47582. } else {
  47583. const levelScale = Math.pow( 2, - srcLevel );
  47584. width = Math.floor( image.width * levelScale );
  47585. height = Math.floor( image.height * levelScale );
  47586. if ( srcTexture.isDataArrayTexture || srcTexture.isArrayTexture ) {
  47587. depth = image.depth;
  47588. } else if ( srcTexture.isData3DTexture ) {
  47589. depth = Math.floor( image.depth * levelScale );
  47590. } else {
  47591. depth = 1;
  47592. }
  47593. minX = 0;
  47594. minY = 0;
  47595. minZ = 0;
  47596. }
  47597. if ( dstPosition !== null ) {
  47598. dstX = dstPosition.x;
  47599. dstY = dstPosition.y;
  47600. dstZ = dstPosition.z;
  47601. } else {
  47602. dstX = 0;
  47603. dstY = 0;
  47604. dstZ = 0;
  47605. }
  47606. gl.pixelStorei( gl.UNPACK_FLIP_Y_WEBGL, dstTexture.flipY );
  47607. gl.pixelStorei( gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, dstTexture.premultiplyAlpha );
  47608. gl.pixelStorei( gl.UNPACK_ALIGNMENT, dstTexture.unpackAlignment );
  47609. // used for copying data from cpu
  47610. const currentUnpackRowLen = gl.getParameter( gl.UNPACK_ROW_LENGTH );
  47611. const currentUnpackImageHeight = gl.getParameter( gl.UNPACK_IMAGE_HEIGHT );
  47612. const currentUnpackSkipPixels = gl.getParameter( gl.UNPACK_SKIP_PIXELS );
  47613. const currentUnpackSkipRows = gl.getParameter( gl.UNPACK_SKIP_ROWS );
  47614. const currentUnpackSkipImages = gl.getParameter( gl.UNPACK_SKIP_IMAGES );
  47615. gl.pixelStorei( gl.UNPACK_ROW_LENGTH, image.width );
  47616. gl.pixelStorei( gl.UNPACK_IMAGE_HEIGHT, image.height );
  47617. gl.pixelStorei( gl.UNPACK_SKIP_PIXELS, minX );
  47618. gl.pixelStorei( gl.UNPACK_SKIP_ROWS, minY );
  47619. gl.pixelStorei( gl.UNPACK_SKIP_IMAGES, minZ );
  47620. // set up the src texture
  47621. const isSrc3D = srcTexture.isDataArrayTexture || srcTexture.isData3DTexture || dstTexture.isArrayTexture;
  47622. const isDst3D = dstTexture.isDataArrayTexture || dstTexture.isData3DTexture || dstTexture.isArrayTexture;
  47623. if ( srcTexture.isDepthTexture ) {
  47624. const srcTextureData = backend.get( srcTexture );
  47625. const dstTextureData = backend.get( dstTexture );
  47626. const srcRenderContextData = backend.get( srcTextureData.renderTarget );
  47627. const dstRenderContextData = backend.get( dstTextureData.renderTarget );
  47628. const srcFramebuffer = srcRenderContextData.framebuffers[ srcTextureData.cacheKey ];
  47629. const dstFramebuffer = dstRenderContextData.framebuffers[ dstTextureData.cacheKey ];
  47630. state.bindFramebuffer( gl.READ_FRAMEBUFFER, srcFramebuffer );
  47631. state.bindFramebuffer( gl.DRAW_FRAMEBUFFER, dstFramebuffer );
  47632. for ( let i = 0; i < depth; i ++ ) {
  47633. // if the source or destination are a 3d target then a layer needs to be bound
  47634. if ( isSrc3D ) {
  47635. gl.framebufferTextureLayer( gl.READ_FRAMEBUFFER, gl.COLOR_ATTACHMENT0, srcTextureData.textureGPU, srcLevel, minZ + i );
  47636. gl.framebufferTextureLayer( gl.DRAW_FRAMEBUFFER, gl.COLOR_ATTACHMENT0, dstTextureGPU, dstLevel, dstZ + i );
  47637. }
  47638. gl.blitFramebuffer( minX, minY, width, height, dstX, dstY, width, height, gl.DEPTH_BUFFER_BIT, gl.NEAREST );
  47639. }
  47640. state.bindFramebuffer( gl.READ_FRAMEBUFFER, null );
  47641. state.bindFramebuffer( gl.DRAW_FRAMEBUFFER, null );
  47642. } else if ( srcLevel !== 0 || srcTexture.isRenderTargetTexture || backend.has( srcTexture ) ) {
  47643. // get the appropriate frame buffers
  47644. const srcTextureData = backend.get( srcTexture );
  47645. if ( this._srcFramebuffer === null ) this._srcFramebuffer = gl.createFramebuffer();
  47646. if ( this._dstFramebuffer === null ) this._dstFramebuffer = gl.createFramebuffer();
  47647. // bind the frame buffer targets
  47648. state.bindFramebuffer( gl.READ_FRAMEBUFFER, this._srcFramebuffer );
  47649. state.bindFramebuffer( gl.DRAW_FRAMEBUFFER, this._dstFramebuffer );
  47650. for ( let i = 0; i < depth; i ++ ) {
  47651. // assign the correct layers and mip maps to the frame buffers
  47652. if ( isSrc3D ) {
  47653. gl.framebufferTextureLayer( gl.READ_FRAMEBUFFER, gl.COLOR_ATTACHMENT0, srcTextureData.textureGPU, srcLevel, minZ + i );
  47654. } else {
  47655. gl.framebufferTexture2D( gl.READ_FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, srcTextureData.textureGPU, srcLevel );
  47656. }
  47657. if ( isDst3D ) {
  47658. gl.framebufferTextureLayer( gl.DRAW_FRAMEBUFFER, gl.COLOR_ATTACHMENT0, dstTextureGPU, dstLevel, dstZ + i );
  47659. } else {
  47660. gl.framebufferTexture2D( gl.DRAW_FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, dstTextureGPU, dstLevel );
  47661. }
  47662. // copy the data using the fastest function that can achieve the copy
  47663. if ( srcLevel !== 0 ) {
  47664. gl.blitFramebuffer( minX, minY, width, height, dstX, dstY, width, height, gl.COLOR_BUFFER_BIT, gl.NEAREST );
  47665. } else if ( isDst3D ) {
  47666. gl.copyTexSubImage3D( glTextureType, dstLevel, dstX, dstY, dstZ + i, minX, minY, width, height );
  47667. } else {
  47668. gl.copyTexSubImage2D( glTextureType, dstLevel, dstX, dstY, minX, minY, width, height );
  47669. }
  47670. }
  47671. // unbind read, draw buffers
  47672. state.bindFramebuffer( gl.READ_FRAMEBUFFER, null );
  47673. state.bindFramebuffer( gl.DRAW_FRAMEBUFFER, null );
  47674. } else {
  47675. if ( isDst3D ) {
  47676. // copy data into the 3d texture
  47677. if ( srcTexture.isDataTexture || srcTexture.isData3DTexture ) {
  47678. gl.texSubImage3D( glTextureType, dstLevel, dstX, dstY, dstZ, width, height, depth, glFormat, glType, image.data );
  47679. } else if ( dstTexture.isCompressedArrayTexture ) {
  47680. gl.compressedTexSubImage3D( glTextureType, dstLevel, dstX, dstY, dstZ, width, height, depth, glFormat, image.data );
  47681. } else {
  47682. gl.texSubImage3D( glTextureType, dstLevel, dstX, dstY, dstZ, width, height, depth, glFormat, glType, image );
  47683. }
  47684. } else {
  47685. // copy data into the 2d texture
  47686. if ( srcTexture.isDataTexture ) {
  47687. gl.texSubImage2D( gl.TEXTURE_2D, dstLevel, dstX, dstY, width, height, glFormat, glType, image.data );
  47688. } else if ( srcTexture.isCompressedTexture ) {
  47689. gl.compressedTexSubImage2D( gl.TEXTURE_2D, dstLevel, dstX, dstY, image.width, image.height, glFormat, image.data );
  47690. } else {
  47691. gl.texSubImage2D( gl.TEXTURE_2D, dstLevel, dstX, dstY, width, height, glFormat, glType, image );
  47692. }
  47693. }
  47694. }
  47695. // reset values
  47696. gl.pixelStorei( gl.UNPACK_ROW_LENGTH, currentUnpackRowLen );
  47697. gl.pixelStorei( gl.UNPACK_IMAGE_HEIGHT, currentUnpackImageHeight );
  47698. gl.pixelStorei( gl.UNPACK_SKIP_PIXELS, currentUnpackSkipPixels );
  47699. gl.pixelStorei( gl.UNPACK_SKIP_ROWS, currentUnpackSkipRows );
  47700. gl.pixelStorei( gl.UNPACK_SKIP_IMAGES, currentUnpackSkipImages );
  47701. // Generate mipmaps only when copying level 0
  47702. if ( dstLevel === 0 && dstTexture.generateMipmaps ) {
  47703. gl.generateMipmap( glTextureType );
  47704. }
  47705. state.unbindTexture();
  47706. }
  47707. /**
  47708. * Copies the current bound framebuffer to the given texture.
  47709. *
  47710. * @param {Texture} texture - The destination texture.
  47711. * @param {RenderContext} renderContext - The render context.
  47712. * @param {Vector4} rectangle - A four dimensional vector defining the origin and dimension of the copy.
  47713. */
  47714. copyFramebufferToTexture( texture, renderContext, rectangle ) {
  47715. const { gl } = this;
  47716. const { state } = this.backend;
  47717. const { textureGPU } = this.backend.get( texture );
  47718. const { x, y, z: width, w: height } = rectangle;
  47719. const requireDrawFrameBuffer = texture.isDepthTexture === true || ( renderContext.renderTarget && renderContext.renderTarget.samples > 0 );
  47720. const srcHeight = renderContext.renderTarget ? renderContext.renderTarget.height : this.backend.getDrawingBufferSize().y;
  47721. if ( requireDrawFrameBuffer ) {
  47722. const partial = ( x !== 0 || y !== 0 );
  47723. let mask;
  47724. let attachment;
  47725. if ( texture.isDepthTexture === true ) {
  47726. mask = gl.DEPTH_BUFFER_BIT;
  47727. attachment = gl.DEPTH_ATTACHMENT;
  47728. if ( renderContext.stencil ) {
  47729. mask |= gl.STENCIL_BUFFER_BIT;
  47730. }
  47731. } else {
  47732. mask = gl.COLOR_BUFFER_BIT;
  47733. attachment = gl.COLOR_ATTACHMENT0;
  47734. }
  47735. if ( partial ) {
  47736. const renderTargetContextData = this.backend.get( renderContext.renderTarget );
  47737. const fb = renderTargetContextData.framebuffers[ renderContext.getCacheKey() ];
  47738. const msaaFrameBuffer = renderTargetContextData.msaaFrameBuffer;
  47739. state.bindFramebuffer( gl.DRAW_FRAMEBUFFER, fb );
  47740. state.bindFramebuffer( gl.READ_FRAMEBUFFER, msaaFrameBuffer );
  47741. const flippedY = srcHeight - y - height;
  47742. gl.blitFramebuffer( x, flippedY, x + width, flippedY + height, x, flippedY, x + width, flippedY + height, mask, gl.NEAREST );
  47743. state.bindFramebuffer( gl.READ_FRAMEBUFFER, fb );
  47744. state.bindTexture( gl.TEXTURE_2D, textureGPU );
  47745. gl.copyTexSubImage2D( gl.TEXTURE_2D, 0, 0, 0, x, flippedY, width, height );
  47746. state.unbindTexture();
  47747. } else {
  47748. const fb = gl.createFramebuffer();
  47749. state.bindFramebuffer( gl.DRAW_FRAMEBUFFER, fb );
  47750. gl.framebufferTexture2D( gl.DRAW_FRAMEBUFFER, attachment, gl.TEXTURE_2D, textureGPU, 0 );
  47751. gl.blitFramebuffer( 0, 0, width, height, 0, 0, width, height, mask, gl.NEAREST );
  47752. gl.deleteFramebuffer( fb );
  47753. }
  47754. } else {
  47755. state.bindTexture( gl.TEXTURE_2D, textureGPU );
  47756. gl.copyTexSubImage2D( gl.TEXTURE_2D, 0, 0, 0, x, srcHeight - height - y, width, height );
  47757. state.unbindTexture();
  47758. }
  47759. if ( texture.generateMipmaps ) this.generateMipmaps( texture );
  47760. this.backend._setFramebuffer( renderContext );
  47761. }
  47762. /**
  47763. * SetupS storage for internal depth/stencil buffers and bind to correct framebuffer.
  47764. *
  47765. * @param {WebGLRenderbuffer} renderbuffer - The render buffer.
  47766. * @param {RenderContext} renderContext - The render context.
  47767. * @param {number} samples - The MSAA sample count.
  47768. * @param {boolean} [useMultisampledRTT=false] - Whether to use WEBGL_multisampled_render_to_texture or not.
  47769. */
  47770. setupRenderBufferStorage( renderbuffer, renderContext, samples, useMultisampledRTT = false ) {
  47771. const { gl } = this;
  47772. const renderTarget = renderContext.renderTarget;
  47773. const { depthTexture, depthBuffer, stencilBuffer, width, height } = renderTarget;
  47774. gl.bindRenderbuffer( gl.RENDERBUFFER, renderbuffer );
  47775. if ( depthBuffer && ! stencilBuffer ) {
  47776. let glInternalFormat = gl.DEPTH_COMPONENT24;
  47777. if ( useMultisampledRTT === true ) {
  47778. const multisampledRTTExt = this.extensions.get( 'WEBGL_multisampled_render_to_texture' );
  47779. multisampledRTTExt.renderbufferStorageMultisampleEXT( gl.RENDERBUFFER, renderTarget.samples, glInternalFormat, width, height );
  47780. } else if ( samples > 0 ) {
  47781. if ( depthTexture && depthTexture.isDepthTexture ) {
  47782. if ( depthTexture.type === gl.FLOAT ) {
  47783. glInternalFormat = gl.DEPTH_COMPONENT32F;
  47784. }
  47785. }
  47786. gl.renderbufferStorageMultisample( gl.RENDERBUFFER, samples, glInternalFormat, width, height );
  47787. } else {
  47788. gl.renderbufferStorage( gl.RENDERBUFFER, glInternalFormat, width, height );
  47789. }
  47790. gl.framebufferRenderbuffer( gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, renderbuffer );
  47791. } else if ( depthBuffer && stencilBuffer ) {
  47792. if ( samples > 0 ) {
  47793. gl.renderbufferStorageMultisample( gl.RENDERBUFFER, samples, gl.DEPTH24_STENCIL8, width, height );
  47794. } else {
  47795. gl.renderbufferStorage( gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height );
  47796. }
  47797. gl.framebufferRenderbuffer( gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, renderbuffer );
  47798. }
  47799. gl.bindRenderbuffer( gl.RENDERBUFFER, null );
  47800. }
  47801. /**
  47802. * Returns texture data as a typed array.
  47803. *
  47804. * @async
  47805. * @param {Texture} texture - The texture to copy.
  47806. * @param {number} x - The x coordinate of the copy origin.
  47807. * @param {number} y - The y coordinate of the copy origin.
  47808. * @param {number} width - The width of the copy.
  47809. * @param {number} height - The height of the copy.
  47810. * @param {number} faceIndex - The face index.
  47811. * @return {Promise<TypedArray>} A Promise that resolves with a typed array when the copy operation has finished.
  47812. */
  47813. async copyTextureToBuffer( texture, x, y, width, height, faceIndex ) {
  47814. const { backend, gl } = this;
  47815. const { textureGPU, glFormat, glType } = this.backend.get( texture );
  47816. const fb = gl.createFramebuffer();
  47817. backend.state.bindFramebuffer( gl.READ_FRAMEBUFFER, fb );
  47818. const target = texture.isCubeTexture ? gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex : gl.TEXTURE_2D;
  47819. gl.framebufferTexture2D( gl.READ_FRAMEBUFFER, gl.COLOR_ATTACHMENT0, target, textureGPU, 0 );
  47820. const typedArrayType = this._getTypedArrayType( glType );
  47821. const bytesPerTexel = this._getBytesPerTexel( glType, glFormat );
  47822. const elementCount = width * height;
  47823. const byteLength = elementCount * bytesPerTexel;
  47824. const buffer = gl.createBuffer();
  47825. gl.bindBuffer( gl.PIXEL_PACK_BUFFER, buffer );
  47826. gl.bufferData( gl.PIXEL_PACK_BUFFER, byteLength, gl.STREAM_READ );
  47827. gl.readPixels( x, y, width, height, glFormat, glType, 0 );
  47828. gl.bindBuffer( gl.PIXEL_PACK_BUFFER, null );
  47829. await backend.utils._clientWaitAsync();
  47830. const dstBuffer = new typedArrayType( byteLength / typedArrayType.BYTES_PER_ELEMENT );
  47831. gl.bindBuffer( gl.PIXEL_PACK_BUFFER, buffer );
  47832. gl.getBufferSubData( gl.PIXEL_PACK_BUFFER, 0, dstBuffer );
  47833. gl.bindBuffer( gl.PIXEL_PACK_BUFFER, null );
  47834. backend.state.bindFramebuffer( gl.READ_FRAMEBUFFER, null );
  47835. gl.deleteFramebuffer( fb );
  47836. return dstBuffer;
  47837. }
  47838. /**
  47839. * Returns the corresponding typed array type for the given WebGL data type.
  47840. *
  47841. * @private
  47842. * @param {GLenum} glType - The WebGL data type.
  47843. * @return {TypedArray.constructor} The typed array type.
  47844. */
  47845. _getTypedArrayType( glType ) {
  47846. const { gl } = this;
  47847. if ( glType === gl.UNSIGNED_BYTE ) return Uint8Array;
  47848. if ( glType === gl.UNSIGNED_SHORT_4_4_4_4 ) return Uint16Array;
  47849. if ( glType === gl.UNSIGNED_SHORT_5_5_5_1 ) return Uint16Array;
  47850. if ( glType === gl.UNSIGNED_SHORT_5_6_5 ) return Uint16Array;
  47851. if ( glType === gl.UNSIGNED_SHORT ) return Uint16Array;
  47852. if ( glType === gl.UNSIGNED_INT ) return Uint32Array;
  47853. if ( glType === gl.HALF_FLOAT ) return Uint16Array;
  47854. if ( glType === gl.FLOAT ) return Float32Array;
  47855. throw new Error( `Unsupported WebGL type: ${glType}` );
  47856. }
  47857. /**
  47858. * Returns the bytes-per-texel value for the given WebGL data type and texture format.
  47859. *
  47860. * @private
  47861. * @param {GLenum} glType - The WebGL data type.
  47862. * @param {GLenum} glFormat - The WebGL texture format.
  47863. * @return {number} The bytes-per-texel.
  47864. */
  47865. _getBytesPerTexel( glType, glFormat ) {
  47866. const { gl } = this;
  47867. let bytesPerComponent = 0;
  47868. if ( glType === gl.UNSIGNED_BYTE ) bytesPerComponent = 1;
  47869. if ( glType === gl.UNSIGNED_SHORT_4_4_4_4 ||
  47870. glType === gl.UNSIGNED_SHORT_5_5_5_1 ||
  47871. glType === gl.UNSIGNED_SHORT_5_6_5 ||
  47872. glType === gl.UNSIGNED_SHORT ||
  47873. glType === gl.HALF_FLOAT ) bytesPerComponent = 2;
  47874. if ( glType === gl.UNSIGNED_INT ||
  47875. glType === gl.FLOAT ) bytesPerComponent = 4;
  47876. if ( glFormat === gl.RGBA ) return bytesPerComponent * 4;
  47877. if ( glFormat === gl.RGB ) return bytesPerComponent * 3;
  47878. if ( glFormat === gl.ALPHA ) return bytesPerComponent;
  47879. }
  47880. /**
  47881. * Frees the internal resources.
  47882. */
  47883. dispose() {
  47884. const { gl } = this;
  47885. if ( this._srcFramebuffer !== null ) gl.deleteFramebuffer( this._srcFramebuffer );
  47886. if ( this._dstFramebuffer !== null ) gl.deleteFramebuffer( this._dstFramebuffer );
  47887. }
  47888. }
  47889. function getImage( source ) {
  47890. if ( source.isDataTexture ) {
  47891. return source.image.data;
  47892. } else if ( ( typeof HTMLImageElement !== 'undefined' && source instanceof HTMLImageElement ) ||
  47893. ( typeof HTMLCanvasElement !== 'undefined' && source instanceof HTMLCanvasElement ) ||
  47894. ( typeof ImageBitmap !== 'undefined' && source instanceof ImageBitmap ) ||
  47895. ( typeof OffscreenCanvas !== 'undefined' && source instanceof OffscreenCanvas ) ) {
  47896. return source;
  47897. }
  47898. return source.data;
  47899. }
  47900. /**
  47901. * A WebGL 2 backend utility module for managing extensions.
  47902. *
  47903. * @private
  47904. */
  47905. class WebGLExtensions {
  47906. /**
  47907. * Constructs a new utility object.
  47908. *
  47909. * @param {WebGLBackend} backend - The WebGL 2 backend.
  47910. */
  47911. constructor( backend ) {
  47912. /**
  47913. * A reference to the WebGL 2 backend.
  47914. *
  47915. * @type {WebGLBackend}
  47916. */
  47917. this.backend = backend;
  47918. /**
  47919. * A reference to the rendering context.
  47920. *
  47921. * @type {WebGL2RenderingContext}
  47922. */
  47923. this.gl = this.backend.gl;
  47924. /**
  47925. * A list with all the supported WebGL extensions.
  47926. *
  47927. * @type {Array<string>}
  47928. */
  47929. this.availableExtensions = this.gl.getSupportedExtensions();
  47930. /**
  47931. * A dictionary with requested WebGL extensions.
  47932. * The key is the name of the extension, the value
  47933. * the requested extension object.
  47934. *
  47935. * @type {Object<string,Object>}
  47936. */
  47937. this.extensions = {};
  47938. }
  47939. /**
  47940. * Returns the extension object for the given extension name.
  47941. *
  47942. * @param {string} name - The extension name.
  47943. * @return {Object} The extension object.
  47944. */
  47945. get( name ) {
  47946. let extension = this.extensions[ name ];
  47947. if ( extension === undefined ) {
  47948. extension = this.gl.getExtension( name );
  47949. this.extensions[ name ] = extension;
  47950. }
  47951. return extension;
  47952. }
  47953. /**
  47954. * Returns `true` if the requested extension is available.
  47955. *
  47956. * @param {string} name - The extension name.
  47957. * @return {boolean} Whether the given extension is available or not.
  47958. */
  47959. has( name ) {
  47960. return this.availableExtensions.includes( name );
  47961. }
  47962. }
  47963. /**
  47964. * A WebGL 2 backend utility module for managing the device's capabilities.
  47965. *
  47966. * @private
  47967. */
  47968. class WebGLCapabilities {
  47969. /**
  47970. * Constructs a new utility object.
  47971. *
  47972. * @param {WebGLBackend} backend - The WebGL 2 backend.
  47973. */
  47974. constructor( backend ) {
  47975. /**
  47976. * A reference to the WebGL 2 backend.
  47977. *
  47978. * @type {WebGLBackend}
  47979. */
  47980. this.backend = backend;
  47981. /**
  47982. * This value holds the cached max anisotropy value.
  47983. *
  47984. * @type {?number}
  47985. * @default null
  47986. */
  47987. this.maxAnisotropy = null;
  47988. }
  47989. /**
  47990. * Returns the maximum anisotropy texture filtering value. This value
  47991. * depends on the device and is reported by the `EXT_texture_filter_anisotropic`
  47992. * WebGL extension.
  47993. *
  47994. * @return {number} The maximum anisotropy texture filtering value.
  47995. */
  47996. getMaxAnisotropy() {
  47997. if ( this.maxAnisotropy !== null ) return this.maxAnisotropy;
  47998. const gl = this.backend.gl;
  47999. const extensions = this.backend.extensions;
  48000. if ( extensions.has( 'EXT_texture_filter_anisotropic' ) === true ) {
  48001. const extension = extensions.get( 'EXT_texture_filter_anisotropic' );
  48002. this.maxAnisotropy = gl.getParameter( extension.MAX_TEXTURE_MAX_ANISOTROPY_EXT );
  48003. } else {
  48004. this.maxAnisotropy = 0;
  48005. }
  48006. return this.maxAnisotropy;
  48007. }
  48008. }
  48009. const GLFeatureName = {
  48010. 'WEBGL_multi_draw': 'WEBGL_multi_draw',
  48011. 'WEBGL_compressed_texture_astc': 'texture-compression-astc',
  48012. 'WEBGL_compressed_texture_etc': 'texture-compression-etc2',
  48013. 'WEBGL_compressed_texture_etc1': 'texture-compression-etc1',
  48014. 'WEBGL_compressed_texture_pvrtc': 'texture-compression-pvrtc',
  48015. 'WEBGL_compressed_texture_s3tc': 'texture-compression-s3tc',
  48016. 'EXT_texture_compression_bptc': 'texture-compression-bc',
  48017. 'EXT_disjoint_timer_query_webgl2': 'timestamp-query',
  48018. 'OVR_multiview2': 'OVR_multiview2'
  48019. };
  48020. class WebGLBufferRenderer {
  48021. constructor( backend ) {
  48022. this.gl = backend.gl;
  48023. this.extensions = backend.extensions;
  48024. this.info = backend.renderer.info;
  48025. this.mode = null;
  48026. this.index = 0;
  48027. this.type = null;
  48028. this.object = null;
  48029. }
  48030. render( start, count ) {
  48031. const { gl, mode, object, type, info, index } = this;
  48032. if ( index !== 0 ) {
  48033. gl.drawElements( mode, count, type, start );
  48034. } else {
  48035. gl.drawArrays( mode, start, count );
  48036. }
  48037. info.update( object, count, 1 );
  48038. }
  48039. renderInstances( start, count, primcount ) {
  48040. const { gl, mode, type, index, object, info } = this;
  48041. if ( primcount === 0 ) return;
  48042. if ( index !== 0 ) {
  48043. gl.drawElementsInstanced( mode, count, type, start, primcount );
  48044. } else {
  48045. gl.drawArraysInstanced( mode, start, count, primcount );
  48046. }
  48047. info.update( object, count, primcount );
  48048. }
  48049. renderMultiDraw( starts, counts, drawCount ) {
  48050. const { extensions, mode, object, info } = this;
  48051. if ( drawCount === 0 ) return;
  48052. const extension = extensions.get( 'WEBGL_multi_draw' );
  48053. if ( extension === null ) {
  48054. for ( let i = 0; i < drawCount; i ++ ) {
  48055. this.render( starts[ i ], counts[ i ] );
  48056. }
  48057. } else {
  48058. if ( this.index !== 0 ) {
  48059. extension.multiDrawElementsWEBGL( mode, counts, 0, this.type, starts, 0, drawCount );
  48060. } else {
  48061. extension.multiDrawArraysWEBGL( mode, starts, 0, counts, 0, drawCount );
  48062. }
  48063. let elementCount = 0;
  48064. for ( let i = 0; i < drawCount; i ++ ) {
  48065. elementCount += counts[ i ];
  48066. }
  48067. info.update( object, elementCount, 1 );
  48068. }
  48069. }
  48070. renderMultiDrawInstances( starts, counts, drawCount, primcount ) {
  48071. const { extensions, mode, object, info } = this;
  48072. if ( drawCount === 0 ) return;
  48073. const extension = extensions.get( 'WEBGL_multi_draw' );
  48074. if ( extension === null ) {
  48075. for ( let i = 0; i < drawCount; i ++ ) {
  48076. this.renderInstances( starts[ i ], counts[ i ], primcount[ i ] );
  48077. }
  48078. } else {
  48079. if ( this.index !== 0 ) {
  48080. extension.multiDrawElementsInstancedWEBGL( mode, counts, 0, this.type, starts, 0, primcount, 0, drawCount );
  48081. } else {
  48082. extension.multiDrawArraysInstancedWEBGL( mode, starts, 0, counts, 0, primcount, 0, drawCount );
  48083. }
  48084. let elementCount = 0;
  48085. for ( let i = 0; i < drawCount; i ++ ) {
  48086. elementCount += counts[ i ] * primcount[ i ];
  48087. }
  48088. info.update( object, elementCount, 1 );
  48089. }
  48090. }
  48091. //
  48092. }
  48093. /**
  48094. * Abstract base class of a timestamp query pool.
  48095. *
  48096. * @abstract
  48097. */
  48098. class TimestampQueryPool {
  48099. /**
  48100. * Creates a new timestamp query pool.
  48101. *
  48102. * @param {number} [maxQueries=256] - Maximum number of queries this pool can hold.
  48103. */
  48104. constructor( maxQueries = 256 ) {
  48105. /**
  48106. * Whether to track timestamps or not.
  48107. *
  48108. * @type {boolean}
  48109. * @default true
  48110. */
  48111. this.trackTimestamp = true;
  48112. /**
  48113. * Maximum number of queries this pool can hold.
  48114. *
  48115. * @type {number}
  48116. * @default 256
  48117. */
  48118. this.maxQueries = maxQueries;
  48119. /**
  48120. * How many queries allocated so far.
  48121. *
  48122. * @type {number}
  48123. * @default 0
  48124. */
  48125. this.currentQueryIndex = 0;
  48126. /**
  48127. * Tracks offsets for different contexts.
  48128. *
  48129. * @type {Map<string, number>}
  48130. */
  48131. this.queryOffsets = new Map();
  48132. /**
  48133. * Whether the pool has been disposed or not.
  48134. *
  48135. * @type {boolean}
  48136. * @default false
  48137. */
  48138. this.isDisposed = false;
  48139. /**
  48140. * TODO
  48141. *
  48142. * @type {number}
  48143. * @default 0
  48144. */
  48145. this.lastValue = 0;
  48146. /**
  48147. * Stores all timestamp frames.
  48148. *
  48149. * @type {Array<number>}
  48150. */
  48151. this.frames = [];
  48152. /**
  48153. * TODO
  48154. *
  48155. * @type {boolean}
  48156. * @default false
  48157. */
  48158. this.pendingResolve = false;
  48159. /**
  48160. * Stores the latest timestamp for each render context.
  48161. *
  48162. * @type {Map<string, number>}
  48163. */
  48164. this.timestamps = new Map();
  48165. }
  48166. /**
  48167. * Returns all timestamp frames.
  48168. *
  48169. * @return {Array<number>} The timestamp frames.
  48170. */
  48171. getTimestampFrames() {
  48172. return this.frames;
  48173. }
  48174. /**
  48175. * Returns the timestamp for a given render context.
  48176. *
  48177. * @param {string} uid - A unique identifier for the render context.
  48178. * @return {?number} The timestamp, or undefined if not available.
  48179. */
  48180. getTimestamp( uid ) {
  48181. let timestamp = this.timestamps.get( uid );
  48182. if ( timestamp === undefined ) {
  48183. warn( `TimestampQueryPool: No timestamp available for uid ${ uid }.` );
  48184. timestamp = 0;
  48185. }
  48186. return timestamp;
  48187. }
  48188. /**
  48189. * Returns whether a timestamp is available for a given render context.
  48190. *
  48191. * @param {string} uid - A unique identifier for the render context.
  48192. * @return {boolean} True if a timestamp is available, false otherwise.
  48193. */
  48194. hasTimestamp( uid ) {
  48195. return this.timestamps.has( uid );
  48196. }
  48197. /**
  48198. * Allocate queries for a specific uid.
  48199. *
  48200. * @abstract
  48201. * @param {string} uid - A unique identifier for the render context.
  48202. * @param {number} frameId - The current frame identifier.
  48203. * @returns {?number}
  48204. */
  48205. allocateQueriesForContext( /* uid, frameId */ ) {}
  48206. /**
  48207. * Resolve all timestamps and return data (or process them).
  48208. *
  48209. * @abstract
  48210. * @async
  48211. * @returns {Promise<number>|number} The resolved timestamp value.
  48212. */
  48213. async resolveQueriesAsync() {}
  48214. /**
  48215. * Dispose of the query pool.
  48216. *
  48217. * @abstract
  48218. */
  48219. dispose() {}
  48220. }
  48221. /**
  48222. * Manages a pool of WebGL timestamp queries for performance measurement.
  48223. * Handles creation, execution, and resolution of timer queries using WebGL extensions.
  48224. *
  48225. * @augments TimestampQueryPool
  48226. */
  48227. class WebGLTimestampQueryPool extends TimestampQueryPool {
  48228. /**
  48229. * Creates a new WebGL timestamp query pool.
  48230. *
  48231. * @param {WebGLRenderingContext|WebGL2RenderingContext} gl - The WebGL context.
  48232. * @param {string} type - The type identifier for this query pool.
  48233. * @param {number} [maxQueries=2048] - Maximum number of queries this pool can hold.
  48234. */
  48235. constructor( gl, type, maxQueries = 2048 ) {
  48236. super( maxQueries );
  48237. this.gl = gl;
  48238. this.type = type;
  48239. // Check for timer query extensions
  48240. this.ext = gl.getExtension( 'EXT_disjoint_timer_query_webgl2' ) ||
  48241. gl.getExtension( 'EXT_disjoint_timer_query' );
  48242. if ( ! this.ext ) {
  48243. warn( 'EXT_disjoint_timer_query not supported; timestamps will be disabled.' );
  48244. this.trackTimestamp = false;
  48245. return;
  48246. }
  48247. // Create query objects
  48248. this.queries = [];
  48249. for ( let i = 0; i < this.maxQueries; i ++ ) {
  48250. this.queries.push( gl.createQuery() );
  48251. }
  48252. this.activeQuery = null;
  48253. this.queryStates = new Map(); // Track state of each query: 'inactive', 'started', 'ended'
  48254. }
  48255. /**
  48256. * Allocates a pair of queries for a given render context.
  48257. *
  48258. * @param {string} uid - A unique identifier for the render context.
  48259. * @returns {?number} The base offset for the allocated queries, or null if allocation failed.
  48260. */
  48261. allocateQueriesForContext( uid ) {
  48262. if ( ! this.trackTimestamp ) return null;
  48263. // Check if we have enough space for a new query pair
  48264. if ( this.currentQueryIndex + 2 > this.maxQueries ) {
  48265. 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() } ).` );
  48266. return null;
  48267. }
  48268. const baseOffset = this.currentQueryIndex;
  48269. this.currentQueryIndex += 2;
  48270. // Initialize query states
  48271. this.queryStates.set( baseOffset, 'inactive' );
  48272. this.queryOffsets.set( uid, baseOffset );
  48273. return baseOffset;
  48274. }
  48275. /**
  48276. * Begins a timestamp query for the specified render context.
  48277. *
  48278. * @param {string} uid - A unique identifier for the render context.
  48279. */
  48280. beginQuery( uid ) {
  48281. if ( ! this.trackTimestamp || this.isDisposed ) {
  48282. return;
  48283. }
  48284. const baseOffset = this.queryOffsets.get( uid );
  48285. if ( baseOffset == null ) {
  48286. return;
  48287. }
  48288. // Don't start a new query if there's an active one
  48289. if ( this.activeQuery !== null ) {
  48290. return;
  48291. }
  48292. const query = this.queries[ baseOffset ];
  48293. if ( ! query ) {
  48294. return;
  48295. }
  48296. try {
  48297. // Only begin if query is inactive
  48298. if ( this.queryStates.get( baseOffset ) === 'inactive' ) {
  48299. this.gl.beginQuery( this.ext.TIME_ELAPSED_EXT, query );
  48300. this.activeQuery = baseOffset;
  48301. this.queryStates.set( baseOffset, 'started' );
  48302. }
  48303. } catch ( e ) {
  48304. error( 'Error in beginQuery:', e );
  48305. this.activeQuery = null;
  48306. this.queryStates.set( baseOffset, 'inactive' );
  48307. }
  48308. }
  48309. /**
  48310. * Ends the active timestamp query for the specified render context.
  48311. *
  48312. * @param {string} uid - A unique identifier for the render context.
  48313. */
  48314. endQuery( uid ) {
  48315. if ( ! this.trackTimestamp || this.isDisposed ) {
  48316. return;
  48317. }
  48318. const baseOffset = this.queryOffsets.get( uid );
  48319. if ( baseOffset == null ) {
  48320. return;
  48321. }
  48322. // Only end if this is the active query
  48323. if ( this.activeQuery !== baseOffset ) {
  48324. return;
  48325. }
  48326. try {
  48327. this.gl.endQuery( this.ext.TIME_ELAPSED_EXT );
  48328. this.queryStates.set( baseOffset, 'ended' );
  48329. this.activeQuery = null;
  48330. } catch ( e ) {
  48331. error( 'Error in endQuery:', e );
  48332. // Reset state on error
  48333. this.queryStates.set( baseOffset, 'inactive' );
  48334. this.activeQuery = null;
  48335. }
  48336. }
  48337. /**
  48338. * Asynchronously resolves all completed queries and returns the total duration.
  48339. *
  48340. * @async
  48341. * @returns {Promise<number>} The total duration in milliseconds, or the last valid value if resolution fails.
  48342. */
  48343. async resolveQueriesAsync() {
  48344. if ( ! this.trackTimestamp || this.pendingResolve ) {
  48345. return this.lastValue;
  48346. }
  48347. this.pendingResolve = true;
  48348. try {
  48349. // Wait for all ended queries to complete
  48350. const resolvePromises = new Map();
  48351. for ( const [ uid, baseOffset ] of this.queryOffsets ) {
  48352. const state = this.queryStates.get( baseOffset );
  48353. if ( state === 'ended' ) {
  48354. const query = this.queries[ baseOffset ];
  48355. resolvePromises.set( uid, this.resolveQuery( query ) );
  48356. }
  48357. }
  48358. if ( resolvePromises.size === 0 ) {
  48359. return this.lastValue;
  48360. }
  48361. //
  48362. const framesDuration = {};
  48363. const frames = [];
  48364. for ( const [ uid, promise ] of resolvePromises ) {
  48365. const match = uid.match( /^(.*):f(\d+)$/ );
  48366. const frame = parseInt( match[ 2 ] );
  48367. if ( frames.includes( frame ) === false ) {
  48368. frames.push( frame );
  48369. }
  48370. if ( framesDuration[ frame ] === undefined ) framesDuration[ frame ] = 0;
  48371. const duration = await promise;
  48372. this.timestamps.set( uid, duration );
  48373. framesDuration[ frame ] += duration;
  48374. }
  48375. // Return the total duration of the last frame
  48376. const totalDuration = framesDuration[ frames[ frames.length - 1 ] ];
  48377. // Store the last valid result
  48378. this.lastValue = totalDuration;
  48379. this.frames = frames;
  48380. // Reset states
  48381. this.currentQueryIndex = 0;
  48382. this.queryOffsets.clear();
  48383. this.queryStates.clear();
  48384. this.activeQuery = null;
  48385. return totalDuration;
  48386. } catch ( e ) {
  48387. error( 'Error resolving queries:', e );
  48388. return this.lastValue;
  48389. } finally {
  48390. this.pendingResolve = false;
  48391. }
  48392. }
  48393. /**
  48394. * Resolves a single query, checking for completion and disjoint operation.
  48395. *
  48396. * @async
  48397. * @param {WebGLQuery} query - The query object to resolve.
  48398. * @returns {Promise<number>} The elapsed time in milliseconds.
  48399. */
  48400. async resolveQuery( query ) {
  48401. return new Promise( ( resolve ) => {
  48402. if ( this.isDisposed ) {
  48403. resolve( this.lastValue );
  48404. return;
  48405. }
  48406. let timeoutId;
  48407. let isResolved = false;
  48408. const cleanup = () => {
  48409. if ( timeoutId ) {
  48410. clearTimeout( timeoutId );
  48411. timeoutId = null;
  48412. }
  48413. };
  48414. const finalizeResolution = ( value ) => {
  48415. if ( ! isResolved ) {
  48416. isResolved = true;
  48417. cleanup();
  48418. resolve( value );
  48419. }
  48420. };
  48421. const checkQuery = () => {
  48422. if ( this.isDisposed ) {
  48423. finalizeResolution( this.lastValue );
  48424. return;
  48425. }
  48426. try {
  48427. // Check if the GPU timer was disjoint (i.e., timing was unreliable)
  48428. const disjoint = this.gl.getParameter( this.ext.GPU_DISJOINT_EXT );
  48429. if ( disjoint ) {
  48430. finalizeResolution( this.lastValue );
  48431. return;
  48432. }
  48433. const available = this.gl.getQueryParameter( query, this.gl.QUERY_RESULT_AVAILABLE );
  48434. if ( ! available ) {
  48435. timeoutId = setTimeout( checkQuery, 1 );
  48436. return;
  48437. }
  48438. const elapsed = this.gl.getQueryParameter( query, this.gl.QUERY_RESULT );
  48439. resolve( Number( elapsed ) / 1e6 ); // Convert nanoseconds to milliseconds
  48440. } catch ( e ) {
  48441. error( 'Error checking query:', e );
  48442. resolve( this.lastValue );
  48443. }
  48444. };
  48445. checkQuery();
  48446. } );
  48447. }
  48448. /**
  48449. * Releases all resources held by this query pool.
  48450. * This includes deleting all query objects and clearing internal state.
  48451. */
  48452. dispose() {
  48453. if ( this.isDisposed ) {
  48454. return;
  48455. }
  48456. this.isDisposed = true;
  48457. if ( ! this.trackTimestamp ) return;
  48458. for ( const query of this.queries ) {
  48459. this.gl.deleteQuery( query );
  48460. }
  48461. this.queries = [];
  48462. this.queryStates.clear();
  48463. this.queryOffsets.clear();
  48464. this.lastValue = 0;
  48465. this.activeQuery = null;
  48466. }
  48467. }
  48468. /**
  48469. * A backend implementation targeting WebGL 2.
  48470. *
  48471. * @private
  48472. * @augments Backend
  48473. */
  48474. class WebGLBackend extends Backend {
  48475. /**
  48476. * WebGLBackend options.
  48477. *
  48478. * @typedef {Object} WebGLBackend~Options
  48479. * @property {boolean} [logarithmicDepthBuffer=false] - Whether logarithmic depth buffer is enabled or not.
  48480. * @property {boolean} [alpha=true] - Whether the default framebuffer (which represents the final contents of the canvas) should be transparent or opaque.
  48481. * @property {boolean} [depth=true] - Whether the default framebuffer should have a depth buffer or not.
  48482. * @property {boolean} [stencil=false] - Whether the default framebuffer should have a stencil buffer or not.
  48483. * @property {boolean} [antialias=false] - Whether MSAA as the default anti-aliasing should be enabled or not.
  48484. * @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.
  48485. * @property {boolean} [forceWebGL=false] - If set to `true`, the renderer uses a WebGL 2 backend no matter if WebGPU is supported or not.
  48486. * @property {WebGL2RenderingContext} [context=undefined] - A WebGL 2 rendering context.
  48487. */
  48488. /**
  48489. * Constructs a new WebGPU backend.
  48490. *
  48491. * @param {WebGLBackend~Options} [parameters] - The configuration parameter.
  48492. */
  48493. constructor( parameters = {} ) {
  48494. super( parameters );
  48495. /**
  48496. * This flag can be used for type testing.
  48497. *
  48498. * @type {boolean}
  48499. * @readonly
  48500. * @default true
  48501. */
  48502. this.isWebGLBackend = true;
  48503. /**
  48504. * A reference to a backend module holding shader attribute-related
  48505. * utility functions.
  48506. *
  48507. * @type {?WebGLAttributeUtils}
  48508. * @default null
  48509. */
  48510. this.attributeUtils = null;
  48511. /**
  48512. * A reference to a backend module holding extension-related
  48513. * utility functions.
  48514. *
  48515. * @type {?WebGLExtensions}
  48516. * @default null
  48517. */
  48518. this.extensions = null;
  48519. /**
  48520. * A reference to a backend module holding capability-related
  48521. * utility functions.
  48522. *
  48523. * @type {?WebGLCapabilities}
  48524. * @default null
  48525. */
  48526. this.capabilities = null;
  48527. /**
  48528. * A reference to a backend module holding texture-related
  48529. * utility functions.
  48530. *
  48531. * @type {?WebGLTextureUtils}
  48532. * @default null
  48533. */
  48534. this.textureUtils = null;
  48535. /**
  48536. * A reference to a backend module holding renderer-related
  48537. * utility functions.
  48538. *
  48539. * @type {?WebGLBufferRenderer}
  48540. * @default null
  48541. */
  48542. this.bufferRenderer = null;
  48543. /**
  48544. * A reference to the rendering context.
  48545. *
  48546. * @type {?WebGL2RenderingContext}
  48547. * @default null
  48548. */
  48549. this.gl = null;
  48550. /**
  48551. * A reference to a backend module holding state-related
  48552. * utility functions.
  48553. *
  48554. * @type {?WebGLState}
  48555. * @default null
  48556. */
  48557. this.state = null;
  48558. /**
  48559. * A reference to a backend module holding common
  48560. * utility functions.
  48561. *
  48562. * @type {?WebGLUtils}
  48563. * @default null
  48564. */
  48565. this.utils = null;
  48566. /**
  48567. * Dictionary for caching VAOs.
  48568. *
  48569. * @type {Object<string,WebGLVertexArrayObject>}
  48570. */
  48571. this.vaoCache = {};
  48572. /**
  48573. * Dictionary for caching transform feedback objects.
  48574. *
  48575. * @type {Object<string,WebGLTransformFeedback>}
  48576. */
  48577. this.transformFeedbackCache = {};
  48578. /**
  48579. * Controls if `gl.RASTERIZER_DISCARD` should be enabled or not.
  48580. * Only relevant when using compute shaders.
  48581. *
  48582. * @type {boolean}
  48583. * @default false
  48584. */
  48585. this.discard = false;
  48586. /**
  48587. * A reference to the `EXT_disjoint_timer_query_webgl2` extension. `null` if the
  48588. * device does not support the extension.
  48589. *
  48590. * @type {?EXTDisjointTimerQueryWebGL2}
  48591. * @default null
  48592. */
  48593. this.disjoint = null;
  48594. /**
  48595. * A reference to the `KHR_parallel_shader_compile` extension. `null` if the
  48596. * device does not support the extension.
  48597. *
  48598. * @type {?KHRParallelShaderCompile}
  48599. * @default null
  48600. */
  48601. this.parallel = null;
  48602. /**
  48603. * A reference to the current render context.
  48604. *
  48605. * @private
  48606. * @type {RenderContext}
  48607. * @default null
  48608. */
  48609. this._currentContext = null;
  48610. /**
  48611. * A unique collection of bindings.
  48612. *
  48613. * @private
  48614. * @type {WeakSet<Array<BindGroup>>}
  48615. */
  48616. this._knownBindings = new WeakSet();
  48617. /**
  48618. * Whether the device supports framebuffers invalidation or not.
  48619. *
  48620. * @private
  48621. * @type {boolean}
  48622. */
  48623. this._supportsInvalidateFramebuffer = typeof navigator === 'undefined' ? false : /OculusBrowser/g.test( navigator.userAgent );
  48624. /**
  48625. * The target framebuffer when rendering with
  48626. * the WebXR device API.
  48627. *
  48628. * @private
  48629. * @type {?WebGLFramebuffer}
  48630. * @default null
  48631. */
  48632. this._xrFramebuffer = null;
  48633. }
  48634. /**
  48635. * Initializes the backend so it is ready for usage.
  48636. *
  48637. * @param {Renderer} renderer - The renderer.
  48638. */
  48639. init( renderer ) {
  48640. super.init( renderer );
  48641. //
  48642. const parameters = this.parameters;
  48643. const contextAttributes = {
  48644. antialias: renderer.currentSamples > 0,
  48645. alpha: true, // always true for performance reasons
  48646. depth: renderer.depth,
  48647. stencil: renderer.stencil
  48648. };
  48649. const glContext = ( parameters.context !== undefined ) ? parameters.context : renderer.domElement.getContext( 'webgl2', contextAttributes );
  48650. function onContextLost( event ) {
  48651. event.preventDefault();
  48652. const contextLossInfo = {
  48653. api: 'WebGL',
  48654. message: event.statusMessage || 'Unknown reason',
  48655. reason: null,
  48656. originalEvent: event
  48657. };
  48658. renderer.onDeviceLost( contextLossInfo );
  48659. }
  48660. this._onContextLost = onContextLost;
  48661. renderer.domElement.addEventListener( 'webglcontextlost', onContextLost, false );
  48662. this.gl = glContext;
  48663. this.extensions = new WebGLExtensions( this );
  48664. this.capabilities = new WebGLCapabilities( this );
  48665. this.attributeUtils = new WebGLAttributeUtils( this );
  48666. this.textureUtils = new WebGLTextureUtils( this );
  48667. this.bufferRenderer = new WebGLBufferRenderer( this );
  48668. this.state = new WebGLState( this );
  48669. this.utils = new WebGLUtils( this );
  48670. this.extensions.get( 'EXT_color_buffer_float' );
  48671. this.extensions.get( 'WEBGL_clip_cull_distance' );
  48672. this.extensions.get( 'OES_texture_float_linear' );
  48673. this.extensions.get( 'EXT_color_buffer_half_float' );
  48674. this.extensions.get( 'WEBGL_multisampled_render_to_texture' );
  48675. this.extensions.get( 'WEBGL_render_shared_exponent' );
  48676. this.extensions.get( 'WEBGL_multi_draw' );
  48677. this.extensions.get( 'OVR_multiview2' );
  48678. this.disjoint = this.extensions.get( 'EXT_disjoint_timer_query_webgl2' );
  48679. this.parallel = this.extensions.get( 'KHR_parallel_shader_compile' );
  48680. this.drawBuffersIndexedExt = this.extensions.get( 'OES_draw_buffers_indexed' );
  48681. }
  48682. /**
  48683. * The coordinate system of the backend.
  48684. *
  48685. * @type {number}
  48686. * @readonly
  48687. */
  48688. get coordinateSystem() {
  48689. return WebGLCoordinateSystem;
  48690. }
  48691. /**
  48692. * This method performs a readback operation by moving buffer data from
  48693. * a storage buffer attribute from the GPU to the CPU.
  48694. *
  48695. * @async
  48696. * @param {StorageBufferAttribute} attribute - The storage buffer attribute.
  48697. * @return {Promise<ArrayBuffer>} A promise that resolves with the buffer data when the data are ready.
  48698. */
  48699. async getArrayBufferAsync( attribute ) {
  48700. return await this.attributeUtils.getArrayBufferAsync( attribute );
  48701. }
  48702. /**
  48703. * Ensures the backend is XR compatible.
  48704. *
  48705. * @async
  48706. * @return {Promise} A Promise that resolve when the renderer is XR compatible.
  48707. */
  48708. async makeXRCompatible() {
  48709. const attributes = this.gl.getContextAttributes();
  48710. if ( attributes.xrCompatible !== true ) {
  48711. await this.gl.makeXRCompatible();
  48712. }
  48713. }
  48714. /**
  48715. * Sets the XR rendering destination.
  48716. *
  48717. * @param {WebGLFramebuffer} xrFramebuffer - The XR framebuffer.
  48718. */
  48719. setXRTarget( xrFramebuffer ) {
  48720. this._xrFramebuffer = xrFramebuffer;
  48721. }
  48722. /**
  48723. * Configures the given XR render target with external textures.
  48724. *
  48725. * This method is only relevant when using the WebXR Layers API.
  48726. *
  48727. * @param {XRRenderTarget} renderTarget - The XR render target.
  48728. * @param {WebGLTexture} colorTexture - A native color texture.
  48729. * @param {?WebGLTexture} [depthTexture=null] - A native depth texture.
  48730. */
  48731. setXRRenderTargetTextures( renderTarget, colorTexture, depthTexture = null ) {
  48732. const gl = this.gl;
  48733. this.set( renderTarget.texture, { textureGPU: colorTexture, glInternalFormat: gl.RGBA8 } ); // see #24698 why RGBA8 and not SRGB8_ALPHA8 is used
  48734. if ( depthTexture !== null ) {
  48735. const glInternalFormat = renderTarget.stencilBuffer ? gl.DEPTH24_STENCIL8 : gl.DEPTH_COMPONENT24;
  48736. this.set( renderTarget.depthTexture, { textureGPU: depthTexture, glInternalFormat: glInternalFormat } );
  48737. // The multisample_render_to_texture extension doesn't work properly if there
  48738. // are midframe flushes and an external depth texture.
  48739. if ( ( this.extensions.has( 'WEBGL_multisampled_render_to_texture' ) === true ) && renderTarget._autoAllocateDepthBuffer === true && renderTarget.multiview === false ) {
  48740. warn( 'WebGLBackend: Render-to-texture extension was disabled because an external texture was provided' );
  48741. }
  48742. renderTarget._autoAllocateDepthBuffer = false;
  48743. }
  48744. }
  48745. /**
  48746. * Inits a time stamp query for the given render context.
  48747. *
  48748. * @param {string} type - The type of the timestamp query.
  48749. * @param {string} uid - A unique identifier for the timestamp query.
  48750. */
  48751. initTimestampQuery( type, uid ) {
  48752. if ( ! this.disjoint || ! this.trackTimestamp ) return;
  48753. if ( ! this.timestampQueryPool[ type ] ) {
  48754. // TODO: Variable maxQueries?
  48755. this.timestampQueryPool[ type ] = new WebGLTimestampQueryPool( this.gl, type, 2048 );
  48756. }
  48757. const timestampQueryPool = this.timestampQueryPool[ type ];
  48758. const baseOffset = timestampQueryPool.allocateQueriesForContext( uid );
  48759. if ( baseOffset !== null ) {
  48760. timestampQueryPool.beginQuery( uid );
  48761. }
  48762. }
  48763. // timestamp utils
  48764. /**
  48765. * Prepares the timestamp buffer.
  48766. *
  48767. * @param {string} type - The type of the timestamp query.
  48768. * @param {string} uid - A unique identifier for the timestamp query.
  48769. */
  48770. prepareTimestampBuffer( type, uid ) {
  48771. if ( ! this.disjoint || ! this.trackTimestamp ) return;
  48772. const timestampQueryPool = this.timestampQueryPool[ type ];
  48773. timestampQueryPool.endQuery( uid );
  48774. }
  48775. /**
  48776. * Returns the backend's rendering context.
  48777. *
  48778. * @return {WebGL2RenderingContext} The rendering context.
  48779. */
  48780. getContext() {
  48781. return this.gl;
  48782. }
  48783. /**
  48784. * This method is executed at the beginning of a render call and prepares
  48785. * the WebGL state for upcoming render calls
  48786. *
  48787. * @param {RenderContext} renderContext - The render context.
  48788. */
  48789. beginRender( renderContext ) {
  48790. const { state } = this;
  48791. const renderContextData = this.get( renderContext );
  48792. //
  48793. if ( renderContext.viewport ) {
  48794. this.updateViewport( renderContext );
  48795. } else {
  48796. const { width, height } = this.getDrawingBufferSize();
  48797. state.viewport( 0, 0, width, height );
  48798. }
  48799. if ( renderContext.scissor ) {
  48800. const { x, y, width, height } = renderContext.scissorValue;
  48801. state.scissor( x, renderContext.height - height - y, width, height );
  48802. }
  48803. //
  48804. this.initTimestampQuery( TimestampQuery.RENDER, this.getTimestampUID( renderContext ) );
  48805. renderContextData.previousContext = this._currentContext;
  48806. this._currentContext = renderContext;
  48807. this._setFramebuffer( renderContext );
  48808. this.clear( renderContext.clearColor, renderContext.clearDepth, renderContext.clearStencil, renderContext, false );
  48809. const occlusionQueryCount = renderContext.occlusionQueryCount;
  48810. if ( occlusionQueryCount > 0 ) {
  48811. // Get a reference to the array of objects with queries. The renderContextData property
  48812. // can be changed by another render pass before the async reading of all previous queries complete
  48813. renderContextData.currentOcclusionQueries = renderContextData.occlusionQueries;
  48814. renderContextData.currentOcclusionQueryObjects = renderContextData.occlusionQueryObjects;
  48815. renderContextData.lastOcclusionObject = null;
  48816. renderContextData.occlusionQueries = new Array( occlusionQueryCount );
  48817. renderContextData.occlusionQueryObjects = new Array( occlusionQueryCount );
  48818. renderContextData.occlusionQueryIndex = 0;
  48819. }
  48820. }
  48821. /**
  48822. * This method is executed at the end of a render call and finalizes work
  48823. * after draw calls.
  48824. *
  48825. * @param {RenderContext} renderContext - The render context.
  48826. */
  48827. finishRender( renderContext ) {
  48828. const { gl, state } = this;
  48829. const renderContextData = this.get( renderContext );
  48830. const previousContext = renderContextData.previousContext;
  48831. state.resetVertexState();
  48832. const occlusionQueryCount = renderContext.occlusionQueryCount;
  48833. if ( occlusionQueryCount > 0 ) {
  48834. if ( occlusionQueryCount > renderContextData.occlusionQueryIndex ) {
  48835. gl.endQuery( gl.ANY_SAMPLES_PASSED );
  48836. }
  48837. this.resolveOccludedAsync( renderContext );
  48838. }
  48839. const textures = renderContext.textures;
  48840. if ( textures !== null ) {
  48841. for ( let i = 0; i < textures.length; i ++ ) {
  48842. const texture = textures[ i ];
  48843. if ( texture.generateMipmaps ) {
  48844. this.generateMipmaps( texture );
  48845. }
  48846. }
  48847. }
  48848. this._currentContext = previousContext;
  48849. this._resolveRenderTarget( renderContext );
  48850. if ( previousContext !== null ) {
  48851. this._setFramebuffer( previousContext );
  48852. if ( previousContext.viewport ) {
  48853. this.updateViewport( previousContext );
  48854. } else {
  48855. const { width, height } = this.getDrawingBufferSize();
  48856. state.viewport( 0, 0, width, height );
  48857. }
  48858. }
  48859. this.prepareTimestampBuffer( TimestampQuery.RENDER, this.getTimestampUID( renderContext ) );
  48860. }
  48861. /**
  48862. * This method processes the result of occlusion queries and writes it
  48863. * into render context data.
  48864. *
  48865. * @async
  48866. * @param {RenderContext} renderContext - The render context.
  48867. */
  48868. resolveOccludedAsync( renderContext ) {
  48869. const renderContextData = this.get( renderContext );
  48870. // handle occlusion query results
  48871. const { currentOcclusionQueries, currentOcclusionQueryObjects } = renderContextData;
  48872. if ( currentOcclusionQueries && currentOcclusionQueryObjects ) {
  48873. const occluded = new WeakSet();
  48874. const { gl } = this;
  48875. renderContextData.currentOcclusionQueryObjects = null;
  48876. renderContextData.currentOcclusionQueries = null;
  48877. const check = () => {
  48878. let completed = 0;
  48879. // check all queries and requeue as appropriate
  48880. for ( let i = 0; i < currentOcclusionQueries.length; i ++ ) {
  48881. const query = currentOcclusionQueries[ i ];
  48882. if ( query === null ) continue;
  48883. if ( gl.getQueryParameter( query, gl.QUERY_RESULT_AVAILABLE ) ) {
  48884. if ( gl.getQueryParameter( query, gl.QUERY_RESULT ) === 0 ) occluded.add( currentOcclusionQueryObjects[ i ] );
  48885. currentOcclusionQueries[ i ] = null;
  48886. gl.deleteQuery( query );
  48887. completed ++;
  48888. }
  48889. }
  48890. if ( completed < currentOcclusionQueries.length ) {
  48891. requestAnimationFrame( check );
  48892. } else {
  48893. renderContextData.occluded = occluded;
  48894. }
  48895. };
  48896. check();
  48897. }
  48898. }
  48899. /**
  48900. * Returns `true` if the given 3D object is fully occluded by other
  48901. * 3D objects in the scene.
  48902. *
  48903. * @param {RenderContext} renderContext - The render context.
  48904. * @param {Object3D} object - The 3D object to test.
  48905. * @return {boolean} Whether the 3D object is fully occluded or not.
  48906. */
  48907. isOccluded( renderContext, object ) {
  48908. const renderContextData = this.get( renderContext );
  48909. return renderContextData.occluded && renderContextData.occluded.has( object );
  48910. }
  48911. /**
  48912. * Updates the viewport with the values from the given render context.
  48913. *
  48914. * @param {RenderContext} renderContext - The render context.
  48915. */
  48916. updateViewport( renderContext ) {
  48917. const { state } = this;
  48918. const { x, y, width, height } = renderContext.viewportValue;
  48919. state.viewport( x, renderContext.height - height - y, width, height );
  48920. }
  48921. /**
  48922. * Defines the scissor test.
  48923. *
  48924. * @param {boolean} boolean - Whether the scissor test should be enabled or not.
  48925. */
  48926. setScissorTest( boolean ) {
  48927. const state = this.state;
  48928. state.setScissorTest( boolean );
  48929. }
  48930. /**
  48931. * Returns the clear color and alpha into a single
  48932. * color object.
  48933. *
  48934. * @return {Color4} The clear color.
  48935. */
  48936. getClearColor() {
  48937. const clearColor = super.getClearColor();
  48938. // Since the canvas is always created with alpha: true,
  48939. // WebGL must always premultiply the clear color.
  48940. clearColor.r *= clearColor.a;
  48941. clearColor.g *= clearColor.a;
  48942. clearColor.b *= clearColor.a;
  48943. return clearColor;
  48944. }
  48945. /**
  48946. * Performs a clear operation.
  48947. *
  48948. * @param {boolean} color - Whether the color buffer should be cleared or not.
  48949. * @param {boolean} depth - Whether the depth buffer should be cleared or not.
  48950. * @param {boolean} stencil - Whether the stencil buffer should be cleared or not.
  48951. * @param {?Object} [descriptor=null] - The render context of the current set render target.
  48952. * @param {boolean} [setFrameBuffer=true] - Controls whether the intermediate framebuffer should be set or not.
  48953. * @param {boolean} [resolveRenderTarget=true] - Controls whether an active render target should be resolved
  48954. * or not. Only relevant for explicit clears.
  48955. */
  48956. clear( color, depth, stencil, descriptor = null, setFrameBuffer = true, resolveRenderTarget = true ) {
  48957. const { gl, renderer } = this;
  48958. if ( descriptor === null ) {
  48959. const clearColor = this.getClearColor();
  48960. descriptor = {
  48961. textures: null,
  48962. clearColorValue: clearColor
  48963. };
  48964. }
  48965. //
  48966. let clear = 0;
  48967. if ( color ) clear |= gl.COLOR_BUFFER_BIT;
  48968. if ( depth ) clear |= gl.DEPTH_BUFFER_BIT;
  48969. if ( stencil ) clear |= gl.STENCIL_BUFFER_BIT;
  48970. if ( clear !== 0 ) {
  48971. let clearColor;
  48972. if ( descriptor.clearColorValue ) {
  48973. clearColor = descriptor.clearColorValue;
  48974. } else {
  48975. clearColor = this.getClearColor();
  48976. }
  48977. const clearDepth = renderer.getClearDepth();
  48978. const clearStencil = renderer.getClearStencil();
  48979. if ( depth ) this.state.setDepthMask( true );
  48980. if ( descriptor.textures === null ) {
  48981. gl.clearColor( clearColor.r, clearColor.g, clearColor.b, clearColor.a );
  48982. gl.clear( clear );
  48983. } else {
  48984. if ( setFrameBuffer ) this._setFramebuffer( descriptor );
  48985. if ( color ) {
  48986. for ( let i = 0; i < descriptor.textures.length; i ++ ) {
  48987. if ( i === 0 ) {
  48988. gl.clearBufferfv( gl.COLOR, i, [ clearColor.r, clearColor.g, clearColor.b, clearColor.a ] );
  48989. } else {
  48990. gl.clearBufferfv( gl.COLOR, i, [ 0, 0, 0, 1 ] );
  48991. }
  48992. }
  48993. }
  48994. if ( depth && stencil ) {
  48995. gl.clearBufferfi( gl.DEPTH_STENCIL, 0, clearDepth, clearStencil );
  48996. } else if ( depth ) {
  48997. gl.clearBufferfv( gl.DEPTH, 0, [ clearDepth ] );
  48998. } else if ( stencil ) {
  48999. gl.clearBufferiv( gl.STENCIL, 0, [ clearStencil ] );
  49000. }
  49001. if ( setFrameBuffer && resolveRenderTarget ) this._resolveRenderTarget( descriptor );
  49002. }
  49003. }
  49004. }
  49005. /**
  49006. * This method is executed at the beginning of a compute call and
  49007. * prepares the state for upcoming compute tasks.
  49008. *
  49009. * @param {Node|Array<Node>} computeGroup - The compute node(s).
  49010. */
  49011. beginCompute( computeGroup ) {
  49012. const { state, gl } = this;
  49013. //
  49014. state.bindFramebuffer( gl.FRAMEBUFFER, null );
  49015. this.initTimestampQuery( TimestampQuery.COMPUTE, this.getTimestampUID( computeGroup ) );
  49016. }
  49017. /**
  49018. * Executes a compute command for the given compute node.
  49019. *
  49020. * @param {Node|Array<Node>} computeGroup - The group of compute nodes of a compute call. Can be a single compute node.
  49021. * @param {Node} computeNode - The compute node.
  49022. * @param {Array<BindGroup>} bindings - The bindings.
  49023. * @param {ComputePipeline} pipeline - The compute pipeline.
  49024. * @param {?number} [count=null] - The count of compute invocations. If `null`, the count is determined by the compute node.
  49025. */
  49026. compute( computeGroup, computeNode, bindings, pipeline, count = null ) {
  49027. const { state, gl } = this;
  49028. if ( this.discard === false ) {
  49029. // required here to handle async behaviour of render.compute()
  49030. state.enable( gl.RASTERIZER_DISCARD );
  49031. this.discard = true;
  49032. }
  49033. const { programGPU, transformBuffers, attributes } = this.get( pipeline );
  49034. const vaoKey = this._getVaoKey( attributes );
  49035. const vaoGPU = this.vaoCache[ vaoKey ];
  49036. if ( vaoGPU === undefined ) {
  49037. this.vaoCache[ vaoKey ] = this._createVao( attributes );
  49038. } else {
  49039. state.setVertexState( vaoGPU );
  49040. }
  49041. state.useProgram( programGPU );
  49042. this._bindUniforms( bindings );
  49043. const transformFeedbackGPU = this._getTransformFeedback( transformBuffers );
  49044. gl.bindTransformFeedback( gl.TRANSFORM_FEEDBACK, transformFeedbackGPU );
  49045. gl.beginTransformFeedback( gl.POINTS );
  49046. count = ( count !== null ) ? count : computeNode.count;
  49047. if ( Array.isArray( count ) ) {
  49048. warnOnce( 'WebGLBackend.compute(): The count parameter must be a single number, not an array.' );
  49049. count = count[ 0 ];
  49050. } else if ( count && typeof count === 'object' && count.isIndirectStorageBufferAttribute ) {
  49051. warnOnce( 'WebGLBackend.compute(): The count parameter must be a single number, not IndirectStorageBufferAttribute' );
  49052. count = computeNode.count;
  49053. }
  49054. if ( attributes[ 0 ].isStorageInstancedBufferAttribute ) {
  49055. gl.drawArraysInstanced( gl.POINTS, 0, 1, count );
  49056. } else {
  49057. gl.drawArrays( gl.POINTS, 0, count );
  49058. }
  49059. gl.endTransformFeedback();
  49060. gl.bindTransformFeedback( gl.TRANSFORM_FEEDBACK, null );
  49061. // switch active buffers
  49062. for ( let i = 0; i < transformBuffers.length; i ++ ) {
  49063. const dualAttributeData = transformBuffers[ i ];
  49064. if ( dualAttributeData.pbo && this.has( dualAttributeData.pbo ) ) {
  49065. this.textureUtils.copyBufferToTexture( dualAttributeData.transformBuffer, dualAttributeData.pbo );
  49066. }
  49067. dualAttributeData.switchBuffers();
  49068. }
  49069. }
  49070. /**
  49071. * This method is executed at the end of a compute call and
  49072. * finalizes work after compute tasks.
  49073. *
  49074. * @param {Node|Array<Node>} computeGroup - The compute node(s).
  49075. */
  49076. finishCompute( computeGroup ) {
  49077. const { state, gl } = this;
  49078. this.discard = false;
  49079. state.disable( gl.RASTERIZER_DISCARD );
  49080. this.prepareTimestampBuffer( TimestampQuery.COMPUTE, this.getTimestampUID( computeGroup ) );
  49081. if ( this._currentContext ) {
  49082. this._setFramebuffer( this._currentContext );
  49083. }
  49084. }
  49085. /**
  49086. * Internal to determine if the current render target is a render target array with depth 2D array texture.
  49087. *
  49088. * @param {RenderContext} renderContext - The render context.
  49089. * @return {boolean} Whether the render target is a render target array with depth 2D array texture.
  49090. *
  49091. * @private
  49092. */
  49093. _isRenderCameraDepthArray( renderContext ) {
  49094. return renderContext.depthTexture && renderContext.depthTexture.isArrayTexture && renderContext.camera.isArrayCamera;
  49095. }
  49096. /**
  49097. * Executes a draw command for the given render object.
  49098. *
  49099. * @param {RenderObject} renderObject - The render object to draw.
  49100. * @param {Info} info - Holds a series of statistical information about the GPU memory and the rendering process.
  49101. */
  49102. draw( renderObject/*, info*/ ) {
  49103. const { object, pipeline, material, context, hardwareClippingPlanes } = renderObject;
  49104. const { programGPU } = this.get( pipeline );
  49105. const { gl, state } = this;
  49106. const contextData = this.get( context );
  49107. const drawParams = renderObject.getDrawParameters();
  49108. if ( drawParams === null ) return;
  49109. //
  49110. this._bindUniforms( renderObject.getBindings() );
  49111. const frontFaceCW = ( object.isMesh && object.matrixWorld.determinant() < 0 );
  49112. state.setMaterial( material, frontFaceCW, hardwareClippingPlanes );
  49113. if ( context.textures !== null && context.textures.length > 1 ) {
  49114. state.setMRTBlending( context.textures );
  49115. }
  49116. state.useProgram( programGPU );
  49117. // vertex state
  49118. const attributes = renderObject.getAttributes();
  49119. const attributesData = this.get( attributes );
  49120. let vaoGPU = attributesData.vaoGPU;
  49121. if ( vaoGPU === undefined ) {
  49122. const vaoKey = this._getVaoKey( attributes );
  49123. vaoGPU = this.vaoCache[ vaoKey ];
  49124. if ( vaoGPU === undefined ) {
  49125. vaoGPU = this._createVao( attributes );
  49126. this.vaoCache[ vaoKey ] = vaoGPU;
  49127. attributesData.vaoGPU = vaoGPU;
  49128. }
  49129. }
  49130. const index = renderObject.getIndex();
  49131. const indexGPU = ( index !== null ) ? this.get( index ).bufferGPU : null;
  49132. state.setVertexState( vaoGPU, indexGPU );
  49133. //
  49134. const lastObject = contextData.lastOcclusionObject;
  49135. if ( lastObject !== object && lastObject !== undefined ) {
  49136. if ( lastObject !== null && lastObject.occlusionTest === true ) {
  49137. gl.endQuery( gl.ANY_SAMPLES_PASSED );
  49138. contextData.occlusionQueryIndex ++;
  49139. }
  49140. if ( object.occlusionTest === true ) {
  49141. const query = gl.createQuery();
  49142. gl.beginQuery( gl.ANY_SAMPLES_PASSED, query );
  49143. contextData.occlusionQueries[ contextData.occlusionQueryIndex ] = query;
  49144. contextData.occlusionQueryObjects[ contextData.occlusionQueryIndex ] = object;
  49145. }
  49146. contextData.lastOcclusionObject = object;
  49147. }
  49148. //
  49149. const renderer = this.bufferRenderer;
  49150. if ( object.isPoints ) renderer.mode = gl.POINTS;
  49151. else if ( object.isLineSegments ) renderer.mode = gl.LINES;
  49152. else if ( object.isLine ) renderer.mode = gl.LINE_STRIP;
  49153. else if ( object.isLineLoop ) renderer.mode = gl.LINE_LOOP;
  49154. else {
  49155. if ( material.wireframe === true ) {
  49156. state.setLineWidth( material.wireframeLinewidth * this.renderer.getPixelRatio() );
  49157. renderer.mode = gl.LINES;
  49158. } else {
  49159. renderer.mode = gl.TRIANGLES;
  49160. }
  49161. }
  49162. //
  49163. const { vertexCount, instanceCount } = drawParams;
  49164. let { firstVertex } = drawParams;
  49165. renderer.object = object;
  49166. if ( index !== null ) {
  49167. firstVertex *= index.array.BYTES_PER_ELEMENT;
  49168. const indexData = this.get( index );
  49169. renderer.index = index.count;
  49170. renderer.type = indexData.type;
  49171. } else {
  49172. renderer.index = 0;
  49173. }
  49174. const draw = () => {
  49175. if ( object.isBatchedMesh ) {
  49176. if ( object._multiDrawInstances !== null ) {
  49177. // @deprecated, r174
  49178. warnOnce( 'WebGLBackend: renderMultiDrawInstances has been deprecated and will be removed in r184. Append to renderMultiDraw arguments and use indirection.' );
  49179. renderer.renderMultiDrawInstances( object._multiDrawStarts, object._multiDrawCounts, object._multiDrawCount, object._multiDrawInstances );
  49180. } else if ( ! this.hasFeature( 'WEBGL_multi_draw' ) ) {
  49181. warnOnce( 'WebGLBackend: WEBGL_multi_draw not supported.' );
  49182. } else {
  49183. renderer.renderMultiDraw( object._multiDrawStarts, object._multiDrawCounts, object._multiDrawCount );
  49184. }
  49185. } else if ( instanceCount > 1 ) {
  49186. renderer.renderInstances( firstVertex, vertexCount, instanceCount );
  49187. } else {
  49188. renderer.render( firstVertex, vertexCount );
  49189. }
  49190. };
  49191. if ( renderObject.camera.isArrayCamera === true && renderObject.camera.cameras.length > 0 && renderObject.camera.isMultiViewCamera === false ) {
  49192. const cameraData = this.get( renderObject.camera );
  49193. const cameras = renderObject.camera.cameras;
  49194. const cameraIndex = renderObject.getBindingGroup( 'cameraIndex' ).bindings[ 0 ];
  49195. if ( cameraData.indexesGPU === undefined || cameraData.indexesGPU.length !== cameras.length ) {
  49196. const data = new Uint32Array( [ 0, 0, 0, 0 ] );
  49197. const indexesGPU = [];
  49198. for ( let i = 0, len = cameras.length; i < len; i ++ ) {
  49199. const bufferGPU = gl.createBuffer();
  49200. data[ 0 ] = i;
  49201. gl.bindBuffer( gl.UNIFORM_BUFFER, bufferGPU );
  49202. gl.bufferData( gl.UNIFORM_BUFFER, data, gl.STATIC_DRAW );
  49203. indexesGPU.push( bufferGPU );
  49204. }
  49205. cameraData.indexesGPU = indexesGPU; // TODO: Create a global library for this
  49206. }
  49207. const cameraIndexData = this.get( cameraIndex );
  49208. const pixelRatio = this.renderer.getPixelRatio();
  49209. const renderTarget = this._currentContext.renderTarget;
  49210. const isRenderCameraDepthArray = this._isRenderCameraDepthArray( this._currentContext );
  49211. const prevActiveCubeFace = this._currentContext.activeCubeFace;
  49212. if ( isRenderCameraDepthArray ) {
  49213. // Clear the depth texture
  49214. const textureData = this.get( renderTarget.depthTexture );
  49215. if ( textureData.clearedRenderId !== this.renderer._nodes.nodeFrame.renderId ) {
  49216. textureData.clearedRenderId = this.renderer._nodes.nodeFrame.renderId;
  49217. const { stencilBuffer } = renderTarget;
  49218. for ( let i = 0, len = cameras.length; i < len; i ++ ) {
  49219. this.renderer._activeCubeFace = i;
  49220. this._currentContext.activeCubeFace = i;
  49221. this._setFramebuffer( this._currentContext );
  49222. this.clear( false, true, stencilBuffer, this._currentContext, false, false );
  49223. }
  49224. this.renderer._activeCubeFace = prevActiveCubeFace;
  49225. this._currentContext.activeCubeFace = prevActiveCubeFace;
  49226. }
  49227. }
  49228. for ( let i = 0, len = cameras.length; i < len; i ++ ) {
  49229. const subCamera = cameras[ i ];
  49230. if ( object.layers.test( subCamera.layers ) ) {
  49231. if ( isRenderCameraDepthArray ) {
  49232. // Update the active layer
  49233. this.renderer._activeCubeFace = i;
  49234. this._currentContext.activeCubeFace = i;
  49235. this._setFramebuffer( this._currentContext );
  49236. }
  49237. const vp = subCamera.viewport;
  49238. if ( vp !== undefined ) {
  49239. const x = vp.x * pixelRatio;
  49240. const y = vp.y * pixelRatio;
  49241. const width = vp.width * pixelRatio;
  49242. const height = vp.height * pixelRatio;
  49243. state.viewport(
  49244. Math.floor( x ),
  49245. Math.floor( renderObject.context.height - height - y ),
  49246. Math.floor( width ),
  49247. Math.floor( height )
  49248. );
  49249. }
  49250. state.bindBufferBase( gl.UNIFORM_BUFFER, cameraIndexData.index, cameraData.indexesGPU[ i ] );
  49251. draw();
  49252. }
  49253. this._currentContext.activeCubeFace = prevActiveCubeFace;
  49254. this.renderer._activeCubeFace = prevActiveCubeFace;
  49255. }
  49256. } else {
  49257. draw();
  49258. }
  49259. }
  49260. /**
  49261. * Explain why always null is returned.
  49262. *
  49263. * @param {RenderObject} renderObject - The render object.
  49264. * @return {boolean} Whether the render pipeline requires an update or not.
  49265. */
  49266. needsRenderUpdate( /*renderObject*/ ) {
  49267. return false;
  49268. }
  49269. /**
  49270. * Explain why no cache key is computed.
  49271. *
  49272. * @param {RenderObject} renderObject - The render object.
  49273. * @return {string} The cache key.
  49274. */
  49275. getRenderCacheKey( /*renderObject*/ ) {
  49276. return '';
  49277. }
  49278. // textures
  49279. /**
  49280. * Creates a default texture for the given texture that can be used
  49281. * as a placeholder until the actual texture is ready for usage.
  49282. *
  49283. * @param {Texture} texture - The texture to create a default texture for.
  49284. */
  49285. createDefaultTexture( texture ) {
  49286. this.textureUtils.createDefaultTexture( texture );
  49287. }
  49288. /**
  49289. * Defines a texture on the GPU for the given texture object.
  49290. *
  49291. * @param {Texture} texture - The texture.
  49292. * @param {Object} [options={}] - Optional configuration parameter.
  49293. */
  49294. createTexture( texture, options ) {
  49295. this.textureUtils.createTexture( texture, options );
  49296. }
  49297. /**
  49298. * Uploads the updated texture data to the GPU.
  49299. *
  49300. * @param {Texture} texture - The texture.
  49301. * @param {Object} [options={}] - Optional configuration parameter.
  49302. */
  49303. updateTexture( texture, options ) {
  49304. this.textureUtils.updateTexture( texture, options );
  49305. }
  49306. /**
  49307. * Generates mipmaps for the given texture.
  49308. *
  49309. * @param {Texture} texture - The texture.
  49310. */
  49311. generateMipmaps( texture ) {
  49312. this.textureUtils.generateMipmaps( texture );
  49313. }
  49314. /**
  49315. * Destroys the GPU data for the given texture object.
  49316. *
  49317. * @param {Texture} texture - The texture.
  49318. * @param {boolean} [isDefaultTexture=false] - Whether the texture uses a default GPU texture or not.
  49319. */
  49320. destroyTexture( texture, isDefaultTexture = false ) {
  49321. this.textureUtils.destroyTexture( texture, isDefaultTexture );
  49322. }
  49323. /**
  49324. * Returns texture data as a typed array.
  49325. *
  49326. * @async
  49327. * @param {Texture} texture - The texture to copy.
  49328. * @param {number} x - The x coordinate of the copy origin.
  49329. * @param {number} y - The y coordinate of the copy origin.
  49330. * @param {number} width - The width of the copy.
  49331. * @param {number} height - The height of the copy.
  49332. * @param {number} faceIndex - The face index.
  49333. * @return {Promise<TypedArray>} A Promise that resolves with a typed array when the copy operation has finished.
  49334. */
  49335. async copyTextureToBuffer( texture, x, y, width, height, faceIndex ) {
  49336. return this.textureUtils.copyTextureToBuffer( texture, x, y, width, height, faceIndex );
  49337. }
  49338. /**
  49339. * This method does nothing since WebGL 2 has no concept of samplers.
  49340. *
  49341. * @param {Texture} texture - The texture to update the sampler for.
  49342. * @return {string} The current sampler key.
  49343. */
  49344. updateSampler( /*texture*/ ) {
  49345. return '';
  49346. }
  49347. // node builder
  49348. /**
  49349. * Returns a node builder for the given render object.
  49350. *
  49351. * @param {RenderObject} object - The render object.
  49352. * @param {Renderer} renderer - The renderer.
  49353. * @return {GLSLNodeBuilder} The node builder.
  49354. */
  49355. createNodeBuilder( object, renderer ) {
  49356. return new GLSLNodeBuilder( object, renderer );
  49357. }
  49358. // program
  49359. /**
  49360. * Creates a shader program from the given programmable stage.
  49361. *
  49362. * @param {ProgrammableStage} program - The programmable stage.
  49363. */
  49364. createProgram( program ) {
  49365. const gl = this.gl;
  49366. const { stage, code } = program;
  49367. const shader = stage === 'fragment' ? gl.createShader( gl.FRAGMENT_SHADER ) : gl.createShader( gl.VERTEX_SHADER );
  49368. gl.shaderSource( shader, code );
  49369. gl.compileShader( shader );
  49370. this.set( program, {
  49371. shaderGPU: shader
  49372. } );
  49373. }
  49374. /**
  49375. * Destroys the shader program of the given programmable stage.
  49376. *
  49377. * @param {ProgrammableStage} program - The programmable stage.
  49378. */
  49379. destroyProgram( program ) {
  49380. this.delete( program );
  49381. }
  49382. /**
  49383. * Creates a render pipeline for the given render object.
  49384. *
  49385. * @param {RenderObject} renderObject - The render object.
  49386. * @param {Array<Promise>} promises - An array of compilation promises which are used in `compileAsync()`.
  49387. */
  49388. createRenderPipeline( renderObject, promises ) {
  49389. const gl = this.gl;
  49390. const pipeline = renderObject.pipeline;
  49391. // Program
  49392. const { fragmentProgram, vertexProgram } = pipeline;
  49393. const programGPU = gl.createProgram();
  49394. const fragmentShader = this.get( fragmentProgram ).shaderGPU;
  49395. const vertexShader = this.get( vertexProgram ).shaderGPU;
  49396. gl.attachShader( programGPU, fragmentShader );
  49397. gl.attachShader( programGPU, vertexShader );
  49398. gl.linkProgram( programGPU );
  49399. this.set( pipeline, {
  49400. programGPU,
  49401. fragmentShader,
  49402. vertexShader
  49403. } );
  49404. if ( promises !== null && this.parallel ) {
  49405. const p = new Promise( ( resolve /*, reject*/ ) => {
  49406. const parallel = this.parallel;
  49407. const checkStatus = () => {
  49408. if ( gl.getProgramParameter( programGPU, parallel.COMPLETION_STATUS_KHR ) ) {
  49409. this._completeCompile( renderObject, pipeline );
  49410. resolve();
  49411. } else {
  49412. requestAnimationFrame( checkStatus );
  49413. }
  49414. };
  49415. checkStatus();
  49416. } );
  49417. promises.push( p );
  49418. return;
  49419. }
  49420. this._completeCompile( renderObject, pipeline );
  49421. }
  49422. /**
  49423. * Formats the source code of error messages.
  49424. *
  49425. * @private
  49426. * @param {string} string - The code.
  49427. * @param {number} errorLine - The error line.
  49428. * @return {string} The formatted code.
  49429. */
  49430. _handleSource( string, errorLine ) {
  49431. const lines = string.split( '\n' );
  49432. const lines2 = [];
  49433. const from = Math.max( errorLine - 6, 0 );
  49434. const to = Math.min( errorLine + 6, lines.length );
  49435. for ( let i = from; i < to; i ++ ) {
  49436. const line = i + 1;
  49437. lines2.push( `${line === errorLine ? '>' : ' '} ${line}: ${lines[ i ]}` );
  49438. }
  49439. return lines2.join( '\n' );
  49440. }
  49441. /**
  49442. * Gets the shader compilation errors from the info log.
  49443. *
  49444. * @private
  49445. * @param {WebGL2RenderingContext} gl - The rendering context.
  49446. * @param {WebGLShader} shader - The WebGL shader object.
  49447. * @param {string} type - The shader type.
  49448. * @return {string} The shader errors.
  49449. */
  49450. _getShaderErrors( gl, shader, type ) {
  49451. const status = gl.getShaderParameter( shader, gl.COMPILE_STATUS );
  49452. const shaderInfoLog = gl.getShaderInfoLog( shader ) || '';
  49453. const errors = shaderInfoLog.trim();
  49454. if ( status && errors === '' ) return '';
  49455. const errorMatches = /ERROR: 0:(\d+)/.exec( errors );
  49456. if ( errorMatches ) {
  49457. const errorLine = parseInt( errorMatches[ 1 ] );
  49458. return type.toUpperCase() + '\n\n' + errors + '\n\n' + this._handleSource( gl.getShaderSource( shader ), errorLine );
  49459. } else {
  49460. return errors;
  49461. }
  49462. }
  49463. /**
  49464. * Logs shader compilation errors.
  49465. *
  49466. * @private
  49467. * @param {WebGLProgram} programGPU - The WebGL program.
  49468. * @param {WebGLShader} glFragmentShader - The fragment shader as a native WebGL shader object.
  49469. * @param {WebGLShader} glVertexShader - The vertex shader as a native WebGL shader object.
  49470. */
  49471. _logProgramError( programGPU, glFragmentShader, glVertexShader ) {
  49472. if ( this.renderer.debug.checkShaderErrors ) {
  49473. const gl = this.gl;
  49474. const programInfoLog = gl.getProgramInfoLog( programGPU ) || '';
  49475. const programLog = programInfoLog.trim();
  49476. if ( gl.getProgramParameter( programGPU, gl.LINK_STATUS ) === false ) {
  49477. if ( typeof this.renderer.debug.onShaderError === 'function' ) {
  49478. this.renderer.debug.onShaderError( gl, programGPU, glVertexShader, glFragmentShader );
  49479. } else {
  49480. // default error reporting
  49481. const vertexErrors = this._getShaderErrors( gl, glVertexShader, 'vertex' );
  49482. const fragmentErrors = this._getShaderErrors( gl, glFragmentShader, 'fragment' );
  49483. error(
  49484. 'THREE.WebGLProgram: Shader Error ' + gl.getError() + ' - ' +
  49485. 'VALIDATE_STATUS ' + gl.getProgramParameter( programGPU, gl.VALIDATE_STATUS ) + '\n\n' +
  49486. 'Program Info Log: ' + programLog + '\n' +
  49487. vertexErrors + '\n' +
  49488. fragmentErrors
  49489. );
  49490. }
  49491. } else if ( programLog !== '' ) {
  49492. warn( 'WebGLProgram: Program Info Log:', programLog );
  49493. }
  49494. }
  49495. }
  49496. /**
  49497. * Completes the shader program setup for the given render object.
  49498. *
  49499. * @private
  49500. * @param {RenderObject} renderObject - The render object.
  49501. * @param {RenderPipeline} pipeline - The render pipeline.
  49502. */
  49503. _completeCompile( renderObject, pipeline ) {
  49504. const { state, gl } = this;
  49505. const pipelineData = this.get( pipeline );
  49506. const { programGPU, fragmentShader, vertexShader } = pipelineData;
  49507. if ( gl.getProgramParameter( programGPU, gl.LINK_STATUS ) === false ) {
  49508. this._logProgramError( programGPU, fragmentShader, vertexShader );
  49509. }
  49510. state.useProgram( programGPU );
  49511. // Bindings
  49512. const bindings = renderObject.getBindings();
  49513. this._setupBindings( bindings, programGPU );
  49514. //
  49515. this.set( pipeline, {
  49516. programGPU
  49517. } );
  49518. }
  49519. /**
  49520. * Creates a compute pipeline for the given compute node.
  49521. *
  49522. * @param {ComputePipeline} computePipeline - The compute pipeline.
  49523. * @param {Array<BindGroup>} bindings - The bindings.
  49524. */
  49525. createComputePipeline( computePipeline, bindings ) {
  49526. const { state, gl } = this;
  49527. // Program
  49528. const fragmentProgram = {
  49529. stage: 'fragment',
  49530. code: '#version 300 es\nprecision highp float;\nvoid main() {}'
  49531. };
  49532. this.createProgram( fragmentProgram );
  49533. const { computeProgram } = computePipeline;
  49534. const programGPU = gl.createProgram();
  49535. const fragmentShader = this.get( fragmentProgram ).shaderGPU;
  49536. const vertexShader = this.get( computeProgram ).shaderGPU;
  49537. const transforms = computeProgram.transforms;
  49538. const transformVaryingNames = [];
  49539. const transformAttributeNodes = [];
  49540. for ( let i = 0; i < transforms.length; i ++ ) {
  49541. const transform = transforms[ i ];
  49542. transformVaryingNames.push( transform.varyingName );
  49543. transformAttributeNodes.push( transform.attributeNode );
  49544. }
  49545. gl.attachShader( programGPU, fragmentShader );
  49546. gl.attachShader( programGPU, vertexShader );
  49547. gl.transformFeedbackVaryings(
  49548. programGPU,
  49549. transformVaryingNames,
  49550. gl.SEPARATE_ATTRIBS
  49551. );
  49552. gl.linkProgram( programGPU );
  49553. if ( gl.getProgramParameter( programGPU, gl.LINK_STATUS ) === false ) {
  49554. this._logProgramError( programGPU, fragmentShader, vertexShader );
  49555. }
  49556. state.useProgram( programGPU );
  49557. // Bindings
  49558. this._setupBindings( bindings, programGPU );
  49559. const attributeNodes = computeProgram.attributes;
  49560. const attributes = [];
  49561. const transformBuffers = [];
  49562. for ( let i = 0; i < attributeNodes.length; i ++ ) {
  49563. const attribute = attributeNodes[ i ].node.attribute;
  49564. attributes.push( attribute );
  49565. if ( ! this.has( attribute ) ) this.attributeUtils.createAttribute( attribute, gl.ARRAY_BUFFER );
  49566. }
  49567. for ( let i = 0; i < transformAttributeNodes.length; i ++ ) {
  49568. const attribute = transformAttributeNodes[ i ].attribute;
  49569. if ( ! this.has( attribute ) ) this.attributeUtils.createAttribute( attribute, gl.ARRAY_BUFFER );
  49570. const attributeData = this.get( attribute );
  49571. transformBuffers.push( attributeData );
  49572. }
  49573. //
  49574. this.set( computePipeline, {
  49575. programGPU,
  49576. transformBuffers,
  49577. attributes
  49578. } );
  49579. }
  49580. /**
  49581. * Creates bindings from the given bind group definition.
  49582. *
  49583. * @param {BindGroup} bindGroup - The bind group.
  49584. * @param {Array<BindGroup>} bindings - Array of bind groups.
  49585. * @param {number} cacheIndex - The cache index.
  49586. * @param {number} version - The version.
  49587. */
  49588. createBindings( bindGroup, bindings /*, cacheIndex, version*/ ) {
  49589. if ( this._knownBindings.has( bindings ) === false ) {
  49590. this._knownBindings.add( bindings );
  49591. let uniformBuffers = 0;
  49592. let textures = 0;
  49593. for ( const bindGroup of bindings ) {
  49594. this.set( bindGroup, {
  49595. textures: textures,
  49596. uniformBuffers: uniformBuffers
  49597. } );
  49598. for ( const binding of bindGroup.bindings ) {
  49599. if ( binding.isUniformBuffer ) uniformBuffers ++;
  49600. if ( binding.isSampledTexture ) textures ++;
  49601. }
  49602. }
  49603. }
  49604. this.updateBindings( bindGroup, bindings );
  49605. }
  49606. /**
  49607. * Updates the given bind group definition.
  49608. *
  49609. * @param {BindGroup} bindGroup - The bind group.
  49610. * @param {Array<BindGroup>} bindings - Array of bind groups.
  49611. * @param {number} cacheIndex - The cache index.
  49612. * @param {number} version - The version.
  49613. */
  49614. updateBindings( bindGroup /*, bindings, cacheIndex, version*/ ) {
  49615. const { gl } = this;
  49616. const bindGroupData = this.get( bindGroup );
  49617. let i = bindGroupData.uniformBuffers;
  49618. let t = bindGroupData.textures;
  49619. for ( const binding of bindGroup.bindings ) {
  49620. const map = this.get( binding );
  49621. if ( binding.isUniformsGroup || binding.isUniformBuffer ) {
  49622. const array = binding.buffer;
  49623. let { bufferGPU } = this.get( array );
  49624. if ( bufferGPU === undefined ) {
  49625. // create
  49626. bufferGPU = gl.createBuffer();
  49627. gl.bindBuffer( gl.UNIFORM_BUFFER, bufferGPU );
  49628. gl.bufferData( gl.UNIFORM_BUFFER, array.byteLength, gl.DYNAMIC_DRAW );
  49629. this.set( array, { bufferGPU } );
  49630. } else {
  49631. gl.bindBuffer( gl.UNIFORM_BUFFER, bufferGPU );
  49632. }
  49633. // update
  49634. const updateRanges = binding.updateRanges;
  49635. gl.bindBuffer( gl.UNIFORM_BUFFER, bufferGPU );
  49636. if ( updateRanges.length === 0 ) {
  49637. gl.bufferData( gl.UNIFORM_BUFFER, array, gl.DYNAMIC_DRAW );
  49638. } else {
  49639. const isTyped = isTypedArray( array );
  49640. const byteOffsetFactor = isTyped ? 1 : array.BYTES_PER_ELEMENT;
  49641. for ( let i = 0, l = updateRanges.length; i < l; i ++ ) {
  49642. const range = updateRanges[ i ];
  49643. const dataOffset = range.start * byteOffsetFactor;
  49644. const size = range.count * byteOffsetFactor;
  49645. const bufferOffset = dataOffset * ( isTyped ? array.BYTES_PER_ELEMENT : 1 ); // bufferOffset is always in bytes
  49646. gl.bufferSubData( gl.UNIFORM_BUFFER, bufferOffset, array, dataOffset, size );
  49647. }
  49648. }
  49649. map.index = i ++;
  49650. map.bufferGPU = bufferGPU;
  49651. this.set( binding, map );
  49652. } else if ( binding.isSampledTexture ) {
  49653. const { textureGPU, glTextureType } = this.get( binding.texture );
  49654. map.index = t ++;
  49655. map.textureGPU = textureGPU;
  49656. map.glTextureType = glTextureType;
  49657. this.set( binding, map );
  49658. }
  49659. }
  49660. }
  49661. /**
  49662. * Updates a buffer binding.
  49663. *
  49664. * @param {Buffer} binding - The buffer binding to update.
  49665. */
  49666. updateBinding( binding ) {
  49667. const gl = this.gl;
  49668. if ( binding.isUniformsGroup || binding.isUniformBuffer ) {
  49669. const bindingData = this.get( binding );
  49670. const bufferGPU = bindingData.bufferGPU;
  49671. const array = binding.buffer;
  49672. const updateRanges = binding.updateRanges;
  49673. gl.bindBuffer( gl.UNIFORM_BUFFER, bufferGPU );
  49674. if ( updateRanges.length === 0 ) {
  49675. gl.bufferData( gl.UNIFORM_BUFFER, array, gl.DYNAMIC_DRAW );
  49676. } else {
  49677. const isTyped = isTypedArray( array );
  49678. const byteOffsetFactor = isTyped ? 1 : array.BYTES_PER_ELEMENT;
  49679. for ( let i = 0, l = updateRanges.length; i < l; i ++ ) {
  49680. const range = updateRanges[ i ];
  49681. const dataOffset = range.start * byteOffsetFactor;
  49682. const size = range.count * byteOffsetFactor;
  49683. const bufferOffset = dataOffset * ( isTyped ? array.BYTES_PER_ELEMENT : 1 ); // bufferOffset is always in bytes
  49684. gl.bufferSubData( gl.UNIFORM_BUFFER, bufferOffset, array, dataOffset, size );
  49685. }
  49686. }
  49687. }
  49688. }
  49689. // attributes
  49690. /**
  49691. * Creates the GPU buffer of an indexed shader attribute.
  49692. *
  49693. * @param {BufferAttribute} attribute - The indexed buffer attribute.
  49694. */
  49695. createIndexAttribute( attribute ) {
  49696. const gl = this.gl;
  49697. this.attributeUtils.createAttribute( attribute, gl.ELEMENT_ARRAY_BUFFER );
  49698. }
  49699. /**
  49700. * Creates the GPU buffer of a shader attribute.
  49701. *
  49702. * @param {BufferAttribute} attribute - The buffer attribute.
  49703. */
  49704. createAttribute( attribute ) {
  49705. if ( this.has( attribute ) ) return;
  49706. const gl = this.gl;
  49707. this.attributeUtils.createAttribute( attribute, gl.ARRAY_BUFFER );
  49708. }
  49709. /**
  49710. * Creates the GPU buffer of a storage attribute.
  49711. *
  49712. * @param {BufferAttribute} attribute - The buffer attribute.
  49713. */
  49714. createStorageAttribute( attribute ) {
  49715. if ( this.has( attribute ) ) return;
  49716. const gl = this.gl;
  49717. this.attributeUtils.createAttribute( attribute, gl.ARRAY_BUFFER );
  49718. }
  49719. /**
  49720. * Updates the GPU buffer of a shader attribute.
  49721. *
  49722. * @param {BufferAttribute} attribute - The buffer attribute to update.
  49723. */
  49724. updateAttribute( attribute ) {
  49725. this.attributeUtils.updateAttribute( attribute );
  49726. }
  49727. /**
  49728. * Destroys the GPU buffer of a shader attribute.
  49729. *
  49730. * @param {BufferAttribute} attribute - The buffer attribute to destroy.
  49731. */
  49732. destroyAttribute( attribute ) {
  49733. this.attributeUtils.destroyAttribute( attribute );
  49734. }
  49735. /**
  49736. * Checks if the given feature is supported by the backend.
  49737. *
  49738. * @param {string} name - The feature's name.
  49739. * @return {boolean} Whether the feature is supported or not.
  49740. */
  49741. hasFeature( name ) {
  49742. const keysMatching = Object.keys( GLFeatureName ).filter( key => GLFeatureName[ key ] === name );
  49743. const extensions = this.extensions;
  49744. for ( let i = 0; i < keysMatching.length; i ++ ) {
  49745. if ( extensions.has( keysMatching[ i ] ) ) return true;
  49746. }
  49747. return false;
  49748. }
  49749. /**
  49750. * Returns the maximum anisotropy texture filtering value.
  49751. *
  49752. * @return {number} The maximum anisotropy texture filtering value.
  49753. */
  49754. getMaxAnisotropy() {
  49755. return this.capabilities.getMaxAnisotropy();
  49756. }
  49757. /**
  49758. * Copies data of the given source texture to the given destination texture.
  49759. *
  49760. * @param {Texture} srcTexture - The source texture.
  49761. * @param {Texture} dstTexture - The destination texture.
  49762. * @param {?(Box3|Box2)} [srcRegion=null] - The region of the source texture to copy.
  49763. * @param {?(Vector2|Vector3)} [dstPosition=null] - The destination position of the copy.
  49764. * @param {number} [srcLevel=0] - The source mip level to copy from.
  49765. * @param {number} [dstLevel=0] - The destination mip level to copy to.
  49766. */
  49767. copyTextureToTexture( srcTexture, dstTexture, srcRegion = null, dstPosition = null, srcLevel = 0, dstLevel = 0 ) {
  49768. this.textureUtils.copyTextureToTexture( srcTexture, dstTexture, srcRegion, dstPosition, srcLevel, dstLevel );
  49769. }
  49770. /**
  49771. * Copies the current bound framebuffer to the given texture.
  49772. *
  49773. * @param {Texture} texture - The destination texture.
  49774. * @param {RenderContext} renderContext - The render context.
  49775. * @param {Vector4} rectangle - A four dimensional vector defining the origin and dimension of the copy.
  49776. */
  49777. copyFramebufferToTexture( texture, renderContext, rectangle ) {
  49778. this.textureUtils.copyFramebufferToTexture( texture, renderContext, rectangle );
  49779. }
  49780. /**
  49781. * Configures the active framebuffer from the given render context.
  49782. *
  49783. * @private
  49784. * @param {RenderContext} descriptor - The render context.
  49785. */
  49786. _setFramebuffer( descriptor ) {
  49787. const { gl, state } = this;
  49788. let currentFrameBuffer = null;
  49789. if ( descriptor.textures !== null ) {
  49790. const renderTarget = descriptor.renderTarget;
  49791. const renderTargetContextData = this.get( renderTarget );
  49792. const { samples, depthBuffer, stencilBuffer } = renderTarget;
  49793. const isCube = renderTarget.isWebGLCubeRenderTarget === true;
  49794. const isRenderTarget3D = renderTarget.isRenderTarget3D === true;
  49795. const isRenderTargetArray = renderTarget.depth > 1;
  49796. const isXRRenderTarget = renderTarget.isXRRenderTarget === true;
  49797. const _hasExternalTextures = ( isXRRenderTarget === true && renderTarget._hasExternalTextures === true );
  49798. let msaaFb = renderTargetContextData.msaaFrameBuffer;
  49799. let depthRenderbuffer = renderTargetContextData.depthRenderbuffer;
  49800. const multisampledRTTExt = this.extensions.get( 'WEBGL_multisampled_render_to_texture' );
  49801. const multiviewExt = this.extensions.get( 'OVR_multiview2' );
  49802. const useMultisampledRTT = this._useMultisampledExtension( renderTarget );
  49803. const cacheKey = getCacheKey( descriptor );
  49804. let fb;
  49805. if ( isCube ) {
  49806. renderTargetContextData.cubeFramebuffers || ( renderTargetContextData.cubeFramebuffers = {} );
  49807. fb = renderTargetContextData.cubeFramebuffers[ cacheKey ];
  49808. } else if ( isXRRenderTarget && _hasExternalTextures === false ) {
  49809. fb = this._xrFramebuffer;
  49810. } else {
  49811. renderTargetContextData.framebuffers || ( renderTargetContextData.framebuffers = {} );
  49812. fb = renderTargetContextData.framebuffers[ cacheKey ];
  49813. }
  49814. if ( fb === undefined ) {
  49815. fb = gl.createFramebuffer();
  49816. state.bindFramebuffer( gl.FRAMEBUFFER, fb );
  49817. const textures = descriptor.textures;
  49818. const depthInvalidationArray = [];
  49819. if ( isCube ) {
  49820. renderTargetContextData.cubeFramebuffers[ cacheKey ] = fb;
  49821. const { textureGPU } = this.get( textures[ 0 ] );
  49822. const cubeFace = this.renderer._activeCubeFace;
  49823. const mipLevel = this.renderer._activeMipmapLevel;
  49824. gl.framebufferTexture2D( gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + cubeFace, textureGPU, mipLevel );
  49825. } else {
  49826. renderTargetContextData.framebuffers[ cacheKey ] = fb;
  49827. for ( let i = 0; i < textures.length; i ++ ) {
  49828. const texture = textures[ i ];
  49829. const textureData = this.get( texture );
  49830. textureData.renderTarget = descriptor.renderTarget;
  49831. textureData.cacheKey = cacheKey; // required for copyTextureToTexture()
  49832. const attachment = gl.COLOR_ATTACHMENT0 + i;
  49833. if ( renderTarget.multiview ) {
  49834. multiviewExt.framebufferTextureMultisampleMultiviewOVR( gl.FRAMEBUFFER, attachment, textureData.textureGPU, 0, samples, 0, 2 );
  49835. } else if ( isRenderTarget3D || isRenderTargetArray ) {
  49836. const layer = this.renderer._activeCubeFace;
  49837. const mipLevel = this.renderer._activeMipmapLevel;
  49838. gl.framebufferTextureLayer( gl.FRAMEBUFFER, attachment, textureData.textureGPU, mipLevel, layer );
  49839. } else {
  49840. if ( useMultisampledRTT ) {
  49841. multisampledRTTExt.framebufferTexture2DMultisampleEXT( gl.FRAMEBUFFER, attachment, gl.TEXTURE_2D, textureData.textureGPU, 0, samples );
  49842. } else {
  49843. const mipLevel = this.renderer._activeMipmapLevel;
  49844. gl.framebufferTexture2D( gl.FRAMEBUFFER, attachment, gl.TEXTURE_2D, textureData.textureGPU, mipLevel );
  49845. }
  49846. }
  49847. }
  49848. }
  49849. const depthStyle = stencilBuffer ? gl.DEPTH_STENCIL_ATTACHMENT : gl.DEPTH_ATTACHMENT;
  49850. if ( renderTarget._autoAllocateDepthBuffer === true ) {
  49851. const renderbuffer = gl.createRenderbuffer();
  49852. this.textureUtils.setupRenderBufferStorage( renderbuffer, descriptor, 0, useMultisampledRTT );
  49853. renderTargetContextData.xrDepthRenderbuffer = renderbuffer;
  49854. depthInvalidationArray.push( stencilBuffer ? gl.DEPTH_STENCIL_ATTACHMENT : gl.DEPTH_ATTACHMENT );
  49855. gl.bindRenderbuffer( gl.RENDERBUFFER, renderbuffer );
  49856. gl.framebufferRenderbuffer( gl.FRAMEBUFFER, depthStyle, gl.RENDERBUFFER, renderbuffer );
  49857. } else {
  49858. if ( descriptor.depthTexture !== null ) {
  49859. depthInvalidationArray.push( stencilBuffer ? gl.DEPTH_STENCIL_ATTACHMENT : gl.DEPTH_ATTACHMENT );
  49860. const textureData = this.get( descriptor.depthTexture );
  49861. textureData.renderTarget = descriptor.renderTarget;
  49862. textureData.cacheKey = cacheKey; // required for copyTextureToTexture()
  49863. if ( renderTarget.multiview ) {
  49864. multiviewExt.framebufferTextureMultisampleMultiviewOVR( gl.FRAMEBUFFER, depthStyle, textureData.textureGPU, 0, samples, 0, 2 );
  49865. } else if ( _hasExternalTextures && useMultisampledRTT ) {
  49866. multisampledRTTExt.framebufferTexture2DMultisampleEXT( gl.FRAMEBUFFER, depthStyle, gl.TEXTURE_2D, textureData.textureGPU, 0, samples );
  49867. } else {
  49868. if ( descriptor.depthTexture.isArrayTexture ) {
  49869. const layer = this.renderer._activeCubeFace;
  49870. gl.framebufferTextureLayer( gl.FRAMEBUFFER, depthStyle, textureData.textureGPU, 0, layer );
  49871. } else if ( descriptor.depthTexture.isCubeTexture ) {
  49872. const cubeFace = this.renderer._activeCubeFace;
  49873. gl.framebufferTexture2D( gl.FRAMEBUFFER, depthStyle, gl.TEXTURE_CUBE_MAP_POSITIVE_X + cubeFace, textureData.textureGPU, 0 );
  49874. } else {
  49875. gl.framebufferTexture2D( gl.FRAMEBUFFER, depthStyle, gl.TEXTURE_2D, textureData.textureGPU, 0 );
  49876. }
  49877. }
  49878. }
  49879. }
  49880. renderTargetContextData.depthInvalidationArray = depthInvalidationArray;
  49881. } else {
  49882. const isRenderCameraDepthArray = this._isRenderCameraDepthArray( descriptor );
  49883. if ( isRenderCameraDepthArray ) {
  49884. state.bindFramebuffer( gl.FRAMEBUFFER, fb );
  49885. const layer = this.renderer._activeCubeFace;
  49886. const depthData = this.get( descriptor.depthTexture );
  49887. const depthStyle = stencilBuffer ? gl.DEPTH_STENCIL_ATTACHMENT : gl.DEPTH_ATTACHMENT;
  49888. gl.framebufferTextureLayer(
  49889. gl.FRAMEBUFFER,
  49890. depthStyle,
  49891. depthData.textureGPU,
  49892. 0,
  49893. layer
  49894. );
  49895. }
  49896. // rebind external XR textures
  49897. if ( ( isXRRenderTarget || useMultisampledRTT || renderTarget.multiview ) && ( renderTarget._isOpaqueFramebuffer !== true ) ) {
  49898. state.bindFramebuffer( gl.FRAMEBUFFER, fb );
  49899. // rebind color
  49900. const textureData = this.get( descriptor.textures[ 0 ] );
  49901. if ( renderTarget.multiview ) {
  49902. multiviewExt.framebufferTextureMultisampleMultiviewOVR( gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, textureData.textureGPU, 0, samples, 0, 2 );
  49903. } else if ( useMultisampledRTT ) {
  49904. multisampledRTTExt.framebufferTexture2DMultisampleEXT( gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, textureData.textureGPU, 0, samples );
  49905. } else {
  49906. gl.framebufferTexture2D( gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, textureData.textureGPU, 0 );
  49907. }
  49908. // rebind depth
  49909. const depthStyle = stencilBuffer ? gl.DEPTH_STENCIL_ATTACHMENT : gl.DEPTH_ATTACHMENT;
  49910. if ( renderTarget._autoAllocateDepthBuffer === true ) {
  49911. const renderbuffer = renderTargetContextData.xrDepthRenderbuffer;
  49912. gl.bindRenderbuffer( gl.RENDERBUFFER, renderbuffer );
  49913. gl.framebufferRenderbuffer( gl.FRAMEBUFFER, depthStyle, gl.RENDERBUFFER, renderbuffer );
  49914. } else {
  49915. const textureData = this.get( descriptor.depthTexture );
  49916. if ( renderTarget.multiview ) {
  49917. multiviewExt.framebufferTextureMultisampleMultiviewOVR( gl.FRAMEBUFFER, depthStyle, textureData.textureGPU, 0, samples, 0, 2 );
  49918. } else if ( useMultisampledRTT ) {
  49919. multisampledRTTExt.framebufferTexture2DMultisampleEXT( gl.FRAMEBUFFER, depthStyle, gl.TEXTURE_2D, textureData.textureGPU, 0, samples );
  49920. } else {
  49921. gl.framebufferTexture2D( gl.FRAMEBUFFER, depthStyle, gl.TEXTURE_2D, textureData.textureGPU, 0 );
  49922. }
  49923. }
  49924. }
  49925. }
  49926. if ( samples > 0 && useMultisampledRTT === false && ! renderTarget.multiview ) {
  49927. if ( msaaFb === undefined ) {
  49928. const invalidationArray = [];
  49929. msaaFb = gl.createFramebuffer();
  49930. state.bindFramebuffer( gl.FRAMEBUFFER, msaaFb );
  49931. const msaaRenderbuffers = [];
  49932. const textures = descriptor.textures;
  49933. for ( let i = 0; i < textures.length; i ++ ) {
  49934. msaaRenderbuffers[ i ] = gl.createRenderbuffer();
  49935. gl.bindRenderbuffer( gl.RENDERBUFFER, msaaRenderbuffers[ i ] );
  49936. invalidationArray.push( gl.COLOR_ATTACHMENT0 + i );
  49937. const texture = descriptor.textures[ i ];
  49938. const textureData = this.get( texture );
  49939. gl.renderbufferStorageMultisample( gl.RENDERBUFFER, samples, textureData.glInternalFormat, descriptor.width, descriptor.height );
  49940. gl.framebufferRenderbuffer( gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0 + i, gl.RENDERBUFFER, msaaRenderbuffers[ i ] );
  49941. }
  49942. gl.bindRenderbuffer( gl.RENDERBUFFER, null );
  49943. renderTargetContextData.msaaFrameBuffer = msaaFb;
  49944. renderTargetContextData.msaaRenderbuffers = msaaRenderbuffers;
  49945. if ( depthBuffer && depthRenderbuffer === undefined ) {
  49946. depthRenderbuffer = gl.createRenderbuffer();
  49947. this.textureUtils.setupRenderBufferStorage( depthRenderbuffer, descriptor, samples );
  49948. renderTargetContextData.depthRenderbuffer = depthRenderbuffer;
  49949. const depthStyle = stencilBuffer ? gl.DEPTH_STENCIL_ATTACHMENT : gl.DEPTH_ATTACHMENT;
  49950. invalidationArray.push( depthStyle );
  49951. }
  49952. renderTargetContextData.invalidationArray = invalidationArray;
  49953. }
  49954. currentFrameBuffer = renderTargetContextData.msaaFrameBuffer;
  49955. } else {
  49956. currentFrameBuffer = fb;
  49957. }
  49958. state.drawBuffers( descriptor, fb );
  49959. }
  49960. state.bindFramebuffer( gl.FRAMEBUFFER, currentFrameBuffer );
  49961. }
  49962. /**
  49963. * Computes the VAO key for the given index and attributes.
  49964. *
  49965. * @private
  49966. * @param {Array<BufferAttribute>} attributes - An array of buffer attributes.
  49967. * @return {string} The VAO key.
  49968. */
  49969. _getVaoKey( attributes ) {
  49970. let key = '';
  49971. for ( let i = 0; i < attributes.length; i ++ ) {
  49972. const attributeData = this.get( attributes[ i ] );
  49973. key += ':' + attributeData.id;
  49974. }
  49975. return key;
  49976. }
  49977. /**
  49978. * Creates a VAO from the index and attributes.
  49979. *
  49980. * @private
  49981. * @param {Array<BufferAttribute>} attributes - An array of buffer attributes.
  49982. * @return {Object} The VAO data.
  49983. */
  49984. _createVao( attributes ) {
  49985. const { gl } = this;
  49986. const vaoGPU = gl.createVertexArray();
  49987. gl.bindVertexArray( vaoGPU );
  49988. for ( let i = 0; i < attributes.length; i ++ ) {
  49989. const attribute = attributes[ i ];
  49990. const attributeData = this.get( attribute );
  49991. gl.bindBuffer( gl.ARRAY_BUFFER, attributeData.bufferGPU );
  49992. gl.enableVertexAttribArray( i );
  49993. let stride, offset;
  49994. if ( attribute.isInterleavedBufferAttribute === true ) {
  49995. stride = attribute.data.stride * attributeData.bytesPerElement;
  49996. offset = attribute.offset * attributeData.bytesPerElement;
  49997. } else {
  49998. stride = 0;
  49999. offset = 0;
  50000. }
  50001. if ( attributeData.isInteger ) {
  50002. gl.vertexAttribIPointer( i, attribute.itemSize, attributeData.type, stride, offset );
  50003. } else {
  50004. gl.vertexAttribPointer( i, attribute.itemSize, attributeData.type, attribute.normalized, stride, offset );
  50005. }
  50006. if ( attribute.isInstancedBufferAttribute && ! attribute.isInterleavedBufferAttribute ) {
  50007. gl.vertexAttribDivisor( i, attribute.meshPerAttribute );
  50008. } else if ( attribute.isInterleavedBufferAttribute && attribute.data.isInstancedInterleavedBuffer ) {
  50009. gl.vertexAttribDivisor( i, attribute.data.meshPerAttribute );
  50010. }
  50011. }
  50012. gl.bindBuffer( gl.ARRAY_BUFFER, null );
  50013. return vaoGPU;
  50014. }
  50015. /**
  50016. * Creates a transform feedback from the given transform buffers.
  50017. *
  50018. * @private
  50019. * @param {Array<DualAttributeData>} transformBuffers - The transform buffers.
  50020. * @return {WebGLTransformFeedback} The transform feedback.
  50021. */
  50022. _getTransformFeedback( transformBuffers ) {
  50023. let key = '';
  50024. for ( let i = 0; i < transformBuffers.length; i ++ ) {
  50025. key += ':' + transformBuffers[ i ].id;
  50026. }
  50027. let transformFeedbackGPU = this.transformFeedbackCache[ key ];
  50028. if ( transformFeedbackGPU !== undefined ) {
  50029. return transformFeedbackGPU;
  50030. }
  50031. const { gl } = this;
  50032. transformFeedbackGPU = gl.createTransformFeedback();
  50033. gl.bindTransformFeedback( gl.TRANSFORM_FEEDBACK, transformFeedbackGPU );
  50034. for ( let i = 0; i < transformBuffers.length; i ++ ) {
  50035. const attributeData = transformBuffers[ i ];
  50036. gl.bindBufferBase( gl.TRANSFORM_FEEDBACK_BUFFER, i, attributeData.transformBuffer );
  50037. }
  50038. gl.bindTransformFeedback( gl.TRANSFORM_FEEDBACK, null );
  50039. this.transformFeedbackCache[ key ] = transformFeedbackGPU;
  50040. return transformFeedbackGPU;
  50041. }
  50042. /**
  50043. * Setups the given bindings.
  50044. *
  50045. * @private
  50046. * @param {Array<BindGroup>} bindings - The bindings.
  50047. * @param {WebGLProgram} programGPU - The WebGL program.
  50048. */
  50049. _setupBindings( bindings, programGPU ) {
  50050. const gl = this.gl;
  50051. for ( const bindGroup of bindings ) {
  50052. for ( const binding of bindGroup.bindings ) {
  50053. const bindingData = this.get( binding );
  50054. const index = bindingData.index;
  50055. if ( binding.isUniformsGroup || binding.isUniformBuffer ) {
  50056. const location = gl.getUniformBlockIndex( programGPU, binding.name );
  50057. gl.uniformBlockBinding( programGPU, location, index );
  50058. } else if ( binding.isSampledTexture ) {
  50059. const location = gl.getUniformLocation( programGPU, binding.name );
  50060. gl.uniform1i( location, index );
  50061. }
  50062. }
  50063. }
  50064. }
  50065. /**
  50066. * Binds the given uniforms.
  50067. *
  50068. * @private
  50069. * @param {Array<BindGroup>} bindings - The bindings.
  50070. */
  50071. _bindUniforms( bindings ) {
  50072. const { gl, state } = this;
  50073. for ( const bindGroup of bindings ) {
  50074. for ( const binding of bindGroup.bindings ) {
  50075. const bindingData = this.get( binding );
  50076. const index = bindingData.index;
  50077. if ( binding.isUniformsGroup || binding.isUniformBuffer ) {
  50078. // TODO USE bindBufferRange to group multiple uniform buffers
  50079. state.bindBufferBase( gl.UNIFORM_BUFFER, index, bindingData.bufferGPU );
  50080. } else if ( binding.isSampledTexture ) {
  50081. state.bindTexture( bindingData.glTextureType, bindingData.textureGPU, gl.TEXTURE0 + index );
  50082. }
  50083. }
  50084. }
  50085. }
  50086. /**
  50087. * The method ensures multisampled render targets are resolved.
  50088. *
  50089. * @private
  50090. * @param {RenderContext} renderContext - The render context.
  50091. */
  50092. _resolveRenderTarget( renderContext ) {
  50093. const { gl, state } = this;
  50094. const renderTarget = renderContext.renderTarget;
  50095. if ( renderContext.textures !== null && renderTarget ) {
  50096. const renderTargetContextData = this.get( renderTarget );
  50097. if ( renderTarget.samples > 0 && this._useMultisampledExtension( renderTarget ) === false ) {
  50098. const fb = renderTargetContextData.framebuffers[ renderContext.getCacheKey() ];
  50099. let mask = gl.COLOR_BUFFER_BIT;
  50100. if ( renderTarget.resolveDepthBuffer ) {
  50101. if ( renderTarget.depthBuffer ) mask |= gl.DEPTH_BUFFER_BIT;
  50102. if ( renderTarget.stencilBuffer && renderTarget.resolveStencilBuffer ) mask |= gl.STENCIL_BUFFER_BIT;
  50103. }
  50104. const msaaFrameBuffer = renderTargetContextData.msaaFrameBuffer;
  50105. const msaaRenderbuffers = renderTargetContextData.msaaRenderbuffers;
  50106. const textures = renderContext.textures;
  50107. const isMRT = textures.length > 1;
  50108. state.bindFramebuffer( gl.READ_FRAMEBUFFER, msaaFrameBuffer );
  50109. state.bindFramebuffer( gl.DRAW_FRAMEBUFFER, fb );
  50110. if ( isMRT ) {
  50111. // blitFramebuffer() can only copy/resolve the first color attachment of a framebuffer. When using MRT,
  50112. // the engine temporarily removes all attachments and then configures each attachment for the resolve.
  50113. for ( let i = 0; i < textures.length; i ++ ) {
  50114. gl.framebufferRenderbuffer( gl.READ_FRAMEBUFFER, gl.COLOR_ATTACHMENT0 + i, gl.RENDERBUFFER, null );
  50115. gl.framebufferTexture2D( gl.DRAW_FRAMEBUFFER, gl.COLOR_ATTACHMENT0 + i, gl.TEXTURE_2D, null, 0 );
  50116. }
  50117. }
  50118. for ( let i = 0; i < textures.length; i ++ ) {
  50119. if ( isMRT ) {
  50120. // configure attachment for resolve
  50121. const { textureGPU } = this.get( textures[ i ] );
  50122. gl.framebufferRenderbuffer( gl.READ_FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.RENDERBUFFER, msaaRenderbuffers[ i ] );
  50123. gl.framebufferTexture2D( gl.DRAW_FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, textureGPU, 0 );
  50124. }
  50125. if ( renderContext.scissor ) {
  50126. const { x, y, width, height } = renderContext.scissorValue;
  50127. const viewY = renderContext.height - height - y;
  50128. gl.blitFramebuffer( x, viewY, x + width, viewY + height, x, viewY, x + width, viewY + height, mask, gl.NEAREST );
  50129. } else {
  50130. gl.blitFramebuffer( 0, 0, renderContext.width, renderContext.height, 0, 0, renderContext.width, renderContext.height, mask, gl.NEAREST );
  50131. }
  50132. }
  50133. if ( isMRT ) {
  50134. // restore attachments
  50135. for ( let i = 0; i < textures.length; i ++ ) {
  50136. const { textureGPU } = this.get( textures[ i ] );
  50137. gl.framebufferRenderbuffer( gl.READ_FRAMEBUFFER, gl.COLOR_ATTACHMENT0 + i, gl.RENDERBUFFER, msaaRenderbuffers[ i ] );
  50138. gl.framebufferTexture2D( gl.DRAW_FRAMEBUFFER, gl.COLOR_ATTACHMENT0 + i, gl.TEXTURE_2D, textureGPU, 0 );
  50139. }
  50140. }
  50141. if ( this._supportsInvalidateFramebuffer === true ) {
  50142. gl.invalidateFramebuffer( gl.READ_FRAMEBUFFER, renderTargetContextData.invalidationArray );
  50143. }
  50144. } else if ( renderTarget.resolveDepthBuffer === false && renderTargetContextData.framebuffers ) {
  50145. const fb = renderTargetContextData.framebuffers[ renderContext.getCacheKey() ];
  50146. state.bindFramebuffer( gl.DRAW_FRAMEBUFFER, fb );
  50147. gl.invalidateFramebuffer( gl.DRAW_FRAMEBUFFER, renderTargetContextData.depthInvalidationArray );
  50148. }
  50149. }
  50150. }
  50151. /**
  50152. * Returns `true` if the `WEBGL_multisampled_render_to_texture` extension
  50153. * should be used when MSAA is enabled.
  50154. *
  50155. * @private
  50156. * @param {RenderTarget} renderTarget - The render target that should be multisampled.
  50157. * @return {boolean} Whether to use the `WEBGL_multisampled_render_to_texture` extension for MSAA or not.
  50158. */
  50159. _useMultisampledExtension( renderTarget ) {
  50160. if ( renderTarget.multiview === true ) {
  50161. return true;
  50162. }
  50163. return renderTarget.samples > 0 && this.extensions.has( 'WEBGL_multisampled_render_to_texture' ) === true && renderTarget._autoAllocateDepthBuffer !== false;
  50164. }
  50165. /**
  50166. * Frees internal resources.
  50167. */
  50168. dispose() {
  50169. if ( this.textureUtils !== null ) this.textureUtils.dispose();
  50170. const extension = this.extensions.get( 'WEBGL_lose_context' );
  50171. if ( extension ) extension.loseContext();
  50172. this.renderer.domElement.removeEventListener( 'webglcontextlost', this._onContextLost );
  50173. }
  50174. }
  50175. const GPUPrimitiveTopology = {
  50176. PointList: 'point-list',
  50177. LineList: 'line-list',
  50178. LineStrip: 'line-strip',
  50179. TriangleList: 'triangle-list',
  50180. TriangleStrip: 'triangle-strip',
  50181. };
  50182. const GPUShaderStage = ( typeof self !== 'undefined' ) ? self.GPUShaderStage : { VERTEX: 1, FRAGMENT: 2, COMPUTE: 4 };
  50183. const GPUCompareFunction = {
  50184. Never: 'never',
  50185. Less: 'less',
  50186. Equal: 'equal',
  50187. LessEqual: 'less-equal',
  50188. Greater: 'greater',
  50189. NotEqual: 'not-equal',
  50190. GreaterEqual: 'greater-equal',
  50191. Always: 'always'
  50192. };
  50193. const GPUStoreOp = {
  50194. Store: 'store'};
  50195. const GPULoadOp = {
  50196. Load: 'load',
  50197. Clear: 'clear'
  50198. };
  50199. const GPUFrontFace = {
  50200. CCW: 'ccw',
  50201. CW: 'cw'
  50202. };
  50203. const GPUCullMode = {
  50204. None: 'none',
  50205. Back: 'back'
  50206. };
  50207. const GPUIndexFormat = {
  50208. Uint16: 'uint16',
  50209. Uint32: 'uint32'
  50210. };
  50211. const GPUTextureFormat = {
  50212. // 8-bit formats
  50213. R8Unorm: 'r8unorm',
  50214. R8Snorm: 'r8snorm',
  50215. R8Uint: 'r8uint',
  50216. R8Sint: 'r8sint',
  50217. // 16-bit formats
  50218. R16Uint: 'r16uint',
  50219. R16Sint: 'r16sint',
  50220. R16Float: 'r16float',
  50221. RG8Unorm: 'rg8unorm',
  50222. RG8Snorm: 'rg8snorm',
  50223. RG8Uint: 'rg8uint',
  50224. RG8Sint: 'rg8sint',
  50225. // 32-bit formats
  50226. R32Uint: 'r32uint',
  50227. R32Sint: 'r32sint',
  50228. R32Float: 'r32float',
  50229. RG16Uint: 'rg16uint',
  50230. RG16Sint: 'rg16sint',
  50231. RG16Float: 'rg16float',
  50232. RGBA8Unorm: 'rgba8unorm',
  50233. RGBA8UnormSRGB: 'rgba8unorm-srgb',
  50234. RGBA8Snorm: 'rgba8snorm',
  50235. RGBA8Uint: 'rgba8uint',
  50236. RGBA8Sint: 'rgba8sint',
  50237. BGRA8Unorm: 'bgra8unorm',
  50238. BGRA8UnormSRGB: 'bgra8unorm-srgb',
  50239. // Packed 32-bit formats
  50240. RGB9E5UFloat: 'rgb9e5ufloat',
  50241. RGB10A2Unorm: 'rgb10a2unorm',
  50242. RG11B10UFloat: 'rg11b10ufloat',
  50243. // 64-bit formats
  50244. RG32Uint: 'rg32uint',
  50245. RG32Sint: 'rg32sint',
  50246. RG32Float: 'rg32float',
  50247. RGBA16Uint: 'rgba16uint',
  50248. RGBA16Sint: 'rgba16sint',
  50249. RGBA16Float: 'rgba16float',
  50250. // 128-bit formats
  50251. RGBA32Uint: 'rgba32uint',
  50252. RGBA32Sint: 'rgba32sint',
  50253. RGBA32Float: 'rgba32float',
  50254. Depth16Unorm: 'depth16unorm',
  50255. Depth24Plus: 'depth24plus',
  50256. Depth24PlusStencil8: 'depth24plus-stencil8',
  50257. Depth32Float: 'depth32float',
  50258. // 'depth32float-stencil8' extension
  50259. Depth32FloatStencil8: 'depth32float-stencil8',
  50260. // BC compressed formats usable if 'texture-compression-bc' is both
  50261. // supported by the device/user agent and enabled in requestDevice.
  50262. BC1RGBAUnorm: 'bc1-rgba-unorm',
  50263. BC1RGBAUnormSRGB: 'bc1-rgba-unorm-srgb',
  50264. BC2RGBAUnorm: 'bc2-rgba-unorm',
  50265. BC2RGBAUnormSRGB: 'bc2-rgba-unorm-srgb',
  50266. BC3RGBAUnorm: 'bc3-rgba-unorm',
  50267. BC3RGBAUnormSRGB: 'bc3-rgba-unorm-srgb',
  50268. BC4RUnorm: 'bc4-r-unorm',
  50269. BC4RSnorm: 'bc4-r-snorm',
  50270. BC5RGUnorm: 'bc5-rg-unorm',
  50271. BC5RGSnorm: 'bc5-rg-snorm',
  50272. BC6HRGBUFloat: 'bc6h-rgb-ufloat',
  50273. BC6HRGBFloat: 'bc6h-rgb-float',
  50274. BC7RGBAUnorm: 'bc7-rgba-unorm',
  50275. BC7RGBAUnormSRGB: 'bc7-rgba-unorm-srgb',
  50276. // ETC2 compressed formats usable if 'texture-compression-etc2' is both
  50277. // supported by the device/user agent and enabled in requestDevice.
  50278. ETC2RGB8Unorm: 'etc2-rgb8unorm',
  50279. ETC2RGB8UnormSRGB: 'etc2-rgb8unorm-srgb',
  50280. ETC2RGB8A1Unorm: 'etc2-rgb8a1unorm',
  50281. ETC2RGB8A1UnormSRGB: 'etc2-rgb8a1unorm-srgb',
  50282. ETC2RGBA8Unorm: 'etc2-rgba8unorm',
  50283. ETC2RGBA8UnormSRGB: 'etc2-rgba8unorm-srgb',
  50284. EACR11Unorm: 'eac-r11unorm',
  50285. EACR11Snorm: 'eac-r11snorm',
  50286. EACRG11Unorm: 'eac-rg11unorm',
  50287. EACRG11Snorm: 'eac-rg11snorm',
  50288. // ASTC compressed formats usable if 'texture-compression-astc' is both
  50289. // supported by the device/user agent and enabled in requestDevice.
  50290. ASTC4x4Unorm: 'astc-4x4-unorm',
  50291. ASTC4x4UnormSRGB: 'astc-4x4-unorm-srgb',
  50292. ASTC5x4Unorm: 'astc-5x4-unorm',
  50293. ASTC5x4UnormSRGB: 'astc-5x4-unorm-srgb',
  50294. ASTC5x5Unorm: 'astc-5x5-unorm',
  50295. ASTC5x5UnormSRGB: 'astc-5x5-unorm-srgb',
  50296. ASTC6x5Unorm: 'astc-6x5-unorm',
  50297. ASTC6x5UnormSRGB: 'astc-6x5-unorm-srgb',
  50298. ASTC6x6Unorm: 'astc-6x6-unorm',
  50299. ASTC6x6UnormSRGB: 'astc-6x6-unorm-srgb',
  50300. ASTC8x5Unorm: 'astc-8x5-unorm',
  50301. ASTC8x5UnormSRGB: 'astc-8x5-unorm-srgb',
  50302. ASTC8x6Unorm: 'astc-8x6-unorm',
  50303. ASTC8x6UnormSRGB: 'astc-8x6-unorm-srgb',
  50304. ASTC8x8Unorm: 'astc-8x8-unorm',
  50305. ASTC8x8UnormSRGB: 'astc-8x8-unorm-srgb',
  50306. ASTC10x5Unorm: 'astc-10x5-unorm',
  50307. ASTC10x5UnormSRGB: 'astc-10x5-unorm-srgb',
  50308. ASTC10x6Unorm: 'astc-10x6-unorm',
  50309. ASTC10x6UnormSRGB: 'astc-10x6-unorm-srgb',
  50310. ASTC10x8Unorm: 'astc-10x8-unorm',
  50311. ASTC10x8UnormSRGB: 'astc-10x8-unorm-srgb',
  50312. ASTC10x10Unorm: 'astc-10x10-unorm',
  50313. ASTC10x10UnormSRGB: 'astc-10x10-unorm-srgb',
  50314. ASTC12x10Unorm: 'astc-12x10-unorm',
  50315. ASTC12x10UnormSRGB: 'astc-12x10-unorm-srgb',
  50316. ASTC12x12Unorm: 'astc-12x12-unorm',
  50317. ASTC12x12UnormSRGB: 'astc-12x12-unorm-srgb',
  50318. };
  50319. const GPUAddressMode = {
  50320. ClampToEdge: 'clamp-to-edge',
  50321. Repeat: 'repeat',
  50322. MirrorRepeat: 'mirror-repeat'
  50323. };
  50324. const GPUFilterMode = {
  50325. Linear: 'linear',
  50326. Nearest: 'nearest'
  50327. };
  50328. const GPUBlendFactor = {
  50329. Zero: 'zero',
  50330. One: 'one',
  50331. Src: 'src',
  50332. OneMinusSrc: 'one-minus-src',
  50333. SrcAlpha: 'src-alpha',
  50334. OneMinusSrcAlpha: 'one-minus-src-alpha',
  50335. Dst: 'dst',
  50336. OneMinusDst: 'one-minus-dst',
  50337. DstAlpha: 'dst-alpha',
  50338. OneMinusDstAlpha: 'one-minus-dst-alpha',
  50339. SrcAlphaSaturated: 'src-alpha-saturated',
  50340. Constant: 'constant',
  50341. OneMinusConstant: 'one-minus-constant'
  50342. };
  50343. const GPUBlendOperation = {
  50344. Add: 'add',
  50345. Subtract: 'subtract',
  50346. ReverseSubtract: 'reverse-subtract',
  50347. Min: 'min',
  50348. Max: 'max'
  50349. };
  50350. const GPUColorWriteFlags = {
  50351. None: 0,
  50352. All: 0xF
  50353. };
  50354. const GPUStencilOperation = {
  50355. Keep: 'keep',
  50356. Zero: 'zero',
  50357. Replace: 'replace',
  50358. Invert: 'invert',
  50359. IncrementClamp: 'increment-clamp',
  50360. DecrementClamp: 'decrement-clamp',
  50361. IncrementWrap: 'increment-wrap',
  50362. DecrementWrap: 'decrement-wrap'
  50363. };
  50364. const GPUBufferBindingType = {
  50365. Storage: 'storage',
  50366. ReadOnlyStorage: 'read-only-storage'
  50367. };
  50368. const GPUStorageTextureAccess = {
  50369. WriteOnly: 'write-only',
  50370. ReadOnly: 'read-only',
  50371. ReadWrite: 'read-write',
  50372. };
  50373. const GPUSamplerBindingType = {
  50374. NonFiltering: 'non-filtering',
  50375. Comparison: 'comparison'
  50376. };
  50377. const GPUTextureSampleType = {
  50378. Float: 'float',
  50379. UnfilterableFloat: 'unfilterable-float',
  50380. Depth: 'depth',
  50381. SInt: 'sint',
  50382. UInt: 'uint'
  50383. };
  50384. const GPUTextureDimension = {
  50385. TwoD: '2d',
  50386. ThreeD: '3d'
  50387. };
  50388. const GPUTextureViewDimension = {
  50389. TwoD: '2d',
  50390. TwoDArray: '2d-array',
  50391. Cube: 'cube',
  50392. ThreeD: '3d'
  50393. };
  50394. const GPUTextureAspect = {
  50395. All: 'all'};
  50396. const GPUInputStepMode = {
  50397. Vertex: 'vertex',
  50398. Instance: 'instance'
  50399. };
  50400. const GPUFeatureName = {
  50401. CoreFeaturesAndLimits: 'core-features-and-limits',
  50402. DepthClipControl: 'depth-clip-control',
  50403. Depth32FloatStencil8: 'depth32float-stencil8',
  50404. TextureCompressionBC: 'texture-compression-bc',
  50405. TextureCompressionBCSliced3D: 'texture-compression-bc-sliced-3d',
  50406. TextureCompressionETC2: 'texture-compression-etc2',
  50407. TextureCompressionASTC: 'texture-compression-astc',
  50408. TextureCompressionASTCSliced3D: 'texture-compression-astc-sliced-3d',
  50409. TimestampQuery: 'timestamp-query',
  50410. IndirectFirstInstance: 'indirect-first-instance',
  50411. ShaderF16: 'shader-f16',
  50412. RG11B10UFloat: 'rg11b10ufloat-renderable',
  50413. BGRA8UNormStorage: 'bgra8unorm-storage',
  50414. Float32Filterable: 'float32-filterable',
  50415. Float32Blendable: 'float32-blendable',
  50416. ClipDistances: 'clip-distances',
  50417. DualSourceBlending: 'dual-source-blending',
  50418. Subgroups: 'subgroups',
  50419. TextureFormatsTier1: 'texture-formats-tier1',
  50420. TextureFormatsTier2: 'texture-formats-tier2'
  50421. };
  50422. const GPUFeatureMap = {
  50423. 'texture-compression-s3tc': 'texture-compression-bc',
  50424. 'texture-compression-etc1': 'texture-compression-etc2'
  50425. };
  50426. /**
  50427. * A special form of sampler binding type.
  50428. * It's texture value is managed by a node object.
  50429. *
  50430. * @private
  50431. * @augments Sampler
  50432. */
  50433. class NodeSampler extends Sampler {
  50434. /**
  50435. * Constructs a new node-based sampler.
  50436. *
  50437. * @param {string} name - The samplers's name.
  50438. * @param {TextureNode} textureNode - The texture node.
  50439. * @param {UniformGroupNode} groupNode - The uniform group node.
  50440. */
  50441. constructor( name, textureNode, groupNode ) {
  50442. super( name, textureNode ? textureNode.value : null );
  50443. /**
  50444. * The texture node.
  50445. *
  50446. * @type {TextureNode}
  50447. */
  50448. this.textureNode = textureNode;
  50449. /**
  50450. * The uniform group node.
  50451. *
  50452. * @type {UniformGroupNode}
  50453. */
  50454. this.groupNode = groupNode;
  50455. }
  50456. /**
  50457. * Updates the texture value of this sampler.
  50458. *
  50459. * @return {boolean} Whether the sampler needs an update or not.
  50460. */
  50461. update() {
  50462. const { textureNode } = this;
  50463. if ( this.texture !== textureNode.value ) {
  50464. this.texture = textureNode.value;
  50465. return true;
  50466. }
  50467. return super.update();
  50468. }
  50469. }
  50470. /**
  50471. * Represents a storage buffer binding type.
  50472. *
  50473. * @private
  50474. * @augments Buffer
  50475. */
  50476. class StorageBuffer extends Buffer {
  50477. /**
  50478. * Constructs a new uniform buffer.
  50479. *
  50480. * @param {string} name - The buffer's name.
  50481. * @param {BufferAttribute} attribute - The buffer attribute.
  50482. */
  50483. constructor( name, attribute ) {
  50484. super( name, attribute ? attribute.array : null );
  50485. /**
  50486. * This flag can be used for type testing.
  50487. *
  50488. * @type {BufferAttribute}
  50489. */
  50490. this.attribute = attribute;
  50491. /**
  50492. * This flag can be used for type testing.
  50493. *
  50494. * @type {boolean}
  50495. * @readonly
  50496. * @default true
  50497. */
  50498. this.isStorageBuffer = true;
  50499. }
  50500. }
  50501. let _id = 0;
  50502. /**
  50503. * A special form of storage buffer binding type.
  50504. * It's buffer value is managed by a node object.
  50505. *
  50506. * @private
  50507. * @augments StorageBuffer
  50508. */
  50509. class NodeStorageBuffer extends StorageBuffer {
  50510. /**
  50511. * Constructs a new node-based storage buffer.
  50512. *
  50513. * @param {StorageBufferNode} nodeUniform - The storage buffer node.
  50514. * @param {UniformGroupNode} groupNode - The uniform group node.
  50515. */
  50516. constructor( nodeUniform, groupNode ) {
  50517. super( 'StorageBuffer_' + _id ++, nodeUniform ? nodeUniform.value : null );
  50518. /**
  50519. * The node uniform.
  50520. *
  50521. * @type {StorageBufferNode}
  50522. */
  50523. this.nodeUniform = nodeUniform;
  50524. /**
  50525. * The access type.
  50526. *
  50527. * @type {string}
  50528. */
  50529. this.access = nodeUniform ? nodeUniform.access : NodeAccess.READ_WRITE;
  50530. /**
  50531. * The uniform group node.
  50532. *
  50533. * @type {UniformGroupNode}
  50534. */
  50535. this.groupNode = groupNode;
  50536. }
  50537. /**
  50538. * The storage buffer.
  50539. *
  50540. * @type {BufferAttribute}
  50541. */
  50542. get buffer() {
  50543. return this.nodeUniform.value;
  50544. }
  50545. }
  50546. /**
  50547. * A WebGPU backend utility module used by {@link WebGPUTextureUtils}.
  50548. *
  50549. * @private
  50550. */
  50551. class WebGPUTexturePassUtils extends DataMap {
  50552. /**
  50553. * Constructs a new utility object.
  50554. *
  50555. * @param {GPUDevice} device - The WebGPU device.
  50556. */
  50557. constructor( device ) {
  50558. super();
  50559. /**
  50560. * The WebGPU device.
  50561. *
  50562. * @type {GPUDevice}
  50563. */
  50564. this.device = device;
  50565. const mipmapVertexSource = `
  50566. struct VarysStruct {
  50567. @builtin( position ) Position: vec4<f32>,
  50568. @location( 0 ) vTex : vec2<f32>
  50569. };
  50570. @vertex
  50571. fn main( @builtin( vertex_index ) vertexIndex : u32 ) -> VarysStruct {
  50572. var Varys : VarysStruct;
  50573. var pos = array< vec2<f32>, 4 >(
  50574. vec2<f32>( -1.0, 1.0 ),
  50575. vec2<f32>( 1.0, 1.0 ),
  50576. vec2<f32>( -1.0, -1.0 ),
  50577. vec2<f32>( 1.0, -1.0 )
  50578. );
  50579. var tex = array< vec2<f32>, 4 >(
  50580. vec2<f32>( 0.0, 0.0 ),
  50581. vec2<f32>( 1.0, 0.0 ),
  50582. vec2<f32>( 0.0, 1.0 ),
  50583. vec2<f32>( 1.0, 1.0 )
  50584. );
  50585. Varys.vTex = tex[ vertexIndex ];
  50586. Varys.Position = vec4<f32>( pos[ vertexIndex ], 0.0, 1.0 );
  50587. return Varys;
  50588. }
  50589. `;
  50590. const mipmapFragmentSource = `
  50591. @group( 0 ) @binding( 0 )
  50592. var imgSampler : sampler;
  50593. @group( 0 ) @binding( 1 )
  50594. var img : texture_2d<f32>;
  50595. @fragment
  50596. fn main( @location( 0 ) vTex : vec2<f32> ) -> @location( 0 ) vec4<f32> {
  50597. return textureSample( img, imgSampler, vTex );
  50598. }
  50599. `;
  50600. const flipYFragmentSource = `
  50601. @group( 0 ) @binding( 0 )
  50602. var imgSampler : sampler;
  50603. @group( 0 ) @binding( 1 )
  50604. var img : texture_2d<f32>;
  50605. @fragment
  50606. fn main( @location( 0 ) vTex : vec2<f32> ) -> @location( 0 ) vec4<f32> {
  50607. return textureSample( img, imgSampler, vec2( vTex.x, 1.0 - vTex.y ) );
  50608. }
  50609. `;
  50610. /**
  50611. * The mipmap GPU sampler.
  50612. *
  50613. * @type {GPUSampler}
  50614. */
  50615. this.mipmapSampler = device.createSampler( { minFilter: GPUFilterMode.Linear } );
  50616. /**
  50617. * The flipY GPU sampler.
  50618. *
  50619. * @type {GPUSampler}
  50620. */
  50621. this.flipYSampler = device.createSampler( { minFilter: GPUFilterMode.Nearest } ); //@TODO?: Consider using textureLoad()
  50622. /**
  50623. * A cache for GPU render pipelines used for copy/transfer passes.
  50624. * Every texture format requires a unique pipeline.
  50625. *
  50626. * @type {Object<string,GPURenderPipeline>}
  50627. */
  50628. this.transferPipelines = {};
  50629. /**
  50630. * A cache for GPU render pipelines used for flipY passes.
  50631. * Every texture format requires a unique pipeline.
  50632. *
  50633. * @type {Object<string,GPURenderPipeline>}
  50634. */
  50635. this.flipYPipelines = {};
  50636. /**
  50637. * The mipmap vertex shader module.
  50638. *
  50639. * @type {GPUShaderModule}
  50640. */
  50641. this.mipmapVertexShaderModule = device.createShaderModule( {
  50642. label: 'mipmapVertex',
  50643. code: mipmapVertexSource
  50644. } );
  50645. /**
  50646. * The mipmap fragment shader module.
  50647. *
  50648. * @type {GPUShaderModule}
  50649. */
  50650. this.mipmapFragmentShaderModule = device.createShaderModule( {
  50651. label: 'mipmapFragment',
  50652. code: mipmapFragmentSource
  50653. } );
  50654. /**
  50655. * The flipY fragment shader module.
  50656. *
  50657. * @type {GPUShaderModule}
  50658. */
  50659. this.flipYFragmentShaderModule = device.createShaderModule( {
  50660. label: 'flipYFragment',
  50661. code: flipYFragmentSource
  50662. } );
  50663. }
  50664. /**
  50665. * Returns a render pipeline for the internal copy render pass. The pass
  50666. * requires a unique render pipeline for each texture format.
  50667. *
  50668. * @param {string} format - The GPU texture format
  50669. * @return {GPURenderPipeline} The GPU render pipeline.
  50670. */
  50671. getTransferPipeline( format ) {
  50672. let pipeline = this.transferPipelines[ format ];
  50673. if ( pipeline === undefined ) {
  50674. pipeline = this.device.createRenderPipeline( {
  50675. label: `mipmap-${ format }`,
  50676. vertex: {
  50677. module: this.mipmapVertexShaderModule,
  50678. entryPoint: 'main'
  50679. },
  50680. fragment: {
  50681. module: this.mipmapFragmentShaderModule,
  50682. entryPoint: 'main',
  50683. targets: [ { format } ]
  50684. },
  50685. primitive: {
  50686. topology: GPUPrimitiveTopology.TriangleStrip,
  50687. stripIndexFormat: GPUIndexFormat.Uint32
  50688. },
  50689. layout: 'auto'
  50690. } );
  50691. this.transferPipelines[ format ] = pipeline;
  50692. }
  50693. return pipeline;
  50694. }
  50695. /**
  50696. * Returns a render pipeline for the flipY render pass. The pass
  50697. * requires a unique render pipeline for each texture format.
  50698. *
  50699. * @param {string} format - The GPU texture format
  50700. * @return {GPURenderPipeline} The GPU render pipeline.
  50701. */
  50702. getFlipYPipeline( format ) {
  50703. let pipeline = this.flipYPipelines[ format ];
  50704. if ( pipeline === undefined ) {
  50705. pipeline = this.device.createRenderPipeline( {
  50706. label: `flipY-${ format }`,
  50707. vertex: {
  50708. module: this.mipmapVertexShaderModule,
  50709. entryPoint: 'main'
  50710. },
  50711. fragment: {
  50712. module: this.flipYFragmentShaderModule,
  50713. entryPoint: 'main',
  50714. targets: [ { format } ]
  50715. },
  50716. primitive: {
  50717. topology: GPUPrimitiveTopology.TriangleStrip,
  50718. stripIndexFormat: GPUIndexFormat.Uint32
  50719. },
  50720. layout: 'auto'
  50721. } );
  50722. this.flipYPipelines[ format ] = pipeline;
  50723. }
  50724. return pipeline;
  50725. }
  50726. /**
  50727. * Flip the contents of the given GPU texture along its vertical axis.
  50728. *
  50729. * @param {GPUTexture} textureGPU - The GPU texture object.
  50730. * @param {Object} textureGPUDescriptor - The texture descriptor.
  50731. * @param {number} [baseArrayLayer=0] - The index of the first array layer accessible to the texture view.
  50732. */
  50733. flipY( textureGPU, textureGPUDescriptor, baseArrayLayer = 0 ) {
  50734. const format = textureGPUDescriptor.format;
  50735. const { width, height } = textureGPUDescriptor.size;
  50736. const transferPipeline = this.getTransferPipeline( format );
  50737. const flipYPipeline = this.getFlipYPipeline( format );
  50738. const tempTexture = this.device.createTexture( {
  50739. size: { width, height, depthOrArrayLayers: 1 },
  50740. format,
  50741. usage: GPUTextureUsage.RENDER_ATTACHMENT | GPUTextureUsage.TEXTURE_BINDING
  50742. } );
  50743. const srcView = textureGPU.createView( {
  50744. baseMipLevel: 0,
  50745. mipLevelCount: 1,
  50746. dimension: GPUTextureViewDimension.TwoD,
  50747. baseArrayLayer
  50748. } );
  50749. const dstView = tempTexture.createView( {
  50750. baseMipLevel: 0,
  50751. mipLevelCount: 1,
  50752. dimension: GPUTextureViewDimension.TwoD,
  50753. baseArrayLayer: 0
  50754. } );
  50755. const commandEncoder = this.device.createCommandEncoder( {} );
  50756. const pass = ( pipeline, sourceView, destinationView ) => {
  50757. const bindGroupLayout = pipeline.getBindGroupLayout( 0 ); // @TODO: Consider making this static.
  50758. const bindGroup = this.device.createBindGroup( {
  50759. layout: bindGroupLayout,
  50760. entries: [ {
  50761. binding: 0,
  50762. resource: this.flipYSampler
  50763. }, {
  50764. binding: 1,
  50765. resource: sourceView
  50766. } ]
  50767. } );
  50768. const passEncoder = commandEncoder.beginRenderPass( {
  50769. colorAttachments: [ {
  50770. view: destinationView,
  50771. loadOp: GPULoadOp.Clear,
  50772. storeOp: GPUStoreOp.Store,
  50773. clearValue: [ 0, 0, 0, 0 ]
  50774. } ]
  50775. } );
  50776. passEncoder.setPipeline( pipeline );
  50777. passEncoder.setBindGroup( 0, bindGroup );
  50778. passEncoder.draw( 4, 1, 0, 0 );
  50779. passEncoder.end();
  50780. };
  50781. pass( transferPipeline, srcView, dstView );
  50782. pass( flipYPipeline, dstView, srcView );
  50783. this.device.queue.submit( [ commandEncoder.finish() ] );
  50784. tempTexture.destroy();
  50785. }
  50786. /**
  50787. * Generates mipmaps for the given GPU texture.
  50788. *
  50789. * @param {GPUTexture} textureGPU - The GPU texture object.
  50790. * @param {Object} textureGPUDescriptor - The texture descriptor.
  50791. * @param {number} [baseArrayLayer=0] - The index of the first array layer accessible to the texture view.
  50792. * @param {?GPUCommandEncoder} [encoder=null] - An optional command encoder used to generate mipmaps.
  50793. */
  50794. generateMipmaps( textureGPU, textureGPUDescriptor, baseArrayLayer = 0, encoder = null ) {
  50795. const textureData = this.get( textureGPU );
  50796. if ( textureData.layers === undefined ) {
  50797. textureData.layers = [];
  50798. }
  50799. const passes = textureData.layers[ baseArrayLayer ] || this._mipmapCreateBundles( textureGPU, textureGPUDescriptor, baseArrayLayer );
  50800. const commandEncoder = encoder || this.device.createCommandEncoder( { label: 'mipmapEncoder' } );
  50801. this._mipmapRunBundles( commandEncoder, passes );
  50802. if ( encoder === null ) this.device.queue.submit( [ commandEncoder.finish() ] );
  50803. textureData.layers[ baseArrayLayer ] = passes;
  50804. }
  50805. /**
  50806. * Since multiple copy render passes are required to generate mipmaps, the passes
  50807. * are managed as render bundles to improve performance.
  50808. *
  50809. * @param {GPUTexture} textureGPU - The GPU texture object.
  50810. * @param {Object} textureGPUDescriptor - The texture descriptor.
  50811. * @param {number} baseArrayLayer - The index of the first array layer accessible to the texture view.
  50812. * @return {Array<Object>} An array of render bundles.
  50813. */
  50814. _mipmapCreateBundles( textureGPU, textureGPUDescriptor, baseArrayLayer ) {
  50815. const pipeline = this.getTransferPipeline( textureGPUDescriptor.format );
  50816. const bindGroupLayout = pipeline.getBindGroupLayout( 0 ); // @TODO: Consider making this static.
  50817. let srcView = textureGPU.createView( {
  50818. baseMipLevel: 0,
  50819. mipLevelCount: 1,
  50820. dimension: GPUTextureViewDimension.TwoD,
  50821. baseArrayLayer
  50822. } );
  50823. const passes = [];
  50824. for ( let i = 1; i < textureGPUDescriptor.mipLevelCount; i ++ ) {
  50825. const bindGroup = this.device.createBindGroup( {
  50826. layout: bindGroupLayout,
  50827. entries: [ {
  50828. binding: 0,
  50829. resource: this.mipmapSampler
  50830. }, {
  50831. binding: 1,
  50832. resource: srcView
  50833. } ]
  50834. } );
  50835. const dstView = textureGPU.createView( {
  50836. baseMipLevel: i,
  50837. mipLevelCount: 1,
  50838. dimension: GPUTextureViewDimension.TwoD,
  50839. baseArrayLayer
  50840. } );
  50841. const passDescriptor = {
  50842. colorAttachments: [ {
  50843. view: dstView,
  50844. loadOp: GPULoadOp.Clear,
  50845. storeOp: GPUStoreOp.Store,
  50846. clearValue: [ 0, 0, 0, 0 ]
  50847. } ]
  50848. };
  50849. const passEncoder = this.device.createRenderBundleEncoder( {
  50850. colorFormats: [ textureGPUDescriptor.format ]
  50851. } );
  50852. passEncoder.setPipeline( pipeline );
  50853. passEncoder.setBindGroup( 0, bindGroup );
  50854. passEncoder.draw( 4, 1, 0, 0 );
  50855. passes.push( {
  50856. renderBundles: [ passEncoder.finish() ],
  50857. passDescriptor
  50858. } );
  50859. srcView = dstView;
  50860. }
  50861. return passes;
  50862. }
  50863. /**
  50864. * Executes the render bundles.
  50865. *
  50866. * @param {GPUCommandEncoder} commandEncoder - The GPU command encoder.
  50867. * @param {Array<Object>} passes - An array of render bundles.
  50868. */
  50869. _mipmapRunBundles( commandEncoder, passes ) {
  50870. const levels = passes.length;
  50871. for ( let i = 0; i < levels; i ++ ) {
  50872. const pass = passes[ i ];
  50873. const passEncoder = commandEncoder.beginRenderPass( pass.passDescriptor );
  50874. passEncoder.executeBundles( pass.renderBundles );
  50875. passEncoder.end();
  50876. }
  50877. }
  50878. }
  50879. const _compareToWebGPU = {
  50880. [ NeverCompare ]: 'never',
  50881. [ LessCompare ]: 'less',
  50882. [ EqualCompare ]: 'equal',
  50883. [ LessEqualCompare ]: 'less-equal',
  50884. [ GreaterCompare ]: 'greater',
  50885. [ GreaterEqualCompare ]: 'greater-equal',
  50886. [ AlwaysCompare ]: 'always',
  50887. [ NotEqualCompare ]: 'not-equal'
  50888. };
  50889. const _flipMap = [ 0, 1, 3, 2, 4, 5 ];
  50890. /**
  50891. * A WebGPU backend utility module for managing textures.
  50892. *
  50893. * @private
  50894. */
  50895. class WebGPUTextureUtils {
  50896. /**
  50897. * Constructs a new utility object.
  50898. *
  50899. * @param {WebGPUBackend} backend - The WebGPU backend.
  50900. */
  50901. constructor( backend ) {
  50902. /**
  50903. * A reference to the WebGPU backend.
  50904. *
  50905. * @type {WebGPUBackend}
  50906. */
  50907. this.backend = backend;
  50908. /**
  50909. * A reference to the pass utils.
  50910. *
  50911. * @type {?WebGPUTexturePassUtils}
  50912. * @default null
  50913. */
  50914. this._passUtils = null;
  50915. /**
  50916. * A dictionary for managing default textures. The key
  50917. * is the texture format, the value the texture object.
  50918. *
  50919. * @type {Object<string,Texture>}
  50920. */
  50921. this.defaultTexture = {};
  50922. /**
  50923. * A dictionary for managing default cube textures. The key
  50924. * is the texture format, the value the texture object.
  50925. *
  50926. * @type {Object<string,CubeTexture>}
  50927. */
  50928. this.defaultCubeTexture = {};
  50929. /**
  50930. * A default video frame.
  50931. *
  50932. * @type {?VideoFrame}
  50933. * @default null
  50934. */
  50935. this.defaultVideoFrame = null;
  50936. /**
  50937. * A cache of shared texture samplers.
  50938. *
  50939. * @type {Map<string, Object>}
  50940. */
  50941. this._samplerCache = new Map();
  50942. }
  50943. /**
  50944. * Creates a GPU sampler for the given texture.
  50945. *
  50946. * @param {Texture} texture - The texture to create the sampler for.
  50947. * @return {string} The current sampler key.
  50948. */
  50949. updateSampler( texture ) {
  50950. const backend = this.backend;
  50951. const samplerKey = texture.minFilter + '-' + texture.magFilter + '-' +
  50952. texture.wrapS + '-' + texture.wrapT + '-' + ( texture.wrapR || '0' ) + '-' +
  50953. texture.anisotropy + '-' + ( texture.compareFunction || 0 );
  50954. let samplerData = this._samplerCache.get( samplerKey );
  50955. if ( samplerData === undefined ) {
  50956. const samplerDescriptorGPU = {
  50957. addressModeU: this._convertAddressMode( texture.wrapS ),
  50958. addressModeV: this._convertAddressMode( texture.wrapT ),
  50959. addressModeW: this._convertAddressMode( texture.wrapR ),
  50960. magFilter: this._convertFilterMode( texture.magFilter ),
  50961. minFilter: this._convertFilterMode( texture.minFilter ),
  50962. mipmapFilter: this._convertFilterMode( texture.minFilter ),
  50963. maxAnisotropy: 1
  50964. };
  50965. // anisotropy can only be used when all filter modes are set to linear.
  50966. if ( samplerDescriptorGPU.magFilter === GPUFilterMode.Linear && samplerDescriptorGPU.minFilter === GPUFilterMode.Linear && samplerDescriptorGPU.mipmapFilter === GPUFilterMode.Linear ) {
  50967. samplerDescriptorGPU.maxAnisotropy = texture.anisotropy;
  50968. }
  50969. if ( texture.isDepthTexture && texture.compareFunction !== null ) {
  50970. samplerDescriptorGPU.compare = _compareToWebGPU[ texture.compareFunction ];
  50971. }
  50972. const sampler = backend.device.createSampler( samplerDescriptorGPU );
  50973. samplerData = { sampler, usedTimes: 0 };
  50974. this._samplerCache.set( samplerKey, samplerData );
  50975. }
  50976. const textureData = backend.get( texture );
  50977. if ( textureData.sampler !== samplerData.sampler ) {
  50978. // check if previous sampler is unused so it can be deleted
  50979. if ( textureData.sampler !== undefined ) {
  50980. const oldSamplerData = this._samplerCache.get( textureData.samplerKey );
  50981. oldSamplerData.usedTimes --;
  50982. if ( oldSamplerData.usedTimes === 0 ) {
  50983. this._samplerCache.delete( textureData.samplerKey );
  50984. }
  50985. }
  50986. // update to new sampler data
  50987. textureData.samplerKey = samplerKey;
  50988. textureData.sampler = samplerData.sampler;
  50989. samplerData.usedTimes ++;
  50990. }
  50991. return samplerKey;
  50992. }
  50993. /**
  50994. * Creates a default texture for the given texture that can be used
  50995. * as a placeholder until the actual texture is ready for usage.
  50996. *
  50997. * @param {Texture} texture - The texture to create a default texture for.
  50998. */
  50999. createDefaultTexture( texture ) {
  51000. let textureGPU;
  51001. const format = getFormat( texture );
  51002. if ( texture.isCubeTexture ) {
  51003. textureGPU = this._getDefaultCubeTextureGPU( format );
  51004. } else {
  51005. textureGPU = this._getDefaultTextureGPU( format );
  51006. }
  51007. this.backend.get( texture ).texture = textureGPU;
  51008. }
  51009. /**
  51010. * Defines a texture on the GPU for the given texture object.
  51011. *
  51012. * @param {Texture} texture - The texture.
  51013. * @param {Object} [options={}] - Optional configuration parameter.
  51014. */
  51015. createTexture( texture, options = {} ) {
  51016. const backend = this.backend;
  51017. const textureData = backend.get( texture );
  51018. if ( textureData.initialized ) {
  51019. throw new Error( 'WebGPUTextureUtils: Texture already initialized.' );
  51020. }
  51021. if ( texture.isExternalTexture ) {
  51022. textureData.texture = texture.sourceTexture;
  51023. textureData.initialized = true;
  51024. return;
  51025. }
  51026. if ( options.needsMipmaps === undefined ) options.needsMipmaps = false;
  51027. if ( options.levels === undefined ) options.levels = 1;
  51028. if ( options.depth === undefined ) options.depth = 1;
  51029. const { width, height, depth, levels } = options;
  51030. if ( texture.isFramebufferTexture ) {
  51031. if ( options.renderTarget ) {
  51032. options.format = this.backend.utils.getCurrentColorFormat( options.renderTarget );
  51033. } else {
  51034. options.format = this.backend.utils.getPreferredCanvasFormat();
  51035. }
  51036. }
  51037. const dimension = this._getDimension( texture );
  51038. const format = texture.internalFormat || options.format || getFormat( texture, backend.device );
  51039. textureData.format = format;
  51040. const { samples, primarySamples, isMSAA } = backend.utils.getTextureSampleData( texture );
  51041. let usage = GPUTextureUsage.TEXTURE_BINDING | GPUTextureUsage.COPY_DST | GPUTextureUsage.COPY_SRC;
  51042. if ( texture.isStorageTexture === true ) {
  51043. usage |= GPUTextureUsage.STORAGE_BINDING;
  51044. }
  51045. if ( texture.isCompressedTexture !== true && texture.isCompressedArrayTexture !== true && format !== GPUTextureFormat.RGB9E5UFloat ) {
  51046. usage |= GPUTextureUsage.RENDER_ATTACHMENT;
  51047. }
  51048. const textureDescriptorGPU = {
  51049. label: texture.name,
  51050. size: {
  51051. width: width,
  51052. height: height,
  51053. depthOrArrayLayers: depth,
  51054. },
  51055. mipLevelCount: levels,
  51056. sampleCount: primarySamples,
  51057. dimension: dimension,
  51058. format: format,
  51059. usage: usage
  51060. };
  51061. // texture creation
  51062. if ( format === undefined ) {
  51063. warn( 'WebGPURenderer: Texture format not supported.' );
  51064. this.createDefaultTexture( texture );
  51065. return;
  51066. }
  51067. if ( texture.isCubeTexture ) {
  51068. textureDescriptorGPU.textureBindingViewDimension = GPUTextureViewDimension.Cube;
  51069. }
  51070. textureData.texture = backend.device.createTexture( textureDescriptorGPU );
  51071. if ( isMSAA ) {
  51072. const msaaTextureDescriptorGPU = Object.assign( {}, textureDescriptorGPU );
  51073. msaaTextureDescriptorGPU.label = msaaTextureDescriptorGPU.label + '-msaa';
  51074. msaaTextureDescriptorGPU.sampleCount = samples;
  51075. msaaTextureDescriptorGPU.mipLevelCount = 1; // See https://www.w3.org/TR/webgpu/#texture-creation
  51076. textureData.msaaTexture = backend.device.createTexture( msaaTextureDescriptorGPU );
  51077. }
  51078. textureData.initialized = true;
  51079. textureData.textureDescriptorGPU = textureDescriptorGPU;
  51080. }
  51081. /**
  51082. * Destroys the GPU data for the given texture object.
  51083. *
  51084. * @param {Texture} texture - The texture.
  51085. * @param {boolean} [isDefaultTexture=false] - Whether the texture uses a default GPU texture or not.
  51086. */
  51087. destroyTexture( texture, isDefaultTexture = false ) {
  51088. const backend = this.backend;
  51089. const textureData = backend.get( texture );
  51090. if ( textureData.texture !== undefined && isDefaultTexture === false ) textureData.texture.destroy();
  51091. if ( textureData.msaaTexture !== undefined ) textureData.msaaTexture.destroy();
  51092. backend.delete( texture );
  51093. }
  51094. /**
  51095. * Generates mipmaps for the given texture.
  51096. *
  51097. * @param {Texture} texture - The texture.
  51098. * @param {?GPUCommandEncoder} [encoder=null] - An optional command encoder used to generate mipmaps.
  51099. */
  51100. generateMipmaps( texture, encoder = null ) {
  51101. const textureData = this.backend.get( texture );
  51102. if ( texture.isCubeTexture ) {
  51103. for ( let i = 0; i < 6; i ++ ) {
  51104. this._generateMipmaps( textureData.texture, textureData.textureDescriptorGPU, i, encoder );
  51105. }
  51106. } else {
  51107. const depth = texture.image.depth || 1;
  51108. for ( let i = 0; i < depth; i ++ ) {
  51109. this._generateMipmaps( textureData.texture, textureData.textureDescriptorGPU, i, encoder );
  51110. }
  51111. }
  51112. }
  51113. /**
  51114. * Returns the color buffer representing the color
  51115. * attachment of the default framebuffer.
  51116. *
  51117. * @return {GPUTexture} The color buffer.
  51118. */
  51119. getColorBuffer() {
  51120. const backend = this.backend;
  51121. const canvasTarget = backend.renderer.getCanvasTarget();
  51122. const { width, height } = backend.getDrawingBufferSize();
  51123. const samples = backend.renderer.currentSamples;
  51124. const colorTexture = canvasTarget.colorTexture;
  51125. const colorTextureData = backend.get( colorTexture );
  51126. if ( colorTexture.width === width && colorTexture.height === height && colorTexture.samples === samples ) {
  51127. return colorTextureData.texture;
  51128. }
  51129. // recreate
  51130. let colorBuffer = colorTextureData.texture;
  51131. if ( colorBuffer ) colorBuffer.destroy();
  51132. colorBuffer = backend.device.createTexture( {
  51133. label: 'colorBuffer',
  51134. size: {
  51135. width: width,
  51136. height: height,
  51137. depthOrArrayLayers: 1
  51138. },
  51139. sampleCount: backend.utils.getSampleCount( backend.renderer.currentSamples ),
  51140. format: backend.utils.getPreferredCanvasFormat(),
  51141. usage: GPUTextureUsage.RENDER_ATTACHMENT | GPUTextureUsage.COPY_SRC
  51142. } );
  51143. //
  51144. colorTexture.source.width = width;
  51145. colorTexture.source.height = height;
  51146. colorTexture.samples = samples;
  51147. colorTextureData.texture = colorBuffer;
  51148. return colorBuffer;
  51149. }
  51150. /**
  51151. * Returns the depth buffer representing the depth
  51152. * attachment of the default framebuffer.
  51153. *
  51154. * @param {boolean} [depth=true] - Whether depth is enabled or not.
  51155. * @param {boolean} [stencil=false] - Whether stencil is enabled or not.
  51156. * @return {GPUTexture} The depth buffer.
  51157. */
  51158. getDepthBuffer( depth = true, stencil = false ) {
  51159. const backend = this.backend;
  51160. const canvasTarget = backend.renderer.getCanvasTarget();
  51161. const { width, height } = backend.getDrawingBufferSize();
  51162. const samples = backend.renderer.currentSamples;
  51163. const depthTexture = canvasTarget.depthTexture;
  51164. if ( depthTexture.width === width &&
  51165. depthTexture.height === height &&
  51166. depthTexture.samples === samples &&
  51167. depthTexture.depth === depth &&
  51168. depthTexture.stencil === stencil ) {
  51169. return backend.get( depthTexture ).texture;
  51170. }
  51171. //
  51172. const depthTextureGPU = backend.get( depthTexture ).texture;
  51173. let format, type;
  51174. if ( stencil ) {
  51175. format = DepthStencilFormat;
  51176. type = UnsignedInt248Type;
  51177. } else if ( depth ) {
  51178. format = DepthFormat;
  51179. type = UnsignedIntType;
  51180. }
  51181. if ( depthTextureGPU !== undefined ) {
  51182. if ( depthTexture.image.width === width && depthTexture.image.height === height && depthTexture.format === format && depthTexture.type === type && depthTexture.samples === samples ) {
  51183. return depthTextureGPU;
  51184. }
  51185. this.destroyTexture( depthTexture );
  51186. }
  51187. // recreate
  51188. depthTexture.name = 'depthBuffer';
  51189. depthTexture.format = format;
  51190. depthTexture.type = type;
  51191. depthTexture.image.width = width;
  51192. depthTexture.image.height = height;
  51193. depthTexture.samples = samples;
  51194. this.createTexture( depthTexture, { width, height } );
  51195. return backend.get( depthTexture ).texture;
  51196. }
  51197. /**
  51198. * Uploads the updated texture data to the GPU.
  51199. *
  51200. * @param {Texture} texture - The texture.
  51201. * @param {Object} [options={}] - Optional configuration parameter.
  51202. */
  51203. updateTexture( texture, options ) {
  51204. const textureData = this.backend.get( texture );
  51205. const mipmaps = texture.mipmaps;
  51206. const { textureDescriptorGPU } = textureData;
  51207. if ( texture.isRenderTargetTexture || ( textureDescriptorGPU === undefined /* unsupported texture format */ ) )
  51208. return;
  51209. // transfer texture data
  51210. if ( texture.isDataTexture ) {
  51211. if ( mipmaps.length > 0 ) {
  51212. for ( let i = 0, il = mipmaps.length; i < il; i ++ ) {
  51213. const mipmap = mipmaps[ i ];
  51214. this._copyBufferToTexture( mipmap, textureData.texture, textureDescriptorGPU, 0, texture.flipY, 0, i );
  51215. }
  51216. } else {
  51217. this._copyBufferToTexture( options.image, textureData.texture, textureDescriptorGPU, 0, texture.flipY );
  51218. }
  51219. } else if ( texture.isArrayTexture || texture.isDataArrayTexture || texture.isData3DTexture ) {
  51220. for ( let i = 0; i < options.image.depth; i ++ ) {
  51221. this._copyBufferToTexture( options.image, textureData.texture, textureDescriptorGPU, i, texture.flipY, i );
  51222. }
  51223. } else if ( texture.isCompressedTexture || texture.isCompressedArrayTexture ) {
  51224. this._copyCompressedBufferToTexture( texture.mipmaps, textureData.texture, textureDescriptorGPU );
  51225. } else if ( texture.isCubeTexture ) {
  51226. this._copyCubeMapToTexture( texture, textureData.texture, textureDescriptorGPU );
  51227. } else {
  51228. if ( mipmaps.length > 0 ) {
  51229. for ( let i = 0, il = mipmaps.length; i < il; i ++ ) {
  51230. const mipmap = mipmaps[ i ];
  51231. this._copyImageToTexture( mipmap, textureData.texture, textureDescriptorGPU, 0, texture.flipY, texture.premultiplyAlpha, i );
  51232. }
  51233. } else {
  51234. this._copyImageToTexture( options.image, textureData.texture, textureDescriptorGPU, 0, texture.flipY, texture.premultiplyAlpha );
  51235. }
  51236. }
  51237. //
  51238. textureData.version = texture.version;
  51239. }
  51240. /**
  51241. * Returns texture data as a typed array.
  51242. *
  51243. * @async
  51244. * @param {Texture} texture - The texture to copy.
  51245. * @param {number} x - The x coordinate of the copy origin.
  51246. * @param {number} y - The y coordinate of the copy origin.
  51247. * @param {number} width - The width of the copy.
  51248. * @param {number} height - The height of the copy.
  51249. * @param {number} faceIndex - The face index.
  51250. * @return {Promise<TypedArray>} A Promise that resolves with a typed array when the copy operation has finished.
  51251. */
  51252. async copyTextureToBuffer( texture, x, y, width, height, faceIndex ) {
  51253. const device = this.backend.device;
  51254. const textureData = this.backend.get( texture );
  51255. const textureGPU = textureData.texture;
  51256. const format = textureData.textureDescriptorGPU.format;
  51257. const bytesPerTexel = this._getBytesPerTexel( format );
  51258. let bytesPerRow = width * bytesPerTexel;
  51259. bytesPerRow = Math.ceil( bytesPerRow / 256 ) * 256; // Align to 256 bytes
  51260. const readBuffer = device.createBuffer(
  51261. {
  51262. size: ( ( height - 1 ) * bytesPerRow ) + ( width * bytesPerTexel ), // see https://github.com/mrdoob/three.js/issues/31658#issuecomment-3229442010
  51263. usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ
  51264. }
  51265. );
  51266. const encoder = device.createCommandEncoder();
  51267. encoder.copyTextureToBuffer(
  51268. {
  51269. texture: textureGPU,
  51270. origin: { x, y, z: faceIndex },
  51271. },
  51272. {
  51273. buffer: readBuffer,
  51274. bytesPerRow: bytesPerRow
  51275. },
  51276. {
  51277. width: width,
  51278. height: height
  51279. }
  51280. );
  51281. const typedArrayType = this._getTypedArrayType( format );
  51282. device.queue.submit( [ encoder.finish() ] );
  51283. await readBuffer.mapAsync( GPUMapMode.READ );
  51284. const buffer = readBuffer.getMappedRange();
  51285. return new typedArrayType( buffer );
  51286. }
  51287. /**
  51288. * Frees all internal resources.
  51289. */
  51290. dispose() {
  51291. this._samplerCache.clear();
  51292. }
  51293. /**
  51294. * Returns the default GPU texture for the given format.
  51295. *
  51296. * @private
  51297. * @param {string} format - The GPU format.
  51298. * @return {GPUTexture} The GPU texture.
  51299. */
  51300. _getDefaultTextureGPU( format ) {
  51301. let defaultTexture = this.defaultTexture[ format ];
  51302. if ( defaultTexture === undefined ) {
  51303. const texture = new Texture();
  51304. texture.minFilter = NearestFilter;
  51305. texture.magFilter = NearestFilter;
  51306. this.createTexture( texture, { width: 1, height: 1, format } );
  51307. this.defaultTexture[ format ] = defaultTexture = texture;
  51308. }
  51309. return this.backend.get( defaultTexture ).texture;
  51310. }
  51311. /**
  51312. * Returns the default GPU cube texture for the given format.
  51313. *
  51314. * @private
  51315. * @param {string} format - The GPU format.
  51316. * @return {GPUTexture} The GPU texture.
  51317. */
  51318. _getDefaultCubeTextureGPU( format ) {
  51319. let defaultCubeTexture = this.defaultCubeTexture[ format ];
  51320. if ( defaultCubeTexture === undefined ) {
  51321. const texture = new CubeTexture();
  51322. texture.minFilter = NearestFilter;
  51323. texture.magFilter = NearestFilter;
  51324. this.createTexture( texture, { width: 1, height: 1, depth: 6 } );
  51325. this.defaultCubeTexture[ format ] = defaultCubeTexture = texture;
  51326. }
  51327. return this.backend.get( defaultCubeTexture ).texture;
  51328. }
  51329. /**
  51330. * Uploads cube texture image data to the GPU memory.
  51331. *
  51332. * @private
  51333. * @param {CubeTexture} texture - The cube texture.
  51334. * @param {GPUTexture} textureGPU - The GPU texture.
  51335. * @param {Object} textureDescriptorGPU - The GPU texture descriptor.
  51336. */
  51337. _copyCubeMapToTexture( texture, textureGPU, textureDescriptorGPU ) {
  51338. const images = texture.images;
  51339. const mipmaps = texture.mipmaps;
  51340. for ( let i = 0; i < 6; i ++ ) {
  51341. const image = images[ i ];
  51342. const flipIndex = texture.flipY === true ? _flipMap[ i ] : i;
  51343. if ( image.isDataTexture ) {
  51344. this._copyBufferToTexture( image.image, textureGPU, textureDescriptorGPU, flipIndex, texture.flipY );
  51345. } else {
  51346. this._copyImageToTexture( image, textureGPU, textureDescriptorGPU, flipIndex, texture.flipY, texture.premultiplyAlpha );
  51347. }
  51348. for ( let j = 0; j < mipmaps.length; j ++ ) {
  51349. const mipmap = mipmaps[ j ];
  51350. const image = mipmap.images[ i ];
  51351. if ( image.isDataTexture ) {
  51352. this._copyBufferToTexture( image.image, textureGPU, textureDescriptorGPU, flipIndex, texture.flipY, 0, j + 1 );
  51353. } else {
  51354. this._copyImageToTexture( image, textureGPU, textureDescriptorGPU, flipIndex, texture.flipY, texture.premultiplyAlpha, j + 1 );
  51355. }
  51356. }
  51357. }
  51358. }
  51359. /**
  51360. * Uploads texture image data to the GPU memory.
  51361. *
  51362. * @private
  51363. * @param {HTMLImageElement|ImageBitmap|HTMLCanvasElement} image - The image data.
  51364. * @param {GPUTexture} textureGPU - The GPU texture.
  51365. * @param {Object} textureDescriptorGPU - The GPU texture descriptor.
  51366. * @param {number} originDepth - The origin depth.
  51367. * @param {boolean} flipY - Whether to flip texture data along their vertical axis or not.
  51368. * @param {boolean} premultiplyAlpha - Whether the texture should have its RGB channels premultiplied by the alpha channel or not.
  51369. * @param {number} [mipLevel=0] - The mip level where the data should be copied to.
  51370. */
  51371. _copyImageToTexture( image, textureGPU, textureDescriptorGPU, originDepth, flipY, premultiplyAlpha, mipLevel = 0 ) {
  51372. const device = this.backend.device;
  51373. const width = ( mipLevel > 0 ) ? image.width : textureDescriptorGPU.size.width;
  51374. const height = ( mipLevel > 0 ) ? image.height : textureDescriptorGPU.size.height;
  51375. try {
  51376. device.queue.copyExternalImageToTexture(
  51377. {
  51378. source: image,
  51379. flipY: flipY
  51380. }, {
  51381. texture: textureGPU,
  51382. mipLevel: mipLevel,
  51383. origin: { x: 0, y: 0, z: originDepth },
  51384. premultipliedAlpha: premultiplyAlpha
  51385. }, {
  51386. width: width,
  51387. height: height,
  51388. depthOrArrayLayers: 1
  51389. }
  51390. );
  51391. } catch ( _ ) {} // try/catch has been added to fix bad video frame data on certain devices, see #32391
  51392. }
  51393. /**
  51394. * Returns the pass utils singleton.
  51395. *
  51396. * @private
  51397. * @return {WebGPUTexturePassUtils} The utils instance.
  51398. */
  51399. _getPassUtils() {
  51400. let passUtils = this._passUtils;
  51401. if ( passUtils === null ) {
  51402. this._passUtils = passUtils = new WebGPUTexturePassUtils( this.backend.device );
  51403. }
  51404. return passUtils;
  51405. }
  51406. /**
  51407. * Generates mipmaps for the given GPU texture.
  51408. *
  51409. * @private
  51410. * @param {GPUTexture} textureGPU - The GPU texture object.
  51411. * @param {Object} textureDescriptorGPU - The texture descriptor.
  51412. * @param {number} [baseArrayLayer=0] - The index of the first array layer accessible to the texture view.
  51413. * @param {?GPUCommandEncoder} [encoder=null] - An optional command encoder used to generate mipmaps.
  51414. */
  51415. _generateMipmaps( textureGPU, textureDescriptorGPU, baseArrayLayer = 0, encoder = null ) {
  51416. this._getPassUtils().generateMipmaps( textureGPU, textureDescriptorGPU, baseArrayLayer, encoder );
  51417. }
  51418. /**
  51419. * Flip the contents of the given GPU texture along its vertical axis.
  51420. *
  51421. * @private
  51422. * @param {GPUTexture} textureGPU - The GPU texture object.
  51423. * @param {Object} textureDescriptorGPU - The texture descriptor.
  51424. * @param {number} [originDepth=0] - The origin depth.
  51425. */
  51426. _flipY( textureGPU, textureDescriptorGPU, originDepth = 0 ) {
  51427. this._getPassUtils().flipY( textureGPU, textureDescriptorGPU, originDepth );
  51428. }
  51429. /**
  51430. * Uploads texture buffer data to the GPU memory.
  51431. *
  51432. * @private
  51433. * @param {Object} image - An object defining the image buffer data.
  51434. * @param {GPUTexture} textureGPU - The GPU texture.
  51435. * @param {Object} textureDescriptorGPU - The GPU texture descriptor.
  51436. * @param {number} originDepth - The origin depth.
  51437. * @param {boolean} flipY - Whether to flip texture data along their vertical axis or not.
  51438. * @param {number} [depth=0] - The depth offset when copying array or 3D texture data.
  51439. * @param {number} [mipLevel=0] - The mip level where the data should be copied to.
  51440. */
  51441. _copyBufferToTexture( image, textureGPU, textureDescriptorGPU, originDepth, flipY, depth = 0, mipLevel = 0 ) {
  51442. // @TODO: Consider to use GPUCommandEncoder.copyBufferToTexture()
  51443. // @TODO: Consider to support valid buffer layouts with other formats like RGB
  51444. const device = this.backend.device;
  51445. const data = image.data;
  51446. const bytesPerTexel = this._getBytesPerTexel( textureDescriptorGPU.format );
  51447. const bytesPerRow = image.width * bytesPerTexel;
  51448. device.queue.writeTexture(
  51449. {
  51450. texture: textureGPU,
  51451. mipLevel: mipLevel,
  51452. origin: { x: 0, y: 0, z: originDepth }
  51453. },
  51454. data,
  51455. {
  51456. offset: image.width * image.height * bytesPerTexel * depth,
  51457. bytesPerRow
  51458. },
  51459. {
  51460. width: image.width,
  51461. height: image.height,
  51462. depthOrArrayLayers: 1
  51463. } );
  51464. if ( flipY === true ) {
  51465. this._flipY( textureGPU, textureDescriptorGPU, originDepth );
  51466. }
  51467. }
  51468. /**
  51469. * Uploads compressed texture data to the GPU memory.
  51470. *
  51471. * @private
  51472. * @param {Array<Object>} mipmaps - An array with mipmap data.
  51473. * @param {GPUTexture} textureGPU - The GPU texture.
  51474. * @param {Object} textureDescriptorGPU - The GPU texture descriptor.
  51475. */
  51476. _copyCompressedBufferToTexture( mipmaps, textureGPU, textureDescriptorGPU ) {
  51477. // @TODO: Consider to use GPUCommandEncoder.copyBufferToTexture()
  51478. const device = this.backend.device;
  51479. const blockData = this._getBlockData( textureDescriptorGPU.format );
  51480. const isArrayTexture = textureDescriptorGPU.size.depthOrArrayLayers > 1;
  51481. for ( let i = 0; i < mipmaps.length; i ++ ) {
  51482. const mipmap = mipmaps[ i ];
  51483. const width = mipmap.width;
  51484. const height = mipmap.height;
  51485. const depth = isArrayTexture ? textureDescriptorGPU.size.depthOrArrayLayers : 1;
  51486. const bytesPerRow = Math.ceil( width / blockData.width ) * blockData.byteLength;
  51487. const bytesPerImage = bytesPerRow * Math.ceil( height / blockData.height );
  51488. for ( let j = 0; j < depth; j ++ ) {
  51489. device.queue.writeTexture(
  51490. {
  51491. texture: textureGPU,
  51492. mipLevel: i,
  51493. origin: { x: 0, y: 0, z: j }
  51494. },
  51495. mipmap.data,
  51496. {
  51497. offset: j * bytesPerImage,
  51498. bytesPerRow,
  51499. rowsPerImage: Math.ceil( height / blockData.height )
  51500. },
  51501. {
  51502. width: Math.ceil( width / blockData.width ) * blockData.width,
  51503. height: Math.ceil( height / blockData.height ) * blockData.height,
  51504. depthOrArrayLayers: 1
  51505. }
  51506. );
  51507. }
  51508. }
  51509. }
  51510. /**
  51511. * This method is only relevant for compressed texture formats. It returns a block
  51512. * data descriptor for the given GPU compressed texture format.
  51513. *
  51514. * @private
  51515. * @param {string} format - The GPU compressed texture format.
  51516. * @return {Object} The block data descriptor.
  51517. */
  51518. _getBlockData( format ) {
  51519. if ( format === GPUTextureFormat.BC1RGBAUnorm || format === GPUTextureFormat.BC1RGBAUnormSRGB ) return { byteLength: 8, width: 4, height: 4 }; // DXT1
  51520. if ( format === GPUTextureFormat.BC2RGBAUnorm || format === GPUTextureFormat.BC2RGBAUnormSRGB ) return { byteLength: 16, width: 4, height: 4 }; // DXT3
  51521. if ( format === GPUTextureFormat.BC3RGBAUnorm || format === GPUTextureFormat.BC3RGBAUnormSRGB ) return { byteLength: 16, width: 4, height: 4 }; // DXT5
  51522. if ( format === GPUTextureFormat.BC4RUnorm || format === GPUTextureFormat.BC4RSnorm ) return { byteLength: 8, width: 4, height: 4 }; // RGTC1
  51523. if ( format === GPUTextureFormat.BC5RGUnorm || format === GPUTextureFormat.BC5RGSnorm ) return { byteLength: 16, width: 4, height: 4 }; // RGTC2
  51524. if ( format === GPUTextureFormat.BC6HRGBUFloat || format === GPUTextureFormat.BC6HRGBFloat ) return { byteLength: 16, width: 4, height: 4 }; // BPTC (float)
  51525. if ( format === GPUTextureFormat.BC7RGBAUnorm || format === GPUTextureFormat.BC7RGBAUnormSRGB ) return { byteLength: 16, width: 4, height: 4 }; // BPTC (unorm)
  51526. if ( format === GPUTextureFormat.ETC2RGB8Unorm || format === GPUTextureFormat.ETC2RGB8UnormSRGB ) return { byteLength: 8, width: 4, height: 4 };
  51527. if ( format === GPUTextureFormat.ETC2RGB8A1Unorm || format === GPUTextureFormat.ETC2RGB8A1UnormSRGB ) return { byteLength: 8, width: 4, height: 4 };
  51528. if ( format === GPUTextureFormat.ETC2RGBA8Unorm || format === GPUTextureFormat.ETC2RGBA8UnormSRGB ) return { byteLength: 16, width: 4, height: 4 };
  51529. if ( format === GPUTextureFormat.EACR11Unorm ) return { byteLength: 8, width: 4, height: 4 };
  51530. if ( format === GPUTextureFormat.EACR11Snorm ) return { byteLength: 8, width: 4, height: 4 };
  51531. if ( format === GPUTextureFormat.EACRG11Unorm ) return { byteLength: 16, width: 4, height: 4 };
  51532. if ( format === GPUTextureFormat.EACRG11Snorm ) return { byteLength: 16, width: 4, height: 4 };
  51533. if ( format === GPUTextureFormat.ASTC4x4Unorm || format === GPUTextureFormat.ASTC4x4UnormSRGB ) return { byteLength: 16, width: 4, height: 4 };
  51534. if ( format === GPUTextureFormat.ASTC5x4Unorm || format === GPUTextureFormat.ASTC5x4UnormSRGB ) return { byteLength: 16, width: 5, height: 4 };
  51535. if ( format === GPUTextureFormat.ASTC5x5Unorm || format === GPUTextureFormat.ASTC5x5UnormSRGB ) return { byteLength: 16, width: 5, height: 5 };
  51536. if ( format === GPUTextureFormat.ASTC6x5Unorm || format === GPUTextureFormat.ASTC6x5UnormSRGB ) return { byteLength: 16, width: 6, height: 5 };
  51537. if ( format === GPUTextureFormat.ASTC6x6Unorm || format === GPUTextureFormat.ASTC6x6UnormSRGB ) return { byteLength: 16, width: 6, height: 6 };
  51538. if ( format === GPUTextureFormat.ASTC8x5Unorm || format === GPUTextureFormat.ASTC8x5UnormSRGB ) return { byteLength: 16, width: 8, height: 5 };
  51539. if ( format === GPUTextureFormat.ASTC8x6Unorm || format === GPUTextureFormat.ASTC8x6UnormSRGB ) return { byteLength: 16, width: 8, height: 6 };
  51540. if ( format === GPUTextureFormat.ASTC8x8Unorm || format === GPUTextureFormat.ASTC8x8UnormSRGB ) return { byteLength: 16, width: 8, height: 8 };
  51541. if ( format === GPUTextureFormat.ASTC10x5Unorm || format === GPUTextureFormat.ASTC10x5UnormSRGB ) return { byteLength: 16, width: 10, height: 5 };
  51542. if ( format === GPUTextureFormat.ASTC10x6Unorm || format === GPUTextureFormat.ASTC10x6UnormSRGB ) return { byteLength: 16, width: 10, height: 6 };
  51543. if ( format === GPUTextureFormat.ASTC10x8Unorm || format === GPUTextureFormat.ASTC10x8UnormSRGB ) return { byteLength: 16, width: 10, height: 8 };
  51544. if ( format === GPUTextureFormat.ASTC10x10Unorm || format === GPUTextureFormat.ASTC10x10UnormSRGB ) return { byteLength: 16, width: 10, height: 10 };
  51545. if ( format === GPUTextureFormat.ASTC12x10Unorm || format === GPUTextureFormat.ASTC12x10UnormSRGB ) return { byteLength: 16, width: 12, height: 10 };
  51546. if ( format === GPUTextureFormat.ASTC12x12Unorm || format === GPUTextureFormat.ASTC12x12UnormSRGB ) return { byteLength: 16, width: 12, height: 12 };
  51547. }
  51548. /**
  51549. * Converts the three.js uv wrapping constants to GPU address mode constants.
  51550. *
  51551. * @private
  51552. * @param {number} value - The three.js constant defining a uv wrapping mode.
  51553. * @return {string} The GPU address mode.
  51554. */
  51555. _convertAddressMode( value ) {
  51556. let addressMode = GPUAddressMode.ClampToEdge;
  51557. if ( value === RepeatWrapping ) {
  51558. addressMode = GPUAddressMode.Repeat;
  51559. } else if ( value === MirroredRepeatWrapping ) {
  51560. addressMode = GPUAddressMode.MirrorRepeat;
  51561. }
  51562. return addressMode;
  51563. }
  51564. /**
  51565. * Converts the three.js filter constants to GPU filter constants.
  51566. *
  51567. * @private
  51568. * @param {number} value - The three.js constant defining a filter mode.
  51569. * @return {string} The GPU filter mode.
  51570. */
  51571. _convertFilterMode( value ) {
  51572. let filterMode = GPUFilterMode.Linear;
  51573. if ( value === NearestFilter || value === NearestMipmapNearestFilter || value === NearestMipmapLinearFilter ) {
  51574. filterMode = GPUFilterMode.Nearest;
  51575. }
  51576. return filterMode;
  51577. }
  51578. /**
  51579. * Returns the bytes-per-texel value for the given GPU texture format.
  51580. *
  51581. * @private
  51582. * @param {string} format - The GPU texture format.
  51583. * @return {number} The bytes-per-texel.
  51584. */
  51585. _getBytesPerTexel( format ) {
  51586. // 8-bit formats
  51587. if ( format === GPUTextureFormat.R8Unorm ||
  51588. format === GPUTextureFormat.R8Snorm ||
  51589. format === GPUTextureFormat.R8Uint ||
  51590. format === GPUTextureFormat.R8Sint ) return 1;
  51591. // 16-bit formats
  51592. if ( format === GPUTextureFormat.R16Uint ||
  51593. format === GPUTextureFormat.R16Sint ||
  51594. format === GPUTextureFormat.R16Float ||
  51595. format === GPUTextureFormat.RG8Unorm ||
  51596. format === GPUTextureFormat.RG8Snorm ||
  51597. format === GPUTextureFormat.RG8Uint ||
  51598. format === GPUTextureFormat.RG8Sint ) return 2;
  51599. // 32-bit formats
  51600. if ( format === GPUTextureFormat.R32Uint ||
  51601. format === GPUTextureFormat.R32Sint ||
  51602. format === GPUTextureFormat.R32Float ||
  51603. format === GPUTextureFormat.RG16Uint ||
  51604. format === GPUTextureFormat.RG16Sint ||
  51605. format === GPUTextureFormat.RG16Float ||
  51606. format === GPUTextureFormat.RGBA8Unorm ||
  51607. format === GPUTextureFormat.RGBA8UnormSRGB ||
  51608. format === GPUTextureFormat.RGBA8Snorm ||
  51609. format === GPUTextureFormat.RGBA8Uint ||
  51610. format === GPUTextureFormat.RGBA8Sint ||
  51611. format === GPUTextureFormat.BGRA8Unorm ||
  51612. format === GPUTextureFormat.BGRA8UnormSRGB ||
  51613. // Packed 32-bit formats
  51614. format === GPUTextureFormat.RGB9E5UFloat ||
  51615. format === GPUTextureFormat.RGB10A2Unorm ||
  51616. format === GPUTextureFormat.RG11B10UFloat ||
  51617. format === GPUTextureFormat.Depth32Float ||
  51618. format === GPUTextureFormat.Depth24Plus ||
  51619. format === GPUTextureFormat.Depth24PlusStencil8 ||
  51620. format === GPUTextureFormat.Depth32FloatStencil8 ) return 4;
  51621. // 64-bit formats
  51622. if ( format === GPUTextureFormat.RG32Uint ||
  51623. format === GPUTextureFormat.RG32Sint ||
  51624. format === GPUTextureFormat.RG32Float ||
  51625. format === GPUTextureFormat.RGBA16Uint ||
  51626. format === GPUTextureFormat.RGBA16Sint ||
  51627. format === GPUTextureFormat.RGBA16Float ) return 8;
  51628. // 128-bit formats
  51629. if ( format === GPUTextureFormat.RGBA32Uint ||
  51630. format === GPUTextureFormat.RGBA32Sint ||
  51631. format === GPUTextureFormat.RGBA32Float ) return 16;
  51632. }
  51633. /**
  51634. * Returns the corresponding typed array type for the given GPU texture format.
  51635. *
  51636. * @private
  51637. * @param {string} format - The GPU texture format.
  51638. * @return {TypedArray.constructor} The typed array type.
  51639. */
  51640. _getTypedArrayType( format ) {
  51641. if ( format === GPUTextureFormat.R8Uint ) return Uint8Array;
  51642. if ( format === GPUTextureFormat.R8Sint ) return Int8Array;
  51643. if ( format === GPUTextureFormat.R8Unorm ) return Uint8Array;
  51644. if ( format === GPUTextureFormat.R8Snorm ) return Int8Array;
  51645. if ( format === GPUTextureFormat.RG8Uint ) return Uint8Array;
  51646. if ( format === GPUTextureFormat.RG8Sint ) return Int8Array;
  51647. if ( format === GPUTextureFormat.RG8Unorm ) return Uint8Array;
  51648. if ( format === GPUTextureFormat.RG8Snorm ) return Int8Array;
  51649. if ( format === GPUTextureFormat.RGBA8Uint ) return Uint8Array;
  51650. if ( format === GPUTextureFormat.RGBA8Sint ) return Int8Array;
  51651. if ( format === GPUTextureFormat.RGBA8Unorm || format === GPUTextureFormat.RGBA8UnormSRGB ) return Uint8Array;
  51652. if ( format === GPUTextureFormat.RGBA8Snorm ) return Int8Array;
  51653. if ( format === GPUTextureFormat.R16Uint ) return Uint16Array;
  51654. if ( format === GPUTextureFormat.R16Sint ) return Int16Array;
  51655. if ( format === GPUTextureFormat.RG16Uint ) return Uint16Array;
  51656. if ( format === GPUTextureFormat.RG16Sint ) return Int16Array;
  51657. if ( format === GPUTextureFormat.RGBA16Uint ) return Uint16Array;
  51658. if ( format === GPUTextureFormat.RGBA16Sint ) return Int16Array;
  51659. if ( format === GPUTextureFormat.R16Float ) return Uint16Array;
  51660. if ( format === GPUTextureFormat.RG16Float ) return Uint16Array;
  51661. if ( format === GPUTextureFormat.RGBA16Float ) return Uint16Array;
  51662. if ( format === GPUTextureFormat.R32Uint ) return Uint32Array;
  51663. if ( format === GPUTextureFormat.R32Sint ) return Int32Array;
  51664. if ( format === GPUTextureFormat.R32Float ) return Float32Array;
  51665. if ( format === GPUTextureFormat.RG32Uint ) return Uint32Array;
  51666. if ( format === GPUTextureFormat.RG32Sint ) return Int32Array;
  51667. if ( format === GPUTextureFormat.RG32Float ) return Float32Array;
  51668. if ( format === GPUTextureFormat.RGBA32Uint ) return Uint32Array;
  51669. if ( format === GPUTextureFormat.RGBA32Sint ) return Int32Array;
  51670. if ( format === GPUTextureFormat.RGBA32Float ) return Float32Array;
  51671. if ( format === GPUTextureFormat.BGRA8Unorm || format === GPUTextureFormat.BGRA8UnormSRGB ) return Uint8Array;
  51672. if ( format === GPUTextureFormat.RGB10A2Unorm ) return Uint32Array;
  51673. if ( format === GPUTextureFormat.RGB9E5UFloat ) return Uint32Array;
  51674. if ( format === GPUTextureFormat.RG11B10UFloat ) return Uint32Array;
  51675. if ( format === GPUTextureFormat.Depth32Float ) return Float32Array;
  51676. if ( format === GPUTextureFormat.Depth24Plus ) return Uint32Array;
  51677. if ( format === GPUTextureFormat.Depth24PlusStencil8 ) return Uint32Array;
  51678. if ( format === GPUTextureFormat.Depth32FloatStencil8 ) return Float32Array;
  51679. }
  51680. /**
  51681. * Returns the GPU dimensions for the given texture.
  51682. *
  51683. * @private
  51684. * @param {Texture} texture - The texture.
  51685. * @return {string} The GPU dimension.
  51686. */
  51687. _getDimension( texture ) {
  51688. let dimension;
  51689. if ( texture.is3DTexture || texture.isData3DTexture ) {
  51690. dimension = GPUTextureDimension.ThreeD;
  51691. } else {
  51692. dimension = GPUTextureDimension.TwoD;
  51693. }
  51694. return dimension;
  51695. }
  51696. }
  51697. /**
  51698. * Returns the GPU format for the given texture.
  51699. *
  51700. * @param {Texture} texture - The texture.
  51701. * @param {?GPUDevice} [device=null] - The GPU device which is used for feature detection.
  51702. * It is not necessary to apply the device for most formats.
  51703. * @return {string} The GPU format.
  51704. */
  51705. function getFormat( texture, device = null ) {
  51706. const format = texture.format;
  51707. const type = texture.type;
  51708. const colorSpace = texture.colorSpace;
  51709. const transfer = ColorManagement.getTransfer( colorSpace );
  51710. let formatGPU;
  51711. if ( texture.isCompressedTexture === true || texture.isCompressedArrayTexture === true ) {
  51712. switch ( format ) {
  51713. case RGB_S3TC_DXT1_Format:
  51714. case RGBA_S3TC_DXT1_Format:
  51715. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.BC1RGBAUnormSRGB : GPUTextureFormat.BC1RGBAUnorm;
  51716. break;
  51717. case RGBA_S3TC_DXT3_Format:
  51718. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.BC2RGBAUnormSRGB : GPUTextureFormat.BC2RGBAUnorm;
  51719. break;
  51720. case RGBA_S3TC_DXT5_Format:
  51721. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.BC3RGBAUnormSRGB : GPUTextureFormat.BC3RGBAUnorm;
  51722. break;
  51723. case RED_RGTC1_Format:
  51724. formatGPU = GPUTextureFormat.BC4RUnorm;
  51725. break;
  51726. case SIGNED_RED_RGTC1_Format:
  51727. formatGPU = GPUTextureFormat.BC4RSnorm;
  51728. break;
  51729. case RED_GREEN_RGTC2_Format:
  51730. formatGPU = GPUTextureFormat.BC5RGUnorm;
  51731. break;
  51732. case SIGNED_RED_GREEN_RGTC2_Format:
  51733. formatGPU = GPUTextureFormat.BC5RGSnorm;
  51734. break;
  51735. case RGBA_BPTC_Format:
  51736. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.BC7RGBAUnormSRGB : GPUTextureFormat.BC7RGBAUnorm;
  51737. break;
  51738. case RGB_ETC2_Format:
  51739. case RGB_ETC1_Format:
  51740. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ETC2RGB8UnormSRGB : GPUTextureFormat.ETC2RGB8Unorm;
  51741. break;
  51742. case RGBA_ETC2_EAC_Format:
  51743. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ETC2RGBA8UnormSRGB : GPUTextureFormat.ETC2RGBA8Unorm;
  51744. break;
  51745. case R11_EAC_Format:
  51746. formatGPU = GPUTextureFormat.EACR11Unorm;
  51747. break;
  51748. case SIGNED_R11_EAC_Format:
  51749. formatGPU = GPUTextureFormat.EACR11Snorm;
  51750. break;
  51751. case RG11_EAC_Format:
  51752. formatGPU = GPUTextureFormat.EACRG11Unorm;
  51753. break;
  51754. case SIGNED_RG11_EAC_Format:
  51755. formatGPU = GPUTextureFormat.EACRG11Snorm;
  51756. break;
  51757. case RGBA_ASTC_4x4_Format:
  51758. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ASTC4x4UnormSRGB : GPUTextureFormat.ASTC4x4Unorm;
  51759. break;
  51760. case RGBA_ASTC_5x4_Format:
  51761. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ASTC5x4UnormSRGB : GPUTextureFormat.ASTC5x4Unorm;
  51762. break;
  51763. case RGBA_ASTC_5x5_Format:
  51764. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ASTC5x5UnormSRGB : GPUTextureFormat.ASTC5x5Unorm;
  51765. break;
  51766. case RGBA_ASTC_6x5_Format:
  51767. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ASTC6x5UnormSRGB : GPUTextureFormat.ASTC6x5Unorm;
  51768. break;
  51769. case RGBA_ASTC_6x6_Format:
  51770. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ASTC6x6UnormSRGB : GPUTextureFormat.ASTC6x6Unorm;
  51771. break;
  51772. case RGBA_ASTC_8x5_Format:
  51773. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ASTC8x5UnormSRGB : GPUTextureFormat.ASTC8x5Unorm;
  51774. break;
  51775. case RGBA_ASTC_8x6_Format:
  51776. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ASTC8x6UnormSRGB : GPUTextureFormat.ASTC8x6Unorm;
  51777. break;
  51778. case RGBA_ASTC_8x8_Format:
  51779. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ASTC8x8UnormSRGB : GPUTextureFormat.ASTC8x8Unorm;
  51780. break;
  51781. case RGBA_ASTC_10x5_Format:
  51782. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ASTC10x5UnormSRGB : GPUTextureFormat.ASTC10x5Unorm;
  51783. break;
  51784. case RGBA_ASTC_10x6_Format:
  51785. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ASTC10x6UnormSRGB : GPUTextureFormat.ASTC10x6Unorm;
  51786. break;
  51787. case RGBA_ASTC_10x8_Format:
  51788. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ASTC10x8UnormSRGB : GPUTextureFormat.ASTC10x8Unorm;
  51789. break;
  51790. case RGBA_ASTC_10x10_Format:
  51791. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ASTC10x10UnormSRGB : GPUTextureFormat.ASTC10x10Unorm;
  51792. break;
  51793. case RGBA_ASTC_12x10_Format:
  51794. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ASTC12x10UnormSRGB : GPUTextureFormat.ASTC12x10Unorm;
  51795. break;
  51796. case RGBA_ASTC_12x12_Format:
  51797. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ASTC12x12UnormSRGB : GPUTextureFormat.ASTC12x12Unorm;
  51798. break;
  51799. case RGBAFormat:
  51800. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.RGBA8UnormSRGB : GPUTextureFormat.RGBA8Unorm;
  51801. break;
  51802. default:
  51803. error( 'WebGPURenderer: Unsupported texture format.', format );
  51804. }
  51805. } else {
  51806. switch ( format ) {
  51807. case RGBAFormat:
  51808. switch ( type ) {
  51809. case ByteType:
  51810. formatGPU = GPUTextureFormat.RGBA8Snorm;
  51811. break;
  51812. case ShortType:
  51813. formatGPU = GPUTextureFormat.RGBA16Sint;
  51814. break;
  51815. case UnsignedShortType:
  51816. formatGPU = GPUTextureFormat.RGBA16Uint;
  51817. break;
  51818. case UnsignedIntType:
  51819. formatGPU = GPUTextureFormat.RGBA32Uint;
  51820. break;
  51821. case IntType:
  51822. formatGPU = GPUTextureFormat.RGBA32Sint;
  51823. break;
  51824. case UnsignedByteType:
  51825. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.RGBA8UnormSRGB : GPUTextureFormat.RGBA8Unorm;
  51826. break;
  51827. case HalfFloatType:
  51828. formatGPU = GPUTextureFormat.RGBA16Float;
  51829. break;
  51830. case FloatType:
  51831. formatGPU = GPUTextureFormat.RGBA32Float;
  51832. break;
  51833. default:
  51834. error( 'WebGPURenderer: Unsupported texture type with RGBAFormat.', type );
  51835. }
  51836. break;
  51837. case RGBFormat:
  51838. switch ( type ) {
  51839. case UnsignedInt5999Type:
  51840. formatGPU = GPUTextureFormat.RGB9E5UFloat;
  51841. break;
  51842. case UnsignedInt101111Type:
  51843. formatGPU = GPUTextureFormat.RG11B10UFloat;
  51844. break;
  51845. default:
  51846. error( 'WebGPURenderer: Unsupported texture type with RGBFormat.', type );
  51847. }
  51848. break;
  51849. case RedFormat:
  51850. switch ( type ) {
  51851. case ByteType:
  51852. formatGPU = GPUTextureFormat.R8Snorm;
  51853. break;
  51854. case ShortType:
  51855. formatGPU = GPUTextureFormat.R16Sint;
  51856. break;
  51857. case UnsignedShortType:
  51858. formatGPU = GPUTextureFormat.R16Uint;
  51859. break;
  51860. case UnsignedIntType:
  51861. formatGPU = GPUTextureFormat.R32Uint;
  51862. break;
  51863. case IntType:
  51864. formatGPU = GPUTextureFormat.R32Sint;
  51865. break;
  51866. case UnsignedByteType:
  51867. formatGPU = GPUTextureFormat.R8Unorm;
  51868. break;
  51869. case HalfFloatType:
  51870. formatGPU = GPUTextureFormat.R16Float;
  51871. break;
  51872. case FloatType:
  51873. formatGPU = GPUTextureFormat.R32Float;
  51874. break;
  51875. default:
  51876. error( 'WebGPURenderer: Unsupported texture type with RedFormat.', type );
  51877. }
  51878. break;
  51879. case RGFormat:
  51880. switch ( type ) {
  51881. case ByteType:
  51882. formatGPU = GPUTextureFormat.RG8Snorm;
  51883. break;
  51884. case ShortType:
  51885. formatGPU = GPUTextureFormat.RG16Sint;
  51886. break;
  51887. case UnsignedShortType:
  51888. formatGPU = GPUTextureFormat.RG16Uint;
  51889. break;
  51890. case UnsignedIntType:
  51891. formatGPU = GPUTextureFormat.RG32Uint;
  51892. break;
  51893. case IntType:
  51894. formatGPU = GPUTextureFormat.RG32Sint;
  51895. break;
  51896. case UnsignedByteType:
  51897. formatGPU = GPUTextureFormat.RG8Unorm;
  51898. break;
  51899. case HalfFloatType:
  51900. formatGPU = GPUTextureFormat.RG16Float;
  51901. break;
  51902. case FloatType:
  51903. formatGPU = GPUTextureFormat.RG32Float;
  51904. break;
  51905. default:
  51906. error( 'WebGPURenderer: Unsupported texture type with RGFormat.', type );
  51907. }
  51908. break;
  51909. case DepthFormat:
  51910. switch ( type ) {
  51911. case UnsignedShortType:
  51912. formatGPU = GPUTextureFormat.Depth16Unorm;
  51913. break;
  51914. case UnsignedIntType:
  51915. formatGPU = GPUTextureFormat.Depth24Plus;
  51916. break;
  51917. case FloatType:
  51918. formatGPU = GPUTextureFormat.Depth32Float;
  51919. break;
  51920. default:
  51921. error( 'WebGPURenderer: Unsupported texture type with DepthFormat.', type );
  51922. }
  51923. break;
  51924. case DepthStencilFormat:
  51925. switch ( type ) {
  51926. case UnsignedInt248Type:
  51927. formatGPU = GPUTextureFormat.Depth24PlusStencil8;
  51928. break;
  51929. case FloatType:
  51930. if ( device && device.features.has( GPUFeatureName.Depth32FloatStencil8 ) === false ) {
  51931. error( 'WebGPURenderer: Depth textures with DepthStencilFormat + FloatType can only be used with the "depth32float-stencil8" GPU feature.' );
  51932. }
  51933. formatGPU = GPUTextureFormat.Depth32FloatStencil8;
  51934. break;
  51935. default:
  51936. error( 'WebGPURenderer: Unsupported texture type with DepthStencilFormat.', type );
  51937. }
  51938. break;
  51939. case RedIntegerFormat:
  51940. switch ( type ) {
  51941. case IntType:
  51942. formatGPU = GPUTextureFormat.R32Sint;
  51943. break;
  51944. case UnsignedIntType:
  51945. formatGPU = GPUTextureFormat.R32Uint;
  51946. break;
  51947. default:
  51948. error( 'WebGPURenderer: Unsupported texture type with RedIntegerFormat.', type );
  51949. }
  51950. break;
  51951. case RGIntegerFormat:
  51952. switch ( type ) {
  51953. case IntType:
  51954. formatGPU = GPUTextureFormat.RG32Sint;
  51955. break;
  51956. case UnsignedIntType:
  51957. formatGPU = GPUTextureFormat.RG32Uint;
  51958. break;
  51959. default:
  51960. error( 'WebGPURenderer: Unsupported texture type with RGIntegerFormat.', type );
  51961. }
  51962. break;
  51963. case RGBAIntegerFormat:
  51964. switch ( type ) {
  51965. case IntType:
  51966. formatGPU = GPUTextureFormat.RGBA32Sint;
  51967. break;
  51968. case UnsignedIntType:
  51969. formatGPU = GPUTextureFormat.RGBA32Uint;
  51970. break;
  51971. default:
  51972. error( 'WebGPURenderer: Unsupported texture type with RGBAIntegerFormat.', type );
  51973. }
  51974. break;
  51975. default:
  51976. error( 'WebGPURenderer: Unsupported texture format.', format );
  51977. }
  51978. }
  51979. return formatGPU;
  51980. }
  51981. const declarationRegexp = /^[fn]*\s*([a-z_0-9]+)?\s*\(([\s\S]*?)\)\s*[\-\>]*\s*([a-z_0-9]+(?:<[\s\S]+?>)?)/i;
  51982. const propertiesRegexp = /([a-z_0-9]+)\s*:\s*([a-z_0-9]+(?:<[\s\S]+?>)?)/ig;
  51983. const wgslTypeLib$1 = {
  51984. 'f32': 'float',
  51985. 'i32': 'int',
  51986. 'u32': 'uint',
  51987. 'bool': 'bool',
  51988. 'vec2<f32>': 'vec2',
  51989. 'vec2<i32>': 'ivec2',
  51990. 'vec2<u32>': 'uvec2',
  51991. 'vec2<bool>': 'bvec2',
  51992. 'vec2f': 'vec2',
  51993. 'vec2i': 'ivec2',
  51994. 'vec2u': 'uvec2',
  51995. 'vec2b': 'bvec2',
  51996. 'vec3<f32>': 'vec3',
  51997. 'vec3<i32>': 'ivec3',
  51998. 'vec3<u32>': 'uvec3',
  51999. 'vec3<bool>': 'bvec3',
  52000. 'vec3f': 'vec3',
  52001. 'vec3i': 'ivec3',
  52002. 'vec3u': 'uvec3',
  52003. 'vec3b': 'bvec3',
  52004. 'vec4<f32>': 'vec4',
  52005. 'vec4<i32>': 'ivec4',
  52006. 'vec4<u32>': 'uvec4',
  52007. 'vec4<bool>': 'bvec4',
  52008. 'vec4f': 'vec4',
  52009. 'vec4i': 'ivec4',
  52010. 'vec4u': 'uvec4',
  52011. 'vec4b': 'bvec4',
  52012. 'mat2x2<f32>': 'mat2',
  52013. 'mat2x2f': 'mat2',
  52014. 'mat3x3<f32>': 'mat3',
  52015. 'mat3x3f': 'mat3',
  52016. 'mat4x4<f32>': 'mat4',
  52017. 'mat4x4f': 'mat4',
  52018. 'sampler': 'sampler',
  52019. 'texture_1d': 'texture',
  52020. 'texture_2d': 'texture',
  52021. 'texture_2d_array': 'texture',
  52022. 'texture_multisampled_2d': 'cubeTexture',
  52023. 'texture_depth_2d': 'depthTexture',
  52024. 'texture_depth_2d_array': 'depthTexture',
  52025. 'texture_depth_multisampled_2d': 'depthTexture',
  52026. 'texture_depth_cube': 'depthTexture',
  52027. 'texture_depth_cube_array': 'depthTexture',
  52028. 'texture_3d': 'texture3D',
  52029. 'texture_cube': 'cubeTexture',
  52030. 'texture_cube_array': 'cubeTexture',
  52031. 'texture_storage_1d': 'storageTexture',
  52032. 'texture_storage_2d': 'storageTexture',
  52033. 'texture_storage_2d_array': 'storageTexture',
  52034. 'texture_storage_3d': 'storageTexture'
  52035. };
  52036. const parse = ( source ) => {
  52037. source = source.trim();
  52038. const declaration = source.match( declarationRegexp );
  52039. if ( declaration !== null && declaration.length === 4 ) {
  52040. const inputsCode = declaration[ 2 ];
  52041. const propsMatches = [];
  52042. let match = null;
  52043. while ( ( match = propertiesRegexp.exec( inputsCode ) ) !== null ) {
  52044. propsMatches.push( { name: match[ 1 ], type: match[ 2 ] } );
  52045. }
  52046. // Process matches to correctly pair names and types
  52047. const inputs = [];
  52048. for ( let i = 0; i < propsMatches.length; i ++ ) {
  52049. const { name, type } = propsMatches[ i ];
  52050. let resolvedType = type;
  52051. if ( resolvedType.startsWith( 'ptr' ) ) {
  52052. resolvedType = 'pointer';
  52053. } else {
  52054. if ( resolvedType.startsWith( 'texture' ) ) {
  52055. resolvedType = type.split( '<' )[ 0 ];
  52056. }
  52057. resolvedType = wgslTypeLib$1[ resolvedType ];
  52058. }
  52059. inputs.push( new NodeFunctionInput( resolvedType, name ) );
  52060. }
  52061. const blockCode = source.substring( declaration[ 0 ].length );
  52062. const outputType = declaration[ 3 ] || 'void';
  52063. const name = declaration[ 1 ] !== undefined ? declaration[ 1 ] : '';
  52064. const type = wgslTypeLib$1[ outputType ] || outputType;
  52065. return {
  52066. type,
  52067. inputs,
  52068. name,
  52069. inputsCode,
  52070. blockCode,
  52071. outputType
  52072. };
  52073. } else {
  52074. throw new Error( 'FunctionNode: Function is not a WGSL code.' );
  52075. }
  52076. };
  52077. /**
  52078. * This class represents a WSL node function.
  52079. *
  52080. * @augments NodeFunction
  52081. */
  52082. class WGSLNodeFunction extends NodeFunction {
  52083. /**
  52084. * Constructs a new WGSL node function.
  52085. *
  52086. * @param {string} source - The WGSL source.
  52087. */
  52088. constructor( source ) {
  52089. const { type, inputs, name, inputsCode, blockCode, outputType } = parse( source );
  52090. super( type, inputs, name );
  52091. this.inputsCode = inputsCode;
  52092. this.blockCode = blockCode;
  52093. this.outputType = outputType;
  52094. }
  52095. /**
  52096. * This method returns the WGSL code of the node function.
  52097. *
  52098. * @param {string} [name=this.name] - The function's name.
  52099. * @return {string} The shader code.
  52100. */
  52101. getCode( name = this.name ) {
  52102. const outputType = this.outputType !== 'void' ? '-> ' + this.outputType : '';
  52103. return `fn ${ name } ( ${ this.inputsCode.trim() } ) ${ outputType }` + this.blockCode;
  52104. }
  52105. }
  52106. /**
  52107. * A WGSL node parser.
  52108. *
  52109. * @augments NodeParser
  52110. */
  52111. class WGSLNodeParser extends NodeParser {
  52112. /**
  52113. * The method parses the given WGSL code an returns a node function.
  52114. *
  52115. * @param {string} source - The WGSL code.
  52116. * @return {WGSLNodeFunction} A node function.
  52117. */
  52118. parseFunction( source ) {
  52119. return new WGSLNodeFunction( source );
  52120. }
  52121. }
  52122. const accessNames = {
  52123. [ NodeAccess.READ_ONLY ]: 'read',
  52124. [ NodeAccess.WRITE_ONLY ]: 'write',
  52125. [ NodeAccess.READ_WRITE ]: 'read_write'
  52126. };
  52127. const wrapNames = {
  52128. [ RepeatWrapping ]: 'repeat',
  52129. [ ClampToEdgeWrapping ]: 'clamp',
  52130. [ MirroredRepeatWrapping ]: 'mirror'
  52131. };
  52132. const gpuShaderStageLib = {
  52133. 'vertex': GPUShaderStage.VERTEX,
  52134. 'fragment': GPUShaderStage.FRAGMENT,
  52135. 'compute': GPUShaderStage.COMPUTE
  52136. };
  52137. const supports = {
  52138. instance: true,
  52139. swizzleAssign: false,
  52140. storageBuffer: true
  52141. };
  52142. const wgslFnOpLib = {
  52143. '^^': 'tsl_xor'
  52144. };
  52145. const wgslTypeLib = {
  52146. float: 'f32',
  52147. int: 'i32',
  52148. uint: 'u32',
  52149. bool: 'bool',
  52150. color: 'vec3<f32>',
  52151. vec2: 'vec2<f32>',
  52152. ivec2: 'vec2<i32>',
  52153. uvec2: 'vec2<u32>',
  52154. bvec2: 'vec2<bool>',
  52155. vec3: 'vec3<f32>',
  52156. ivec3: 'vec3<i32>',
  52157. uvec3: 'vec3<u32>',
  52158. bvec3: 'vec3<bool>',
  52159. vec4: 'vec4<f32>',
  52160. ivec4: 'vec4<i32>',
  52161. uvec4: 'vec4<u32>',
  52162. bvec4: 'vec4<bool>',
  52163. mat2: 'mat2x2<f32>',
  52164. mat3: 'mat3x3<f32>',
  52165. mat4: 'mat4x4<f32>'
  52166. };
  52167. const wgslCodeCache = {};
  52168. const wgslPolyfill = {
  52169. tsl_xor: new CodeNode( 'fn tsl_xor( a : bool, b : bool ) -> bool { return ( a || b ) && !( a && b ); }' ),
  52170. mod_float: new CodeNode( 'fn tsl_mod_float( x : f32, y : f32 ) -> f32 { return x - y * floor( x / y ); }' ),
  52171. mod_vec2: new CodeNode( 'fn tsl_mod_vec2( x : vec2f, y : vec2f ) -> vec2f { return x - y * floor( x / y ); }' ),
  52172. mod_vec3: new CodeNode( 'fn tsl_mod_vec3( x : vec3f, y : vec3f ) -> vec3f { return x - y * floor( x / y ); }' ),
  52173. mod_vec4: new CodeNode( 'fn tsl_mod_vec4( x : vec4f, y : vec4f ) -> vec4f { return x - y * floor( x / y ); }' ),
  52174. equals_bool: new CodeNode( 'fn tsl_equals_bool( a : bool, b : bool ) -> bool { return a == b; }' ),
  52175. 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 ); }' ),
  52176. 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 ); }' ),
  52177. 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 ); }' ),
  52178. repeatWrapping_float: new CodeNode( 'fn tsl_repeatWrapping_float( coord: f32 ) -> f32 { return fract( coord ); }' ),
  52179. 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 ); }' ),
  52180. clampWrapping_float: new CodeNode( 'fn tsl_clampWrapping_float( coord: f32 ) -> f32 { return clamp( coord, 0.0, 1.0 ); }' ),
  52181. biquadraticTexture: new CodeNode( /* wgsl */`
  52182. fn tsl_biquadraticTexture( map : texture_2d<f32>, coord : vec2f, iRes : vec2u, level : u32 ) -> vec4f {
  52183. let res = vec2f( iRes );
  52184. let uvScaled = coord * res;
  52185. let uvWrapping = ( ( uvScaled % res ) + res ) % res;
  52186. // https://www.shadertoy.com/view/WtyXRy
  52187. let uv = uvWrapping - 0.5;
  52188. let iuv = floor( uv );
  52189. let f = fract( uv );
  52190. let rg1 = textureLoad( map, vec2u( iuv + vec2( 0.5, 0.5 ) ) % iRes, level );
  52191. let rg2 = textureLoad( map, vec2u( iuv + vec2( 1.5, 0.5 ) ) % iRes, level );
  52192. let rg3 = textureLoad( map, vec2u( iuv + vec2( 0.5, 1.5 ) ) % iRes, level );
  52193. let rg4 = textureLoad( map, vec2u( iuv + vec2( 1.5, 1.5 ) ) % iRes, level );
  52194. return mix( mix( rg1, rg2, f.x ), mix( rg3, rg4, f.x ), f.y );
  52195. }
  52196. ` )
  52197. };
  52198. const wgslMethods = {
  52199. dFdx: 'dpdx',
  52200. dFdy: '- dpdy',
  52201. mod_float: 'tsl_mod_float',
  52202. mod_vec2: 'tsl_mod_vec2',
  52203. mod_vec3: 'tsl_mod_vec3',
  52204. mod_vec4: 'tsl_mod_vec4',
  52205. equals_bool: 'tsl_equals_bool',
  52206. equals_bvec2: 'tsl_equals_bvec2',
  52207. equals_bvec3: 'tsl_equals_bvec3',
  52208. equals_bvec4: 'tsl_equals_bvec4',
  52209. inversesqrt: 'inverseSqrt',
  52210. bitcast: 'bitcast<f32>',
  52211. floatpack_snorm_2x16: 'pack2x16snorm',
  52212. floatpack_unorm_2x16: 'pack2x16unorm',
  52213. floatpack_float16_2x16: 'pack2x16float',
  52214. floatunpack_snorm_2x16: 'unpack2x16snorm',
  52215. floatunpack_unorm_2x16: 'unpack2x16unorm',
  52216. floatunpack_float16_2x16: 'unpack2x16float'
  52217. };
  52218. //
  52219. let diagnostics = '';
  52220. if ( ( typeof navigator !== 'undefined' && /Firefox|Deno/g.test( navigator.userAgent ) ) !== true ) {
  52221. diagnostics += 'diagnostic( off, derivative_uniformity );\n';
  52222. }
  52223. /**
  52224. * A node builder targeting WGSL.
  52225. *
  52226. * This module generates WGSL shader code from node materials and also
  52227. * generates the respective bindings and vertex buffer definitions. These
  52228. * data are later used by the renderer to create render and compute pipelines
  52229. * for render objects.
  52230. *
  52231. * @augments NodeBuilder
  52232. */
  52233. class WGSLNodeBuilder extends NodeBuilder {
  52234. /**
  52235. * Constructs a new WGSL node builder renderer.
  52236. *
  52237. * @param {Object3D} object - The 3D object.
  52238. * @param {Renderer} renderer - The renderer.
  52239. */
  52240. constructor( object, renderer ) {
  52241. super( object, renderer, new WGSLNodeParser() );
  52242. /**
  52243. * A dictionary that holds for each shader stage ('vertex', 'fragment', 'compute')
  52244. * another dictionary which manages UBOs per group ('render','frame','object').
  52245. *
  52246. * @type {Object<string,Object<string,NodeUniformsGroup>>}
  52247. */
  52248. this.uniformGroups = {};
  52249. /**
  52250. * A dictionary that holds for each shader stage a Map of builtins.
  52251. *
  52252. * @type {Object<string,Map<string,Object>>}
  52253. */
  52254. this.builtins = {};
  52255. /**
  52256. * A dictionary that holds for each shader stage a Set of directives.
  52257. *
  52258. * @type {Object<string,Set<string>>}
  52259. */
  52260. this.directives = {};
  52261. /**
  52262. * A map for managing scope arrays. Only relevant for when using
  52263. * {@link WorkgroupInfoNode} in context of compute shaders.
  52264. *
  52265. * @type {Map<string,Object>}
  52266. */
  52267. this.scopedArrays = new Map();
  52268. }
  52269. /**
  52270. * Generates the WGSL snippet for sampled textures.
  52271. *
  52272. * @private
  52273. * @param {Texture} texture - The texture.
  52274. * @param {string} textureProperty - The name of the texture uniform in the shader.
  52275. * @param {string} uvSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  52276. * @param {?string} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  52277. * @param {?string} offsetSnippet - A WGSL snippet that represents the offset that will be applied to the unnormalized texture coordinate before sampling the texture.
  52278. * @param {string} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  52279. * @return {string} The WGSL snippet.
  52280. */
  52281. _generateTextureSample( texture, textureProperty, uvSnippet, depthSnippet, offsetSnippet, shaderStage = this.shaderStage ) {
  52282. if ( shaderStage === 'fragment' ) {
  52283. if ( depthSnippet ) {
  52284. if ( offsetSnippet ) {
  52285. return `textureSample( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ depthSnippet }, ${ offsetSnippet } )`;
  52286. }
  52287. return `textureSample( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ depthSnippet } )`;
  52288. } else {
  52289. if ( offsetSnippet ) {
  52290. return `textureSample( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ offsetSnippet } )`;
  52291. }
  52292. return `textureSample( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet } )`;
  52293. }
  52294. } else {
  52295. return this.generateTextureSampleLevel( texture, textureProperty, uvSnippet, '0', depthSnippet );
  52296. }
  52297. }
  52298. /**
  52299. * Generates the WGSL snippet when sampling textures with explicit mip level.
  52300. *
  52301. * @private
  52302. * @param {Texture} texture - The texture.
  52303. * @param {string} textureProperty - The name of the texture uniform in the shader.
  52304. * @param {string} uvSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  52305. * @param {string} levelSnippet - A WGSL snippet that represents the mip level, with level 0 containing a full size version of the texture.
  52306. * @param {string} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  52307. * @param {?string} offsetSnippet - A WGSL snippet that represents the offset that will be applied to the unnormalized texture coordinate before sampling the texture.
  52308. * @return {string} The WGSL snippet.
  52309. */
  52310. generateTextureSampleLevel( texture, textureProperty, uvSnippet, levelSnippet, depthSnippet, offsetSnippet ) {
  52311. if ( this.isUnfilterable( texture ) === false ) {
  52312. if ( offsetSnippet ) {
  52313. return `textureSampleLevel( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ levelSnippet }, ${ offsetSnippet } )`;
  52314. }
  52315. return `textureSampleLevel( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ levelSnippet } )`;
  52316. } else if ( this.isFilteredTexture( texture ) ) {
  52317. return this.generateFilteredTexture( texture, textureProperty, uvSnippet, offsetSnippet, levelSnippet );
  52318. } else {
  52319. return this.generateTextureLod( texture, textureProperty, uvSnippet, depthSnippet, offsetSnippet, levelSnippet );
  52320. }
  52321. }
  52322. /**
  52323. * Generates a wrap function used in context of textures.
  52324. *
  52325. * @param {Texture} texture - The texture to generate the function for.
  52326. * @return {string} The name of the generated function.
  52327. */
  52328. generateWrapFunction( texture ) {
  52329. const functionName = `tsl_coord_${ wrapNames[ texture.wrapS ] }S_${ wrapNames[ texture.wrapT ] }_${ texture.is3DTexture || texture.isData3DTexture ? '3d' : '2d' }T`;
  52330. let nodeCode = wgslCodeCache[ functionName ];
  52331. if ( nodeCode === undefined ) {
  52332. const includes = [];
  52333. // For 3D textures, use vec3f; for texture arrays, keep vec2f since array index is separate
  52334. const coordType = texture.is3DTexture || texture.isData3DTexture ? 'vec3f' : 'vec2f';
  52335. let code = `fn ${ functionName }( coord : ${ coordType } ) -> ${ coordType } {\n\n\treturn ${ coordType }(\n`;
  52336. const addWrapSnippet = ( wrap, axis ) => {
  52337. if ( wrap === RepeatWrapping ) {
  52338. includes.push( wgslPolyfill.repeatWrapping_float );
  52339. code += `\t\ttsl_repeatWrapping_float( coord.${ axis } )`;
  52340. } else if ( wrap === ClampToEdgeWrapping ) {
  52341. includes.push( wgslPolyfill.clampWrapping_float );
  52342. code += `\t\ttsl_clampWrapping_float( coord.${ axis } )`;
  52343. } else if ( wrap === MirroredRepeatWrapping ) {
  52344. includes.push( wgslPolyfill.mirrorWrapping_float );
  52345. code += `\t\ttsl_mirrorWrapping_float( coord.${ axis } )`;
  52346. } else {
  52347. code += `\t\tcoord.${ axis }`;
  52348. warn( `WebGPURenderer: Unsupported texture wrap type "${ wrap }" for vertex shader.` );
  52349. }
  52350. };
  52351. addWrapSnippet( texture.wrapS, 'x' );
  52352. code += ',\n';
  52353. addWrapSnippet( texture.wrapT, 'y' );
  52354. if ( texture.is3DTexture || texture.isData3DTexture ) {
  52355. code += ',\n';
  52356. addWrapSnippet( texture.wrapR, 'z' );
  52357. }
  52358. code += '\n\t);\n\n}\n';
  52359. wgslCodeCache[ functionName ] = nodeCode = new CodeNode( code, includes );
  52360. }
  52361. nodeCode.build( this );
  52362. return functionName;
  52363. }
  52364. /**
  52365. * Generates the array declaration string.
  52366. *
  52367. * @param {string} type - The type.
  52368. * @param {?number} [count] - The count.
  52369. * @return {string} The generated value as a shader string.
  52370. */
  52371. generateArrayDeclaration( type, count ) {
  52372. return `array< ${ this.getType( type ) }, ${ count } >`;
  52373. }
  52374. /**
  52375. * Generates a WGSL variable that holds the texture dimension of the given texture.
  52376. * It also returns information about the number of layers (elements) of an arrayed
  52377. * texture as well as the cube face count of cube textures.
  52378. *
  52379. * @param {Texture} texture - The texture to generate the function for.
  52380. * @param {string} textureProperty - The name of the video texture uniform in the shader.
  52381. * @param {string} levelSnippet - A WGSL snippet that represents the mip level, with level 0 containing a full size version of the texture.
  52382. * @return {string} The name of the dimension variable.
  52383. */
  52384. generateTextureDimension( texture, textureProperty, levelSnippet ) {
  52385. const textureData = this.getDataFromNode( texture, this.shaderStage, this.globalCache );
  52386. if ( textureData.dimensionsSnippet === undefined ) textureData.dimensionsSnippet = {};
  52387. let textureDimensionNode = textureData.dimensionsSnippet[ levelSnippet ];
  52388. if ( textureData.dimensionsSnippet[ levelSnippet ] === undefined ) {
  52389. let textureDimensionsParams;
  52390. let dimensionType;
  52391. const { primarySamples } = this.renderer.backend.utils.getTextureSampleData( texture );
  52392. const isMultisampled = primarySamples > 1;
  52393. if ( texture.is3DTexture || texture.isData3DTexture ) {
  52394. dimensionType = 'vec3<u32>';
  52395. } else {
  52396. // Regular 2D textures, depth textures, etc.
  52397. dimensionType = 'vec2<u32>';
  52398. }
  52399. // Build parameters string based on texture type and multisampling
  52400. if ( isMultisampled || texture.isStorageTexture ) {
  52401. textureDimensionsParams = textureProperty;
  52402. } else {
  52403. textureDimensionsParams = `${textureProperty}${levelSnippet ? `, u32( ${ levelSnippet } )` : ''}`;
  52404. }
  52405. textureDimensionNode = new VarNode( new ExpressionNode( `textureDimensions( ${ textureDimensionsParams } )`, dimensionType ) );
  52406. textureData.dimensionsSnippet[ levelSnippet ] = textureDimensionNode;
  52407. if ( texture.isArrayTexture || texture.isDataArrayTexture || texture.is3DTexture || texture.isData3DTexture ) {
  52408. textureData.arrayLayerCount = new VarNode(
  52409. new ExpressionNode(
  52410. `textureNumLayers(${textureProperty})`,
  52411. 'u32'
  52412. )
  52413. );
  52414. }
  52415. // For cube textures, we know it's always 6 faces
  52416. if ( texture.isTextureCube ) {
  52417. textureData.cubeFaceCount = new VarNode(
  52418. new ExpressionNode( '6u', 'u32' )
  52419. );
  52420. }
  52421. }
  52422. return textureDimensionNode.build( this );
  52423. }
  52424. /**
  52425. * Generates the WGSL snippet for a manual filtered texture.
  52426. *
  52427. * @param {Texture} texture - The texture.
  52428. * @param {string} textureProperty - The name of the texture uniform in the shader.
  52429. * @param {string} uvSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  52430. * @param {?string} offsetSnippet - A WGSL snippet that represents the offset that will be applied to the unnormalized texture coordinate before sampling the texture.
  52431. * @param {string} [levelSnippet='0u'] - A WGSL snippet that represents the mip level, with level 0 containing a full size version of the texture.
  52432. * @return {string} The WGSL snippet.
  52433. */
  52434. generateFilteredTexture( texture, textureProperty, uvSnippet, offsetSnippet, levelSnippet = '0u' ) {
  52435. this._include( 'biquadraticTexture' );
  52436. const wrapFunction = this.generateWrapFunction( texture );
  52437. const textureDimension = this.generateTextureDimension( texture, textureProperty, levelSnippet );
  52438. if ( offsetSnippet ) {
  52439. uvSnippet = `${ uvSnippet } + vec2<f32>(${ offsetSnippet }) / ${ textureDimension }`;
  52440. }
  52441. return `tsl_biquadraticTexture( ${ textureProperty }, ${ wrapFunction }( ${ uvSnippet } ), ${ textureDimension }, u32( ${ levelSnippet } ) )`;
  52442. }
  52443. /**
  52444. * Generates the WGSL snippet for a texture lookup with explicit level-of-detail.
  52445. * Since it's a lookup, no sampling or filtering is applied.
  52446. *
  52447. * @param {Texture} texture - The texture.
  52448. * @param {string} textureProperty - The name of the texture uniform in the shader.
  52449. * @param {string} uvSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  52450. * @param {?string} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  52451. * @param {?string} offsetSnippet - A WGSL snippet that represents the offset that will be applied to the unnormalized texture coordinate before sampling the texture.
  52452. * @param {string} [levelSnippet='0u'] - A WGSL snippet that represents the mip level, with level 0 containing a full size version of the texture.
  52453. * @return {string} The WGSL snippet.
  52454. */
  52455. generateTextureLod( texture, textureProperty, uvSnippet, depthSnippet, offsetSnippet, levelSnippet = '0u' ) {
  52456. const wrapFunction = this.generateWrapFunction( texture );
  52457. const textureDimension = this.generateTextureDimension( texture, textureProperty, levelSnippet );
  52458. const vecType = texture.is3DTexture || texture.isData3DTexture ? 'vec3' : 'vec2';
  52459. if ( offsetSnippet ) {
  52460. uvSnippet = `${ uvSnippet } + ${ vecType }<f32>(${ offsetSnippet }) / ${ vecType }<f32>( ${ textureDimension } )`;
  52461. }
  52462. const coordSnippet = `${ vecType }<u32>( ${ wrapFunction }( ${ uvSnippet } ) * ${ vecType }<f32>( ${ textureDimension } ) )`;
  52463. return this.generateTextureLoad( texture, textureProperty, coordSnippet, levelSnippet, depthSnippet, null );
  52464. }
  52465. /**
  52466. * Generates the WGSL snippet that reads a single texel from a texture without sampling or filtering.
  52467. *
  52468. * @param {Texture} texture - The texture.
  52469. * @param {string} textureProperty - The name of the texture uniform in the shader.
  52470. * @param {string} uvIndexSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  52471. * @param {?string} levelSnippet - A WGSL snippet that represents the mip level, with level 0 containing a full size version of the texture.
  52472. * @param {?string} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  52473. * @param {?string} offsetSnippet - A WGSL snippet that represents the offset that will be applied to the unnormalized texture coordinate before sampling the texture.
  52474. * @return {string} The WGSL snippet.
  52475. */
  52476. generateTextureLoad( texture, textureProperty, uvIndexSnippet, levelSnippet, depthSnippet, offsetSnippet ) {
  52477. if ( levelSnippet === null ) levelSnippet = '0u';
  52478. if ( offsetSnippet ) {
  52479. uvIndexSnippet = `${ uvIndexSnippet } + ${ offsetSnippet }`;
  52480. }
  52481. let snippet;
  52482. if ( depthSnippet ) {
  52483. snippet = `textureLoad( ${ textureProperty }, ${ uvIndexSnippet }, ${ depthSnippet }, u32( ${ levelSnippet } ) )`;
  52484. } else {
  52485. snippet = `textureLoad( ${ textureProperty }, ${ uvIndexSnippet }, u32( ${ levelSnippet } ) )`;
  52486. if ( this.renderer.backend.compatibilityMode && texture.isDepthTexture ) {
  52487. snippet += '.x';
  52488. }
  52489. }
  52490. return snippet;
  52491. }
  52492. /**
  52493. * Generates the WGSL snippet that writes a single texel to a texture.
  52494. *
  52495. * @param {Texture} texture - The texture.
  52496. * @param {string} textureProperty - The name of the texture uniform in the shader.
  52497. * @param {string} uvIndexSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  52498. * @param {?string} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  52499. * @param {string} valueSnippet - A WGSL snippet that represent the new texel value.
  52500. * @return {string} The WGSL snippet.
  52501. */
  52502. generateTextureStore( texture, textureProperty, uvIndexSnippet, depthSnippet, valueSnippet ) {
  52503. let snippet;
  52504. if ( depthSnippet ) {
  52505. snippet = `textureStore( ${ textureProperty }, ${ uvIndexSnippet }, ${ depthSnippet }, ${ valueSnippet } )`;
  52506. } else {
  52507. snippet = `textureStore( ${ textureProperty }, ${ uvIndexSnippet }, ${ valueSnippet } )`;
  52508. }
  52509. return snippet;
  52510. }
  52511. /**
  52512. * Returns `true` if the sampled values of the given texture should be compared against a reference value.
  52513. *
  52514. * @param {Texture} texture - The texture.
  52515. * @return {boolean} Whether the sampled values of the given texture should be compared against a reference value or not.
  52516. */
  52517. isSampleCompare( texture ) {
  52518. return texture.isDepthTexture === true && texture.compareFunction !== null;
  52519. }
  52520. /**
  52521. * Returns `true` if the given texture is unfilterable.
  52522. *
  52523. * @param {Texture} texture - The texture.
  52524. * @return {boolean} Whether the given texture is unfilterable or not.
  52525. */
  52526. isUnfilterable( texture ) {
  52527. return this.getComponentTypeFromTexture( texture ) !== 'float' ||
  52528. ( ! this.isAvailable( 'float32Filterable' ) && texture.isDataTexture === true && texture.type === FloatType ) ||
  52529. ( this.isSampleCompare( texture ) === false && texture.minFilter === NearestFilter && texture.magFilter === NearestFilter ) ||
  52530. this.renderer.backend.utils.getTextureSampleData( texture ).primarySamples > 1;
  52531. }
  52532. /**
  52533. * Generates the WGSL snippet for sampling/loading the given texture.
  52534. *
  52535. * @param {Texture} texture - The texture.
  52536. * @param {string} textureProperty - The name of the texture uniform in the shader.
  52537. * @param {string} uvSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  52538. * @param {?string} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  52539. * @param {?string} offsetSnippet - A WGSL snippet that represents the offset that will be applied to the unnormalized texture coordinate before sampling the texture.
  52540. * @param {string} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  52541. * @return {string} The WGSL snippet.
  52542. */
  52543. generateTexture( texture, textureProperty, uvSnippet, depthSnippet, offsetSnippet, shaderStage = this.shaderStage ) {
  52544. let snippet = null;
  52545. if ( this.isUnfilterable( texture ) ) {
  52546. snippet = this.generateTextureLod( texture, textureProperty, uvSnippet, depthSnippet, offsetSnippet, '0', shaderStage );
  52547. } else {
  52548. snippet = this._generateTextureSample( texture, textureProperty, uvSnippet, depthSnippet, offsetSnippet, shaderStage );
  52549. }
  52550. return snippet;
  52551. }
  52552. /**
  52553. * Generates the WGSL snippet for sampling/loading the given texture using explicit gradients.
  52554. *
  52555. * @param {Texture} texture - The texture.
  52556. * @param {string} textureProperty - The name of the texture uniform in the shader.
  52557. * @param {string} uvSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  52558. * @param {Array<string>} gradSnippet - An array holding both gradient WGSL snippets.
  52559. * @param {?string} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  52560. * @param {?string} offsetSnippet - A WGSL snippet that represents the offset that will be applied to the unnormalized texture coordinate before sampling the texture.
  52561. * @param {string} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  52562. * @return {string} The WGSL snippet.
  52563. */
  52564. generateTextureGrad( texture, textureProperty, uvSnippet, gradSnippet, depthSnippet, offsetSnippet, shaderStage = this.shaderStage ) {
  52565. if ( shaderStage === 'fragment' ) {
  52566. // TODO handle i32 or u32 --> uvSnippet, array_index: A, ddx, ddy
  52567. if ( offsetSnippet ) {
  52568. return `textureSampleGrad( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ gradSnippet[ 0 ] }, ${ gradSnippet[ 1 ] }, ${ offsetSnippet } )`;
  52569. }
  52570. return `textureSampleGrad( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ gradSnippet[ 0 ] }, ${ gradSnippet[ 1 ] } )`;
  52571. } else {
  52572. error( `WebGPURenderer: THREE.TextureNode.gradient() does not support ${ shaderStage } shader.` );
  52573. }
  52574. }
  52575. /**
  52576. * Generates the WGSL snippet for sampling a depth texture and comparing the sampled depth values
  52577. * against a reference value.
  52578. *
  52579. * @param {Texture} texture - The texture.
  52580. * @param {string} textureProperty - The name of the texture uniform in the shader.
  52581. * @param {string} uvSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  52582. * @param {string} compareSnippet - A WGSL snippet that represents the reference value.
  52583. * @param {?string} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  52584. * @param {?string} offsetSnippet - A WGSL snippet that represents the offset that will be applied to the unnormalized texture coordinate before sampling the texture.
  52585. * @param {string} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  52586. * @return {string} The WGSL snippet.
  52587. */
  52588. generateTextureCompare( texture, textureProperty, uvSnippet, compareSnippet, depthSnippet, offsetSnippet, shaderStage = this.shaderStage ) {
  52589. if ( shaderStage === 'fragment' ) {
  52590. if ( texture.isDepthTexture === true && texture.isArrayTexture === true ) {
  52591. if ( offsetSnippet ) {
  52592. return `textureSampleCompare( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ depthSnippet }, ${ compareSnippet }, ${ offsetSnippet } )`;
  52593. }
  52594. return `textureSampleCompare( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ depthSnippet }, ${ compareSnippet } )`;
  52595. }
  52596. if ( offsetSnippet ) {
  52597. return `textureSampleCompare( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ compareSnippet }, ${ offsetSnippet } )`;
  52598. }
  52599. return `textureSampleCompare( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ compareSnippet } )`;
  52600. } else {
  52601. error( `WebGPURenderer: THREE.DepthTexture.compareFunction() does not support ${ shaderStage } shader.` );
  52602. }
  52603. }
  52604. /**
  52605. * Generates the WGSL snippet when sampling textures with explicit mip level.
  52606. *
  52607. * @param {Texture} texture - The texture.
  52608. * @param {string} textureProperty - The name of the texture uniform in the shader.
  52609. * @param {string} uvSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  52610. * @param {string} levelSnippet - A WGSL snippet that represents the mip level, with level 0 containing a full size version of the texture.
  52611. * @param {?string} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  52612. * @param {?string} offsetSnippet - A WGSL snippet that represents the offset that will be applied to the unnormalized texture coordinate before sampling the texture.
  52613. * @param {string} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  52614. * @return {string} The WGSL snippet.
  52615. */
  52616. generateTextureLevel( texture, textureProperty, uvSnippet, levelSnippet, depthSnippet, offsetSnippet ) {
  52617. if ( this.isUnfilterable( texture ) === false ) {
  52618. if ( offsetSnippet ) {
  52619. return `textureSampleLevel( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ levelSnippet }, ${ offsetSnippet } )`;
  52620. }
  52621. return `textureSampleLevel( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ levelSnippet } )`;
  52622. } else if ( this.isFilteredTexture( texture ) ) {
  52623. return this.generateFilteredTexture( texture, textureProperty, uvSnippet, offsetSnippet, levelSnippet );
  52624. } else {
  52625. return this.generateTextureLod( texture, textureProperty, uvSnippet, depthSnippet, offsetSnippet, levelSnippet );
  52626. }
  52627. }
  52628. /**
  52629. * Generates the WGSL snippet when sampling textures with a bias to the mip level.
  52630. *
  52631. * @param {Texture} texture - The texture.
  52632. * @param {string} textureProperty - The name of the texture uniform in the shader.
  52633. * @param {string} uvSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  52634. * @param {string} biasSnippet - A WGSL snippet that represents the bias to apply to the mip level before sampling.
  52635. * @param {?string} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  52636. * @param {?string} offsetSnippet - A WGSL snippet that represents the offset that will be applied to the unnormalized texture coordinate before sampling the texture.
  52637. * @param {string} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  52638. * @return {string} The WGSL snippet.
  52639. */
  52640. generateTextureBias( texture, textureProperty, uvSnippet, biasSnippet, depthSnippet, offsetSnippet, shaderStage = this.shaderStage ) {
  52641. if ( shaderStage === 'fragment' ) {
  52642. if ( offsetSnippet ) {
  52643. return `textureSampleBias( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ biasSnippet }, ${ offsetSnippet } )`;
  52644. }
  52645. return `textureSampleBias( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ biasSnippet } )`;
  52646. } else {
  52647. error( `WebGPURenderer: THREE.TextureNode.biasNode does not support ${ shaderStage } shader.` );
  52648. }
  52649. }
  52650. /**
  52651. * Returns a WGSL snippet that represents the property name of the given node.
  52652. *
  52653. * @param {Node} node - The node.
  52654. * @param {string} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  52655. * @return {string} The property name.
  52656. */
  52657. getPropertyName( node, shaderStage = this.shaderStage ) {
  52658. if ( node.isNodeVarying === true && node.needsInterpolation === true ) {
  52659. if ( shaderStage === 'vertex' ) {
  52660. return `varyings.${ node.name }`;
  52661. }
  52662. } else if ( node.isNodeUniform === true ) {
  52663. const name = node.name;
  52664. const type = node.type;
  52665. if ( type === 'texture' || type === 'cubeTexture' || type === 'cubeDepthTexture' || type === 'storageTexture' || type === 'texture3D' ) {
  52666. return name;
  52667. } else if ( type === 'buffer' || type === 'storageBuffer' || type === 'indirectStorageBuffer' ) {
  52668. if ( this.isCustomStruct( node ) ) {
  52669. return name;
  52670. }
  52671. return name + '.value';
  52672. } else {
  52673. return node.groupNode.name + '.' + name;
  52674. }
  52675. }
  52676. return super.getPropertyName( node );
  52677. }
  52678. /**
  52679. * Returns the output struct name.
  52680. *
  52681. * @return {string} The name of the output struct.
  52682. */
  52683. getOutputStructName() {
  52684. return 'output';
  52685. }
  52686. /**
  52687. * Returns the native shader operator name for a given generic name.
  52688. *
  52689. * @param {string} op - The operator name to resolve.
  52690. * @return {?string} The resolved operator name.
  52691. */
  52692. getFunctionOperator( op ) {
  52693. const fnOp = wgslFnOpLib[ op ];
  52694. if ( fnOp !== undefined ) {
  52695. this._include( fnOp );
  52696. return fnOp;
  52697. }
  52698. return null;
  52699. }
  52700. /**
  52701. * Returns the node access for the given node and shader stage.
  52702. *
  52703. * @param {StorageTextureNode|StorageBufferNode} node - The storage node.
  52704. * @param {string} shaderStage - The shader stage.
  52705. * @return {string} The node access.
  52706. */
  52707. getNodeAccess( node, shaderStage ) {
  52708. if ( shaderStage !== 'compute' ) {
  52709. if ( node.isAtomic === true ) {
  52710. warn( 'WebGPURenderer: Atomic operations are only supported in compute shaders.' );
  52711. return NodeAccess.READ_WRITE;
  52712. }
  52713. return NodeAccess.READ_ONLY;
  52714. }
  52715. return node.access;
  52716. }
  52717. /**
  52718. * Returns A WGSL snippet representing the storage access.
  52719. *
  52720. * @param {StorageTextureNode|StorageBufferNode} node - The storage node.
  52721. * @param {string} shaderStage - The shader stage.
  52722. * @return {string} The WGSL snippet representing the storage access.
  52723. */
  52724. getStorageAccess( node, shaderStage ) {
  52725. return accessNames[ this.getNodeAccess( node, shaderStage ) ];
  52726. }
  52727. /**
  52728. * This method is one of the more important ones since it's responsible
  52729. * for generating a matching binding instance for the given uniform node.
  52730. *
  52731. * These bindings are later used in the renderer to create bind groups
  52732. * and layouts.
  52733. *
  52734. * @param {UniformNode} node - The uniform node.
  52735. * @param {string} type - The node data type.
  52736. * @param {string} shaderStage - The shader stage.
  52737. * @param {?string} [name=null] - An optional uniform name.
  52738. * @return {NodeUniform} The node uniform object.
  52739. */
  52740. getUniformFromNode( node, type, shaderStage, name = null ) {
  52741. const uniformNode = super.getUniformFromNode( node, type, shaderStage, name );
  52742. const nodeData = this.getDataFromNode( node, shaderStage, this.globalCache );
  52743. if ( nodeData.uniformGPU === undefined ) {
  52744. let uniformGPU;
  52745. const group = node.groupNode;
  52746. const groupName = group.name;
  52747. const bindings = this.getBindGroupArray( groupName, shaderStage );
  52748. if ( type === 'texture' || type === 'cubeTexture' || type === 'cubeDepthTexture' || type === 'storageTexture' || type === 'texture3D' ) {
  52749. let texture = null;
  52750. const access = this.getNodeAccess( node, shaderStage );
  52751. if ( type === 'texture' || type === 'storageTexture' ) {
  52752. if ( node.value.is3DTexture === true ) {
  52753. texture = new NodeSampledTexture3D( uniformNode.name, uniformNode.node, group, access );
  52754. } else {
  52755. texture = new NodeSampledTexture( uniformNode.name, uniformNode.node, group, access );
  52756. }
  52757. } else if ( type === 'cubeTexture' || type === 'cubeDepthTexture' ) {
  52758. texture = new NodeSampledCubeTexture( uniformNode.name, uniformNode.node, group, access );
  52759. } else if ( type === 'texture3D' ) {
  52760. texture = new NodeSampledTexture3D( uniformNode.name, uniformNode.node, group, access );
  52761. }
  52762. texture.store = node.isStorageTextureNode === true;
  52763. texture.mipLevel = texture.store ? node.mipLevel : 0;
  52764. texture.setVisibility( gpuShaderStageLib[ shaderStage ] );
  52765. if ( this.isUnfilterable( node.value ) === false && texture.store === false ) {
  52766. const sampler = new NodeSampler( `${ uniformNode.name }_sampler`, uniformNode.node, group );
  52767. sampler.setVisibility( gpuShaderStageLib[ shaderStage ] );
  52768. bindings.push( sampler, texture );
  52769. uniformGPU = [ sampler, texture ];
  52770. } else {
  52771. bindings.push( texture );
  52772. uniformGPU = [ texture ];
  52773. }
  52774. } else if ( type === 'buffer' || type === 'storageBuffer' || type === 'indirectStorageBuffer' ) {
  52775. const sharedData = this.getSharedDataFromNode( node );
  52776. let buffer = sharedData.buffer;
  52777. if ( buffer === undefined ) {
  52778. const bufferClass = type === 'buffer' ? NodeUniformBuffer : NodeStorageBuffer;
  52779. buffer = new bufferClass( node, group );
  52780. sharedData.buffer = buffer;
  52781. }
  52782. buffer.setVisibility( buffer.getVisibility() | gpuShaderStageLib[ shaderStage ] );
  52783. bindings.push( buffer );
  52784. uniformGPU = buffer;
  52785. uniformNode.name = name ? name : 'NodeBuffer_' + uniformNode.id;
  52786. } else {
  52787. const uniformsStage = this.uniformGroups[ shaderStage ] || ( this.uniformGroups[ shaderStage ] = {} );
  52788. let uniformsGroup = uniformsStage[ groupName ];
  52789. if ( uniformsGroup === undefined ) {
  52790. uniformsGroup = new NodeUniformsGroup( groupName, group );
  52791. uniformsGroup.setVisibility( gpuShaderStageLib[ shaderStage ] );
  52792. uniformsStage[ groupName ] = uniformsGroup;
  52793. bindings.push( uniformsGroup );
  52794. }
  52795. uniformGPU = this.getNodeUniform( uniformNode, type );
  52796. uniformsGroup.addUniform( uniformGPU );
  52797. }
  52798. nodeData.uniformGPU = uniformGPU;
  52799. }
  52800. return uniformNode;
  52801. }
  52802. /**
  52803. * This method should be used whenever builtins are required in nodes.
  52804. * The internal builtins data structure will make sure builtins are
  52805. * defined in the WGSL source.
  52806. *
  52807. * @param {string} name - The builtin name.
  52808. * @param {string} property - The property name.
  52809. * @param {string} type - The node data type.
  52810. * @param {string} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  52811. * @return {string} The property name.
  52812. */
  52813. getBuiltin( name, property, type, shaderStage = this.shaderStage ) {
  52814. const map = this.builtins[ shaderStage ] || ( this.builtins[ shaderStage ] = new Map() );
  52815. if ( map.has( name ) === false ) {
  52816. map.set( name, {
  52817. name,
  52818. property,
  52819. type
  52820. } );
  52821. }
  52822. return property;
  52823. }
  52824. /**
  52825. * Returns `true` if the given builtin is defined in the given shader stage.
  52826. *
  52827. * @param {string} name - The builtin name.
  52828. * @param {string} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  52829. * @return {boolean} Whether the given builtin is defined in the given shader stage or not.
  52830. */
  52831. hasBuiltin( name, shaderStage = this.shaderStage ) {
  52832. return ( this.builtins[ shaderStage ] !== undefined && this.builtins[ shaderStage ].has( name ) );
  52833. }
  52834. /**
  52835. * Returns the vertex index builtin.
  52836. *
  52837. * @return {string} The vertex index.
  52838. */
  52839. getVertexIndex() {
  52840. if ( this.shaderStage === 'vertex' ) {
  52841. return this.getBuiltin( 'vertex_index', 'vertexIndex', 'u32', 'attribute' );
  52842. }
  52843. return 'vertexIndex';
  52844. }
  52845. /**
  52846. * Builds the given shader node.
  52847. *
  52848. * @param {ShaderNodeInternal} shaderNode - The shader node.
  52849. * @return {string} The WGSL function code.
  52850. */
  52851. buildFunctionCode( shaderNode ) {
  52852. const layout = shaderNode.layout;
  52853. const flowData = this.flowShaderNode( shaderNode );
  52854. const parameters = [];
  52855. for ( const input of layout.inputs ) {
  52856. parameters.push( input.name + ' : ' + this.getType( input.type ) );
  52857. }
  52858. //
  52859. let code = `fn ${ layout.name }( ${ parameters.join( ', ' ) } ) -> ${ this.getType( layout.type ) } {
  52860. ${ flowData.vars }
  52861. ${ flowData.code }
  52862. `;
  52863. if ( flowData.result ) {
  52864. code += `\treturn ${ flowData.result };\n`;
  52865. }
  52866. code += '\n}\n';
  52867. //
  52868. return code;
  52869. }
  52870. /**
  52871. * Contextually returns either the vertex stage instance index builtin
  52872. * or the linearized index of an compute invocation within a grid of workgroups.
  52873. *
  52874. * @return {string} The instance index.
  52875. */
  52876. getInstanceIndex() {
  52877. if ( this.shaderStage === 'vertex' ) {
  52878. return this.getBuiltin( 'instance_index', 'instanceIndex', 'u32', 'attribute' );
  52879. }
  52880. return 'instanceIndex';
  52881. }
  52882. /**
  52883. * Returns a builtin representing the index of a compute invocation within the scope of a workgroup load.
  52884. *
  52885. * @return {string} The invocation local index.
  52886. */
  52887. getInvocationLocalIndex() {
  52888. return this.getBuiltin( 'local_invocation_index', 'invocationLocalIndex', 'u32', 'attribute' );
  52889. }
  52890. /**
  52891. * Returns a builtin representing the size of a subgroup within the current shader.
  52892. *
  52893. * @return {string} The subgroup size.
  52894. */
  52895. getSubgroupSize() {
  52896. this.enableSubGroups();
  52897. return this.getBuiltin( 'subgroup_size', 'subgroupSize', 'u32', 'attribute' );
  52898. }
  52899. /**
  52900. * Returns a builtin representing the index of a compute invocation within the scope of a subgroup.
  52901. *
  52902. * @return {string} The invocation subgroup index.
  52903. */
  52904. getInvocationSubgroupIndex() {
  52905. this.enableSubGroups();
  52906. return this.getBuiltin( 'subgroup_invocation_id', 'invocationSubgroupIndex', 'u32', 'attribute' );
  52907. }
  52908. /**
  52909. * Returns a builtin representing the index of a compute invocation's subgroup within its workgroup.
  52910. *
  52911. * @return {string} The subgroup index.
  52912. */
  52913. getSubgroupIndex() {
  52914. this.enableSubGroups();
  52915. return this.getBuiltin( 'subgroup_id', 'subgroupIndex', 'u32', 'attribute' );
  52916. }
  52917. /**
  52918. * Overwritten as a NOP since this method is intended for the WebGL 2 backend.
  52919. *
  52920. * @return {null} Null.
  52921. */
  52922. getDrawIndex() {
  52923. return null;
  52924. }
  52925. /**
  52926. * Returns the front facing builtin.
  52927. *
  52928. * @return {string} The front facing builtin.
  52929. */
  52930. getFrontFacing() {
  52931. return this.getBuiltin( 'front_facing', 'isFront', 'bool' );
  52932. }
  52933. /**
  52934. * Returns the frag coord builtin.
  52935. *
  52936. * @return {string} The frag coord builtin.
  52937. */
  52938. getFragCoord() {
  52939. return this.getBuiltin( 'position', 'fragCoord', 'vec4<f32>' ) + '.xy';
  52940. }
  52941. /**
  52942. * Returns the frag depth builtin.
  52943. *
  52944. * @return {string} The frag depth builtin.
  52945. */
  52946. getFragDepth() {
  52947. return 'output.' + this.getBuiltin( 'frag_depth', 'depth', 'f32', 'output' );
  52948. }
  52949. /**
  52950. * Returns the clip distances builtin.
  52951. *
  52952. * @return {string} The clip distances builtin.
  52953. */
  52954. getClipDistance() {
  52955. return 'varyings.hw_clip_distances';
  52956. }
  52957. /**
  52958. * Whether to flip texture data along its vertical axis or not.
  52959. *
  52960. * @return {boolean} Returns always `false` in context of WGSL.
  52961. */
  52962. isFlipY() {
  52963. return false;
  52964. }
  52965. /**
  52966. * Enables the given directive for the given shader stage.
  52967. *
  52968. * @param {string} name - The directive name.
  52969. * @param {string} [shaderStage=this.shaderStage] - The shader stage to enable the directive for.
  52970. */
  52971. enableDirective( name, shaderStage = this.shaderStage ) {
  52972. const stage = this.directives[ shaderStage ] || ( this.directives[ shaderStage ] = new Set() );
  52973. stage.add( name );
  52974. }
  52975. /**
  52976. * Returns the directives of the given shader stage as a WGSL string.
  52977. *
  52978. * @param {string} shaderStage - The shader stage.
  52979. * @return {string} A WGSL snippet that enables the directives of the given stage.
  52980. */
  52981. getDirectives( shaderStage ) {
  52982. const snippets = [];
  52983. const directives = this.directives[ shaderStage ];
  52984. if ( directives !== undefined ) {
  52985. for ( const directive of directives ) {
  52986. snippets.push( `enable ${directive};` );
  52987. }
  52988. }
  52989. return snippets.join( '\n' );
  52990. }
  52991. /**
  52992. * Enables the 'subgroups' directive.
  52993. */
  52994. enableSubGroups() {
  52995. this.enableDirective( 'subgroups' );
  52996. }
  52997. /**
  52998. * Enables the 'subgroups-f16' directive.
  52999. */
  53000. enableSubgroupsF16() {
  53001. this.enableDirective( 'subgroups-f16' );
  53002. }
  53003. /**
  53004. * Enables the 'clip_distances' directive.
  53005. */
  53006. enableClipDistances() {
  53007. this.enableDirective( 'clip_distances' );
  53008. }
  53009. /**
  53010. * Enables the 'f16' directive.
  53011. */
  53012. enableShaderF16() {
  53013. this.enableDirective( 'f16' );
  53014. }
  53015. /**
  53016. * Enables the 'dual_source_blending' directive.
  53017. */
  53018. enableDualSourceBlending() {
  53019. this.enableDirective( 'dual_source_blending' );
  53020. }
  53021. /**
  53022. * Enables hardware clipping.
  53023. *
  53024. * @param {string} planeCount - The clipping plane count.
  53025. */
  53026. enableHardwareClipping( planeCount ) {
  53027. this.enableClipDistances();
  53028. this.getBuiltin( 'clip_distances', 'hw_clip_distances', `array<f32, ${ planeCount } >`, 'vertex' );
  53029. }
  53030. /**
  53031. * Returns the builtins of the given shader stage as a WGSL string.
  53032. *
  53033. * @param {string} shaderStage - The shader stage.
  53034. * @return {string} A WGSL snippet that represents the builtins of the given stage.
  53035. */
  53036. getBuiltins( shaderStage ) {
  53037. const snippets = [];
  53038. const builtins = this.builtins[ shaderStage ];
  53039. if ( builtins !== undefined ) {
  53040. for ( const { name, property, type } of builtins.values() ) {
  53041. snippets.push( `@builtin( ${name} ) ${property} : ${type}` );
  53042. }
  53043. }
  53044. return snippets.join( ',\n\t' );
  53045. }
  53046. /**
  53047. * This method should be used when a new scoped buffer is used in context of
  53048. * compute shaders. It adds the array to the internal data structure which is
  53049. * later used to generate the respective WGSL.
  53050. *
  53051. * @param {string} name - The array name.
  53052. * @param {string} scope - The scope.
  53053. * @param {string} bufferType - The buffer type.
  53054. * @param {string} bufferCount - The buffer count.
  53055. * @return {string} The array name.
  53056. */
  53057. getScopedArray( name, scope, bufferType, bufferCount ) {
  53058. if ( this.scopedArrays.has( name ) === false ) {
  53059. this.scopedArrays.set( name, {
  53060. name,
  53061. scope,
  53062. bufferType,
  53063. bufferCount
  53064. } );
  53065. }
  53066. return name;
  53067. }
  53068. /**
  53069. * Returns the scoped arrays of the given shader stage as a WGSL string.
  53070. *
  53071. * @param {string} shaderStage - The shader stage.
  53072. * @return {string|undefined} The WGSL snippet that defines the scoped arrays.
  53073. * Returns `undefined` when used in the vertex or fragment stage.
  53074. */
  53075. getScopedArrays( shaderStage ) {
  53076. if ( shaderStage !== 'compute' ) {
  53077. return;
  53078. }
  53079. const snippets = [];
  53080. for ( const { name, scope, bufferType, bufferCount } of this.scopedArrays.values() ) {
  53081. const type = this.getType( bufferType );
  53082. snippets.push( `var<${scope}> ${name}: array< ${type}, ${bufferCount} >;` );
  53083. }
  53084. return snippets.join( '\n' );
  53085. }
  53086. /**
  53087. * Returns the shader attributes of the given shader stage as a WGSL string.
  53088. *
  53089. * @param {string} shaderStage - The shader stage.
  53090. * @return {string} The WGSL snippet that defines the shader attributes.
  53091. */
  53092. getAttributes( shaderStage ) {
  53093. const snippets = [];
  53094. if ( shaderStage === 'compute' ) {
  53095. this.getBuiltin( 'global_invocation_id', 'globalId', 'vec3<u32>', 'attribute' );
  53096. this.getBuiltin( 'workgroup_id', 'workgroupId', 'vec3<u32>', 'attribute' );
  53097. this.getBuiltin( 'local_invocation_id', 'localId', 'vec3<u32>', 'attribute' );
  53098. this.getBuiltin( 'num_workgroups', 'numWorkgroups', 'vec3<u32>', 'attribute' );
  53099. if ( this.renderer.hasFeature( 'subgroups' ) ) {
  53100. this.enableDirective( 'subgroups', shaderStage );
  53101. this.getBuiltin( 'subgroup_size', 'subgroupSize', 'u32', 'attribute' );
  53102. }
  53103. }
  53104. if ( shaderStage === 'vertex' || shaderStage === 'compute' ) {
  53105. const builtins = this.getBuiltins( 'attribute' );
  53106. if ( builtins ) snippets.push( builtins );
  53107. const attributes = this.getAttributesArray();
  53108. for ( let index = 0, length = attributes.length; index < length; index ++ ) {
  53109. const attribute = attributes[ index ];
  53110. const name = attribute.name;
  53111. const type = this.getType( attribute.type );
  53112. snippets.push( `@location( ${index} ) ${ name } : ${ type }` );
  53113. }
  53114. }
  53115. return snippets.join( ',\n\t' );
  53116. }
  53117. /**
  53118. * Returns the members of the given struct type node as a WGSL string.
  53119. *
  53120. * @param {StructTypeNode} struct - The struct type node.
  53121. * @return {string} The WGSL snippet that defines the struct members.
  53122. */
  53123. getStructMembers( struct ) {
  53124. const snippets = [];
  53125. for ( const member of struct.members ) {
  53126. const prefix = struct.output ? '@location( ' + member.index + ' ) ' : '';
  53127. let type = this.getType( member.type );
  53128. if ( member.atomic ) {
  53129. type = 'atomic< ' + type + ' >';
  53130. }
  53131. snippets.push( `\t${ prefix + member.name } : ${ type }` );
  53132. }
  53133. if ( struct.output ) {
  53134. snippets.push( `\t${ this.getBuiltins( 'output' ) }` );
  53135. }
  53136. return snippets.join( ',\n' );
  53137. }
  53138. /**
  53139. * Returns the structs of the given shader stage as a WGSL string.
  53140. *
  53141. * @param {string} shaderStage - The shader stage.
  53142. * @return {string} The WGSL snippet that defines the structs.
  53143. */
  53144. getStructs( shaderStage ) {
  53145. let result = '';
  53146. const structs = this.structs[ shaderStage ];
  53147. if ( structs.length > 0 ) {
  53148. const snippets = [];
  53149. for ( const struct of structs ) {
  53150. let snippet = `struct ${ struct.name } {\n`;
  53151. snippet += this.getStructMembers( struct );
  53152. snippet += '\n};';
  53153. snippets.push( snippet );
  53154. }
  53155. result = '\n' + snippets.join( '\n\n' ) + '\n';
  53156. }
  53157. return result;
  53158. }
  53159. /**
  53160. * Returns a WGSL string representing a variable.
  53161. *
  53162. * @param {string} type - The variable's type.
  53163. * @param {string} name - The variable's name.
  53164. * @param {?number} [count=null] - The array length.
  53165. * @return {string} The WGSL snippet that defines a variable.
  53166. */
  53167. getVar( type, name, count = null ) {
  53168. let snippet = `var ${ name } : `;
  53169. if ( count !== null ) {
  53170. snippet += this.generateArrayDeclaration( type, count );
  53171. } else {
  53172. snippet += this.getType( type );
  53173. }
  53174. return snippet;
  53175. }
  53176. /**
  53177. * Returns the variables of the given shader stage as a WGSL string.
  53178. *
  53179. * @param {string} shaderStage - The shader stage.
  53180. * @return {string} The WGSL snippet that defines the variables.
  53181. */
  53182. getVars( shaderStage ) {
  53183. const snippets = [];
  53184. const vars = this.vars[ shaderStage ];
  53185. if ( vars !== undefined ) {
  53186. for ( const variable of vars ) {
  53187. snippets.push( `\t${ this.getVar( variable.type, variable.name, variable.count ) };` );
  53188. }
  53189. }
  53190. return `\n${ snippets.join( '\n' ) }\n`;
  53191. }
  53192. /**
  53193. * Returns the varyings of the given shader stage as a WGSL string.
  53194. *
  53195. * @param {string} shaderStage - The shader stage.
  53196. * @return {string} The WGSL snippet that defines the varyings.
  53197. */
  53198. getVaryings( shaderStage ) {
  53199. const snippets = [];
  53200. if ( shaderStage === 'vertex' ) {
  53201. this.getBuiltin( 'position', 'Vertex', 'vec4<f32>', 'vertex' );
  53202. }
  53203. if ( shaderStage === 'vertex' || shaderStage === 'fragment' ) {
  53204. const varyings = this.varyings;
  53205. const vars = this.vars[ shaderStage ];
  53206. for ( let index = 0; index < varyings.length; index ++ ) {
  53207. const varying = varyings[ index ];
  53208. if ( varying.needsInterpolation ) {
  53209. let attributesSnippet = `@location( ${index} )`;
  53210. if ( varying.interpolationType ) {
  53211. const samplingSnippet = varying.interpolationSampling !== null ? `, ${ varying.interpolationSampling } )` : ' )';
  53212. attributesSnippet += ` @interpolate( ${ varying.interpolationType }${ samplingSnippet }`;
  53213. // Otherwise, optimize interpolation when sensible
  53214. } else if ( /^(int|uint|ivec|uvec)/.test( varying.type ) ) {
  53215. attributesSnippet += ` @interpolate( ${ this.renderer.backend.compatibilityMode ? 'flat, either' : 'flat' } )`;
  53216. }
  53217. snippets.push( `${ attributesSnippet } ${ varying.name } : ${ this.getType( varying.type ) }` );
  53218. } else if ( shaderStage === 'vertex' && vars.includes( varying ) === false ) {
  53219. vars.push( varying );
  53220. }
  53221. }
  53222. }
  53223. const builtins = this.getBuiltins( shaderStage );
  53224. if ( builtins ) snippets.push( builtins );
  53225. const code = snippets.join( ',\n\t' );
  53226. return shaderStage === 'vertex' ? this._getWGSLStruct( 'VaryingsStruct', '\t' + code ) : code;
  53227. }
  53228. isCustomStruct( nodeUniform ) {
  53229. const attribute = nodeUniform.value;
  53230. const bufferNode = nodeUniform.node;
  53231. const isAttributeStructType = ( attribute.isBufferAttribute || attribute.isInstancedBufferAttribute ) && bufferNode.structTypeNode !== null;
  53232. const isStructArray =
  53233. ( bufferNode.value && bufferNode.value.array ) &&
  53234. ( typeof bufferNode.value.itemSize === 'number' && bufferNode.value.array.length > bufferNode.value.itemSize );
  53235. return isAttributeStructType && ! isStructArray;
  53236. }
  53237. /**
  53238. * Returns the uniforms of the given shader stage as a WGSL string.
  53239. *
  53240. * @param {string} shaderStage - The shader stage.
  53241. * @return {string} The WGSL snippet that defines the uniforms.
  53242. */
  53243. getUniforms( shaderStage ) {
  53244. const uniforms = this.uniforms[ shaderStage ];
  53245. const bindingSnippets = [];
  53246. const bufferSnippets = [];
  53247. const structSnippets = [];
  53248. const uniformGroups = {};
  53249. for ( const uniform of uniforms ) {
  53250. const groupName = uniform.groupNode.name;
  53251. const uniformIndexes = this.bindingsIndexes[ groupName ];
  53252. if ( uniform.type === 'texture' || uniform.type === 'cubeTexture' || uniform.type === 'cubeDepthTexture' || uniform.type === 'storageTexture' || uniform.type === 'texture3D' ) {
  53253. const texture = uniform.node.value;
  53254. if ( this.isUnfilterable( texture ) === false && uniform.node.isStorageTextureNode !== true ) {
  53255. if ( this.isSampleCompare( texture ) ) {
  53256. bindingSnippets.push( `@binding( ${ uniformIndexes.binding ++ } ) @group( ${ uniformIndexes.group } ) var ${ uniform.name }_sampler : sampler_comparison;` );
  53257. } else {
  53258. bindingSnippets.push( `@binding( ${ uniformIndexes.binding ++ } ) @group( ${ uniformIndexes.group } ) var ${ uniform.name }_sampler : sampler;` );
  53259. }
  53260. }
  53261. let textureType;
  53262. let multisampled = '';
  53263. const { primarySamples } = this.renderer.backend.utils.getTextureSampleData( texture );
  53264. if ( primarySamples > 1 ) {
  53265. multisampled = '_multisampled';
  53266. }
  53267. if ( texture.isCubeTexture === true && texture.isDepthTexture === true ) {
  53268. textureType = 'texture_depth_cube';
  53269. } else if ( texture.isCubeTexture === true ) {
  53270. textureType = 'texture_cube<f32>';
  53271. } else if ( texture.isDepthTexture === true ) {
  53272. if ( this.renderer.backend.compatibilityMode && texture.compareFunction === null ) {
  53273. textureType = `texture${ multisampled }_2d<f32>`;
  53274. } else {
  53275. textureType = `texture_depth${ multisampled }_2d${ texture.isArrayTexture === true ? '_array' : '' }`;
  53276. }
  53277. } else if ( uniform.node.isStorageTextureNode === true ) {
  53278. const format = getFormat( texture );
  53279. const access = this.getStorageAccess( uniform.node, shaderStage );
  53280. const is3D = uniform.node.value.is3DTexture;
  53281. const isArrayTexture = uniform.node.value.isArrayTexture;
  53282. const dimension = is3D ? '3d' : `2d${ isArrayTexture ? '_array' : '' }`;
  53283. textureType = `texture_storage_${ dimension }<${ format }, ${ access }>`;
  53284. } else if ( texture.isArrayTexture === true || texture.isDataArrayTexture === true || texture.isCompressedArrayTexture === true ) {
  53285. textureType = 'texture_2d_array<f32>';
  53286. } else if ( texture.is3DTexture === true || texture.isData3DTexture === true ) {
  53287. textureType = 'texture_3d<f32>';
  53288. } else {
  53289. const componentPrefix = this.getComponentTypeFromTexture( texture ).charAt( 0 );
  53290. textureType = `texture${ multisampled }_2d<${ componentPrefix }32>`;
  53291. }
  53292. bindingSnippets.push( `@binding( ${ uniformIndexes.binding ++ } ) @group( ${ uniformIndexes.group } ) var ${ uniform.name } : ${ textureType };` );
  53293. } else if ( uniform.type === 'buffer' || uniform.type === 'storageBuffer' || uniform.type === 'indirectStorageBuffer' ) {
  53294. const bufferNode = uniform.node;
  53295. const bufferType = this.getType( bufferNode.getNodeType( this ) );
  53296. const bufferCount = bufferNode.bufferCount;
  53297. const bufferCountSnippet = bufferCount > 0 && uniform.type === 'buffer' ? ', ' + bufferCount : '';
  53298. const bufferAccessMode = bufferNode.isStorageBufferNode ? `storage, ${ this.getStorageAccess( bufferNode, shaderStage ) }` : 'uniform';
  53299. if ( this.isCustomStruct( uniform ) ) {
  53300. bufferSnippets.push( `@binding( ${ uniformIndexes.binding ++ } ) @group( ${ uniformIndexes.group } ) var<${ bufferAccessMode }> ${ uniform.name } : ${ bufferType };` );
  53301. } else {
  53302. const bufferTypeSnippet = bufferNode.isAtomic ? `atomic<${ bufferType }>` : `${ bufferType }`;
  53303. const bufferSnippet = `\tvalue : array< ${ bufferTypeSnippet }${ bufferCountSnippet } >`;
  53304. bufferSnippets.push( this._getWGSLStructBinding( uniform.name, bufferSnippet, bufferAccessMode, uniformIndexes.binding ++, uniformIndexes.group ) );
  53305. }
  53306. } else {
  53307. const vectorType = this.getType( this.getVectorType( uniform.type ) );
  53308. const groupName = uniform.groupNode.name;
  53309. const group = uniformGroups[ groupName ] || ( uniformGroups[ groupName ] = {
  53310. index: uniformIndexes.binding ++,
  53311. id: uniformIndexes.group,
  53312. snippets: []
  53313. } );
  53314. group.snippets.push( `\t${ uniform.name } : ${ vectorType }` );
  53315. }
  53316. }
  53317. for ( const name in uniformGroups ) {
  53318. const group = uniformGroups[ name ];
  53319. structSnippets.push( this._getWGSLStructBinding( name, group.snippets.join( ',\n' ), 'uniform', group.index, group.id ) );
  53320. }
  53321. let code = bindingSnippets.join( '\n' );
  53322. code += bufferSnippets.join( '\n' );
  53323. code += structSnippets.join( '\n' );
  53324. return code;
  53325. }
  53326. /**
  53327. * Controls the code build of the shader stages.
  53328. */
  53329. buildCode() {
  53330. const shadersData = this.material !== null ? { fragment: {}, vertex: {} } : { compute: {} };
  53331. this.sortBindingGroups();
  53332. for ( const shaderStage in shadersData ) {
  53333. this.shaderStage = shaderStage;
  53334. const stageData = shadersData[ shaderStage ];
  53335. stageData.uniforms = this.getUniforms( shaderStage );
  53336. stageData.attributes = this.getAttributes( shaderStage );
  53337. stageData.varyings = this.getVaryings( shaderStage );
  53338. stageData.structs = this.getStructs( shaderStage );
  53339. stageData.vars = this.getVars( shaderStage );
  53340. stageData.codes = this.getCodes( shaderStage );
  53341. stageData.directives = this.getDirectives( shaderStage );
  53342. stageData.scopedArrays = this.getScopedArrays( shaderStage );
  53343. //
  53344. let flow = '// code\n\n';
  53345. flow += this.flowCode[ shaderStage ];
  53346. const flowNodes = this.flowNodes[ shaderStage ];
  53347. const mainNode = flowNodes[ flowNodes.length - 1 ];
  53348. const outputNode = mainNode.outputNode;
  53349. const isOutputStruct = ( outputNode !== undefined && outputNode.isOutputStructNode === true );
  53350. for ( const node of flowNodes ) {
  53351. const flowSlotData = this.getFlowData( node/*, shaderStage*/ );
  53352. const slotName = node.name;
  53353. if ( slotName ) {
  53354. if ( flow.length > 0 ) flow += '\n';
  53355. flow += `\t// flow -> ${ slotName }\n`;
  53356. }
  53357. flow += `${ flowSlotData.code }\n\t`;
  53358. if ( node === mainNode && shaderStage !== 'compute' ) {
  53359. flow += '// result\n\n\t';
  53360. if ( shaderStage === 'vertex' ) {
  53361. flow += `varyings.Vertex = ${ flowSlotData.result };`;
  53362. } else if ( shaderStage === 'fragment' ) {
  53363. if ( isOutputStruct ) {
  53364. stageData.returnType = outputNode.getNodeType( this );
  53365. stageData.structs += 'var<private> output : ' + stageData.returnType + ';';
  53366. flow += `return ${ flowSlotData.result };`;
  53367. } else {
  53368. let structSnippet = '\t@location(0) color: vec4<f32>';
  53369. const builtins = this.getBuiltins( 'output' );
  53370. if ( builtins ) structSnippet += ',\n\t' + builtins;
  53371. stageData.returnType = 'OutputStruct';
  53372. stageData.structs += this._getWGSLStruct( 'OutputStruct', structSnippet );
  53373. stageData.structs += '\nvar<private> output : OutputStruct;';
  53374. flow += `output.color = ${ flowSlotData.result };\n\n\treturn output;`;
  53375. }
  53376. }
  53377. }
  53378. }
  53379. stageData.flow = flow;
  53380. }
  53381. this.shaderStage = null;
  53382. if ( this.material !== null ) {
  53383. this.vertexShader = this._getWGSLVertexCode( shadersData.vertex );
  53384. this.fragmentShader = this._getWGSLFragmentCode( shadersData.fragment );
  53385. } else {
  53386. // Early strictly validated in computeNode
  53387. const workgroupSize = this.object.workgroupSize;
  53388. this.computeShader = this._getWGSLComputeCode( shadersData.compute, workgroupSize );
  53389. }
  53390. }
  53391. /**
  53392. * Returns the native shader method name for a given generic name.
  53393. *
  53394. * @param {string} method - The method name to resolve.
  53395. * @param {?string} [output=null] - An optional output.
  53396. * @return {string} The resolved WGSL method name.
  53397. */
  53398. getMethod( method, output = null ) {
  53399. let wgslMethod;
  53400. if ( output !== null ) {
  53401. wgslMethod = this._getWGSLMethod( method + '_' + output );
  53402. }
  53403. if ( wgslMethod === undefined ) {
  53404. wgslMethod = this._getWGSLMethod( method );
  53405. }
  53406. return wgslMethod || method;
  53407. }
  53408. /**
  53409. * Returns the bitcast method name for a given input and outputType.
  53410. *
  53411. * @param {string} type - The output type to bitcast to.
  53412. * @return {string} The resolved WGSL bitcast invocation.
  53413. */
  53414. getBitcastMethod( type ) {
  53415. const dataType = this.getType( type );
  53416. return `bitcast<${ dataType }>`;
  53417. }
  53418. /**
  53419. * Returns the float packing method name for a given numeric encoding.
  53420. *
  53421. * @param {string} encoding - The numeric encoding that describes how the float values are mapped to the integer range.
  53422. * @returns {string} The resolve WGSL float packing method name.
  53423. */
  53424. getFloatPackingMethod( encoding ) {
  53425. return this.getMethod( `floatpack_${ encoding }_2x16` );
  53426. }
  53427. /**
  53428. * Returns the float unpacking method name for a given numeric encoding.
  53429. *
  53430. * @param {string} encoding - The numeric encoding that describes how the integer values are mapped to the float range.
  53431. * @returns {string} The resolve WGSL float unpacking method name.
  53432. */
  53433. getFloatUnpackingMethod( encoding ) {
  53434. return this.getMethod( `floatunpack_${ encoding }_2x16` );
  53435. }
  53436. /**
  53437. * Returns the native snippet for a ternary operation.
  53438. *
  53439. * @param {string} condSnippet - The condition determining which expression gets resolved.
  53440. * @param {string} ifSnippet - The expression to resolve to if the condition is true.
  53441. * @param {string} elseSnippet - The expression to resolve to if the condition is false.
  53442. * @return {string} The resolved method name.
  53443. */
  53444. getTernary( condSnippet, ifSnippet, elseSnippet ) {
  53445. return `select( ${elseSnippet}, ${ifSnippet}, ${condSnippet} )`;
  53446. }
  53447. /**
  53448. * Returns the WGSL type of the given node data type.
  53449. *
  53450. * @param {string} type - The node data type.
  53451. * @return {string} The WGSL type.
  53452. */
  53453. getType( type ) {
  53454. return wgslTypeLib[ type ] || type;
  53455. }
  53456. /**
  53457. * Whether the requested feature is available or not.
  53458. *
  53459. * @param {string} name - The requested feature.
  53460. * @return {boolean} Whether the requested feature is supported or not.
  53461. */
  53462. isAvailable( name ) {
  53463. let result = supports[ name ];
  53464. if ( result === undefined ) {
  53465. if ( name === 'float32Filterable' ) {
  53466. result = this.renderer.hasFeature( 'float32-filterable' );
  53467. } else if ( name === 'clipDistance' ) {
  53468. result = this.renderer.hasFeature( 'clip-distances' );
  53469. }
  53470. supports[ name ] = result;
  53471. }
  53472. return result;
  53473. }
  53474. /**
  53475. * Returns the native shader method name for a given generic name.
  53476. *
  53477. * @private
  53478. * @param {string} method - The method name to resolve.
  53479. * @return {string} The resolved WGSL method name.
  53480. */
  53481. _getWGSLMethod( method ) {
  53482. if ( wgslPolyfill[ method ] !== undefined ) {
  53483. this._include( method );
  53484. }
  53485. return wgslMethods[ method ];
  53486. }
  53487. /**
  53488. * Includes the given method name into the current
  53489. * function node.
  53490. *
  53491. * @private
  53492. * @param {string} name - The method name to include.
  53493. * @return {CodeNode} The respective code node.
  53494. */
  53495. _include( name ) {
  53496. const codeNode = wgslPolyfill[ name ];
  53497. codeNode.build( this );
  53498. this.addInclude( codeNode );
  53499. return codeNode;
  53500. }
  53501. /**
  53502. * Returns a WGSL vertex shader based on the given shader data.
  53503. *
  53504. * @private
  53505. * @param {Object} shaderData - The shader data.
  53506. * @return {string} The vertex shader.
  53507. */
  53508. _getWGSLVertexCode( shaderData ) {
  53509. return `${ this.getSignature() }
  53510. // directives
  53511. ${shaderData.directives}
  53512. // structs
  53513. ${shaderData.structs}
  53514. // uniforms
  53515. ${shaderData.uniforms}
  53516. // varyings
  53517. ${shaderData.varyings}
  53518. var<private> varyings : VaryingsStruct;
  53519. // codes
  53520. ${shaderData.codes}
  53521. @vertex
  53522. fn main( ${shaderData.attributes} ) -> VaryingsStruct {
  53523. // vars
  53524. ${shaderData.vars}
  53525. // flow
  53526. ${shaderData.flow}
  53527. return varyings;
  53528. }
  53529. `;
  53530. }
  53531. /**
  53532. * Returns a WGSL fragment shader based on the given shader data.
  53533. *
  53534. * @private
  53535. * @param {Object} shaderData - The shader data.
  53536. * @return {string} The vertex shader.
  53537. */
  53538. _getWGSLFragmentCode( shaderData ) {
  53539. return `${ this.getSignature() }
  53540. // global
  53541. ${ diagnostics }
  53542. // structs
  53543. ${shaderData.structs}
  53544. // uniforms
  53545. ${shaderData.uniforms}
  53546. // codes
  53547. ${shaderData.codes}
  53548. @fragment
  53549. fn main( ${shaderData.varyings} ) -> ${shaderData.returnType} {
  53550. // vars
  53551. ${shaderData.vars}
  53552. // flow
  53553. ${shaderData.flow}
  53554. }
  53555. `;
  53556. }
  53557. /**
  53558. * Returns a WGSL compute shader based on the given shader data.
  53559. *
  53560. * @private
  53561. * @param {Object} shaderData - The shader data.
  53562. * @param {string} workgroupSize - The workgroup size.
  53563. * @return {string} The vertex shader.
  53564. */
  53565. _getWGSLComputeCode( shaderData, workgroupSize ) {
  53566. const [ workgroupSizeX, workgroupSizeY, workgroupSizeZ ] = workgroupSize;
  53567. return `${ this.getSignature() }
  53568. // directives
  53569. ${ shaderData.directives }
  53570. // system
  53571. var<private> instanceIndex : u32;
  53572. // locals
  53573. ${ shaderData.scopedArrays }
  53574. // structs
  53575. ${ shaderData.structs }
  53576. // uniforms
  53577. ${ shaderData.uniforms }
  53578. // codes
  53579. ${ shaderData.codes }
  53580. @compute @workgroup_size( ${ workgroupSizeX }, ${ workgroupSizeY }, ${ workgroupSizeZ } )
  53581. fn main( ${ shaderData.attributes } ) {
  53582. // system
  53583. instanceIndex = globalId.x
  53584. + globalId.y * ( ${ workgroupSizeX } * numWorkgroups.x )
  53585. + globalId.z * ( ${ workgroupSizeX } * numWorkgroups.x ) * ( ${ workgroupSizeY } * numWorkgroups.y );
  53586. // vars
  53587. ${ shaderData.vars }
  53588. // flow
  53589. ${ shaderData.flow }
  53590. }
  53591. `;
  53592. }
  53593. /**
  53594. * Returns a WGSL struct based on the given name and variables.
  53595. *
  53596. * @private
  53597. * @param {string} name - The struct name.
  53598. * @param {string} vars - The struct variables.
  53599. * @return {string} The WGSL snippet representing a struct.
  53600. */
  53601. _getWGSLStruct( name, vars ) {
  53602. return `
  53603. struct ${name} {
  53604. ${vars}
  53605. };`;
  53606. }
  53607. /**
  53608. * Returns a WGSL struct binding.
  53609. *
  53610. * @private
  53611. * @param {string} name - The struct name.
  53612. * @param {string} vars - The struct variables.
  53613. * @param {string} access - The access.
  53614. * @param {number} [binding=0] - The binding index.
  53615. * @param {number} [group=0] - The group index.
  53616. * @return {string} The WGSL snippet representing a struct binding.
  53617. */
  53618. _getWGSLStructBinding( name, vars, access, binding = 0, group = 0 ) {
  53619. const structName = name + 'Struct';
  53620. const structSnippet = this._getWGSLStruct( structName, vars );
  53621. return `${structSnippet}
  53622. @binding( ${ binding } ) @group( ${ group } )
  53623. var<${access}> ${ name } : ${ structName };`;
  53624. }
  53625. }
  53626. /**
  53627. * A WebGPU backend utility module with common helpers.
  53628. *
  53629. * @private
  53630. */
  53631. class WebGPUUtils {
  53632. /**
  53633. * Constructs a new utility object.
  53634. *
  53635. * @param {WebGPUBackend} backend - The WebGPU backend.
  53636. */
  53637. constructor( backend ) {
  53638. /**
  53639. * A reference to the WebGPU backend.
  53640. *
  53641. * @type {WebGPUBackend}
  53642. */
  53643. this.backend = backend;
  53644. }
  53645. /**
  53646. * Returns the depth/stencil GPU format for the given render context.
  53647. *
  53648. * @param {RenderContext} renderContext - The render context.
  53649. * @return {string} The depth/stencil GPU texture format.
  53650. */
  53651. getCurrentDepthStencilFormat( renderContext ) {
  53652. let format;
  53653. if ( renderContext.depthTexture !== null ) {
  53654. format = this.getTextureFormatGPU( renderContext.depthTexture );
  53655. } else if ( renderContext.depth && renderContext.stencil ) {
  53656. format = GPUTextureFormat.Depth24PlusStencil8;
  53657. } else if ( renderContext.depth ) {
  53658. format = GPUTextureFormat.Depth24Plus;
  53659. }
  53660. return format;
  53661. }
  53662. /**
  53663. * Returns the GPU format for the given texture.
  53664. *
  53665. * @param {Texture} texture - The texture.
  53666. * @return {string} The GPU texture format.
  53667. */
  53668. getTextureFormatGPU( texture ) {
  53669. return this.backend.get( texture ).format;
  53670. }
  53671. /**
  53672. * Returns an object that defines the multi-sampling state of the given texture.
  53673. *
  53674. * @param {Texture} texture - The texture.
  53675. * @return {Object} The multi-sampling state.
  53676. */
  53677. getTextureSampleData( texture ) {
  53678. let samples;
  53679. if ( texture.isFramebufferTexture ) {
  53680. samples = 1;
  53681. } else if ( texture.isDepthTexture && ! texture.renderTarget ) {
  53682. const renderer = this.backend.renderer;
  53683. const renderTarget = renderer.getRenderTarget();
  53684. samples = renderTarget ? renderTarget.samples : renderer.currentSamples;
  53685. } else if ( texture.renderTarget ) {
  53686. samples = texture.renderTarget.samples;
  53687. }
  53688. samples = samples || 1;
  53689. const isMSAA = samples > 1 && texture.renderTarget !== null && ( texture.isDepthTexture !== true && texture.isFramebufferTexture !== true );
  53690. const primarySamples = isMSAA ? 1 : samples;
  53691. return { samples, primarySamples, isMSAA };
  53692. }
  53693. /**
  53694. * Returns the default color attachment's GPU format of the current render context.
  53695. *
  53696. * @param {RenderContext} renderContext - The render context.
  53697. * @return {string} The GPU texture format of the default color attachment.
  53698. */
  53699. getCurrentColorFormat( renderContext ) {
  53700. let format;
  53701. if ( renderContext.textures !== null ) {
  53702. format = this.getTextureFormatGPU( renderContext.textures[ 0 ] );
  53703. } else {
  53704. format = this.getPreferredCanvasFormat(); // default context format
  53705. }
  53706. return format;
  53707. }
  53708. /**
  53709. * Returns the GPU formats of all color attachments of the current render context.
  53710. *
  53711. * @param {RenderContext} renderContext - The render context.
  53712. * @return {Array<string>} The GPU texture formats of all color attachments.
  53713. */
  53714. getCurrentColorFormats( renderContext ) {
  53715. if ( renderContext.textures !== null ) {
  53716. return renderContext.textures.map( t => this.getTextureFormatGPU( t ) );
  53717. } else {
  53718. return [ this.getPreferredCanvasFormat() ]; // default context format
  53719. }
  53720. }
  53721. /**
  53722. * Returns the output color space of the current render context.
  53723. *
  53724. * @param {RenderContext} renderContext - The render context.
  53725. * @return {string} The output color space.
  53726. */
  53727. getCurrentColorSpace( renderContext ) {
  53728. if ( renderContext.textures !== null ) {
  53729. return renderContext.textures[ 0 ].colorSpace;
  53730. }
  53731. return this.backend.renderer.outputColorSpace;
  53732. }
  53733. /**
  53734. * Returns GPU primitive topology for the given object and material.
  53735. *
  53736. * @param {Object3D} object - The 3D object.
  53737. * @param {Material} material - The material.
  53738. * @return {string} The GPU primitive topology.
  53739. */
  53740. getPrimitiveTopology( object, material ) {
  53741. if ( object.isPoints ) return GPUPrimitiveTopology.PointList;
  53742. else if ( object.isLineSegments || ( object.isMesh && material.wireframe === true ) ) return GPUPrimitiveTopology.LineList;
  53743. else if ( object.isLine ) return GPUPrimitiveTopology.LineStrip;
  53744. else if ( object.isMesh ) return GPUPrimitiveTopology.TriangleList;
  53745. }
  53746. /**
  53747. * Returns a modified sample count from the given sample count value.
  53748. *
  53749. * That is required since WebGPU only supports either 1 or 4.
  53750. *
  53751. * @param {number} sampleCount - The input sample count.
  53752. * @return {number} The (potentially updated) output sample count.
  53753. */
  53754. getSampleCount( sampleCount ) {
  53755. return sampleCount >= 4 ? 4 : 1;
  53756. }
  53757. /**
  53758. * Returns the sample count of the given render context.
  53759. *
  53760. * @param {RenderContext} renderContext - The render context.
  53761. * @return {number} The sample count.
  53762. */
  53763. getSampleCountRenderContext( renderContext ) {
  53764. if ( renderContext.textures !== null ) {
  53765. return this.getSampleCount( renderContext.sampleCount );
  53766. }
  53767. return this.getSampleCount( this.backend.renderer.currentSamples );
  53768. }
  53769. /**
  53770. * Returns the preferred canvas format.
  53771. *
  53772. * There is a separate method for this so it's possible to
  53773. * honor edge cases for specific devices.
  53774. *
  53775. * @return {string} The GPU texture format of the canvas.
  53776. */
  53777. getPreferredCanvasFormat() {
  53778. const parameters = this.backend.parameters;
  53779. const bufferType = parameters.outputType;
  53780. if ( bufferType === undefined ) {
  53781. return navigator.gpu.getPreferredCanvasFormat();
  53782. } else if ( bufferType === UnsignedByteType ) {
  53783. return GPUTextureFormat.BGRA8Unorm;
  53784. } else if ( bufferType === HalfFloatType ) {
  53785. return GPUTextureFormat.RGBA16Float;
  53786. } else {
  53787. throw new Error( 'Unsupported output buffer type.' );
  53788. }
  53789. }
  53790. }
  53791. const typedArraysToVertexFormatPrefix = new Map( [
  53792. [ Int8Array, [ 'sint8', 'snorm8' ]],
  53793. [ Uint8Array, [ 'uint8', 'unorm8' ]],
  53794. [ Int16Array, [ 'sint16', 'snorm16' ]],
  53795. [ Uint16Array, [ 'uint16', 'unorm16' ]],
  53796. [ Int32Array, [ 'sint32', 'snorm32' ]],
  53797. [ Uint32Array, [ 'uint32', 'unorm32' ]],
  53798. [ Float32Array, [ 'float32', ]],
  53799. ] );
  53800. if ( typeof Float16Array !== 'undefined' ) {
  53801. typedArraysToVertexFormatPrefix.set( Float16Array, [ 'float16' ] );
  53802. }
  53803. const typedAttributeToVertexFormatPrefix = new Map( [
  53804. [ Float16BufferAttribute, [ 'float16', ]],
  53805. ] );
  53806. const typeArraysToVertexFormatPrefixForItemSize1 = new Map( [
  53807. [ Int32Array, 'sint32' ],
  53808. [ Int16Array, 'sint32' ], // patch for INT16
  53809. [ Uint32Array, 'uint32' ],
  53810. [ Uint16Array, 'uint32' ], // patch for UINT16
  53811. [ Float32Array, 'float32' ]
  53812. ] );
  53813. /**
  53814. * A WebGPU backend utility module for managing shader attributes.
  53815. *
  53816. * @private
  53817. */
  53818. class WebGPUAttributeUtils {
  53819. /**
  53820. * Constructs a new utility object.
  53821. *
  53822. * @param {WebGPUBackend} backend - The WebGPU backend.
  53823. */
  53824. constructor( backend ) {
  53825. /**
  53826. * A reference to the WebGPU backend.
  53827. *
  53828. * @type {WebGPUBackend}
  53829. */
  53830. this.backend = backend;
  53831. }
  53832. /**
  53833. * Creates the GPU buffer for the given buffer attribute.
  53834. *
  53835. * @param {BufferAttribute} attribute - The buffer attribute.
  53836. * @param {GPUBufferUsage} usage - A flag that indicates how the buffer may be used after its creation.
  53837. */
  53838. createAttribute( attribute, usage ) {
  53839. const bufferAttribute = this._getBufferAttribute( attribute );
  53840. const backend = this.backend;
  53841. const bufferData = backend.get( bufferAttribute );
  53842. let buffer = bufferData.buffer;
  53843. if ( buffer === undefined ) {
  53844. const device = backend.device;
  53845. let array = bufferAttribute.array;
  53846. // patch for INT16 and UINT16
  53847. if ( attribute.normalized === false ) {
  53848. if ( array.constructor === Int16Array || array.constructor === Int8Array ) {
  53849. array = new Int32Array( array );
  53850. } else if ( array.constructor === Uint16Array || array.constructor === Uint8Array ) {
  53851. array = new Uint32Array( array );
  53852. if ( usage & GPUBufferUsage.INDEX ) {
  53853. for ( let i = 0; i < array.length; i ++ ) {
  53854. if ( array[ i ] === 0xffff ) array[ i ] = 0xffffffff; // use correct primitive restart index
  53855. }
  53856. }
  53857. }
  53858. }
  53859. bufferAttribute.array = array;
  53860. if ( ( bufferAttribute.isStorageBufferAttribute || bufferAttribute.isStorageInstancedBufferAttribute ) && bufferAttribute.itemSize === 3 ) {
  53861. array = new array.constructor( bufferAttribute.count * 4 );
  53862. for ( let i = 0; i < bufferAttribute.count; i ++ ) {
  53863. array.set( bufferAttribute.array.subarray( i * 3, i * 3 + 3 ), i * 4 );
  53864. }
  53865. // Update BufferAttribute
  53866. bufferAttribute.itemSize = 4;
  53867. bufferAttribute.array = array;
  53868. bufferData._force3to4BytesAlignment = true;
  53869. }
  53870. // ensure 4 byte alignment
  53871. const byteLength = array.byteLength;
  53872. const size = byteLength + ( ( 4 - ( byteLength % 4 ) ) % 4 );
  53873. buffer = device.createBuffer( {
  53874. label: bufferAttribute.name,
  53875. size: size,
  53876. usage: usage,
  53877. mappedAtCreation: true
  53878. } );
  53879. new array.constructor( buffer.getMappedRange() ).set( array );
  53880. buffer.unmap();
  53881. bufferData.buffer = buffer;
  53882. }
  53883. }
  53884. /**
  53885. * Updates the GPU buffer of the given buffer attribute.
  53886. *
  53887. * @param {BufferAttribute} attribute - The buffer attribute.
  53888. */
  53889. updateAttribute( attribute ) {
  53890. const bufferAttribute = this._getBufferAttribute( attribute );
  53891. const backend = this.backend;
  53892. const device = backend.device;
  53893. const bufferData = backend.get( bufferAttribute );
  53894. const buffer = backend.get( bufferAttribute ).buffer;
  53895. let array = bufferAttribute.array;
  53896. // if storage buffer ensure 4 byte alignment
  53897. if ( bufferData._force3to4BytesAlignment === true ) {
  53898. array = new array.constructor( bufferAttribute.count * 4 );
  53899. for ( let i = 0; i < bufferAttribute.count; i ++ ) {
  53900. array.set( bufferAttribute.array.subarray( i * 3, i * 3 + 3 ), i * 4 );
  53901. }
  53902. bufferAttribute.array = array;
  53903. }
  53904. const updateRanges = bufferAttribute.updateRanges;
  53905. if ( updateRanges.length === 0 ) {
  53906. // Not using update ranges
  53907. device.queue.writeBuffer(
  53908. buffer,
  53909. 0,
  53910. array,
  53911. 0
  53912. );
  53913. } else {
  53914. const isTyped = isTypedArray( array );
  53915. const byteOffsetFactor = isTyped ? 1 : array.BYTES_PER_ELEMENT;
  53916. for ( let i = 0, l = updateRanges.length; i < l; i ++ ) {
  53917. const range = updateRanges[ i ];
  53918. let dataOffset, size;
  53919. if ( bufferData._force3to4BytesAlignment === true ) {
  53920. const vertexStart = Math.floor( range.start / 3 );
  53921. const vertexCount = Math.ceil( range.count / 3 );
  53922. dataOffset = vertexStart * 4 * byteOffsetFactor;
  53923. size = vertexCount * 4 * byteOffsetFactor;
  53924. } else {
  53925. dataOffset = range.start * byteOffsetFactor;
  53926. size = range.count * byteOffsetFactor;
  53927. }
  53928. const bufferOffset = dataOffset * ( isTyped ? array.BYTES_PER_ELEMENT : 1 ); // bufferOffset is always in bytes
  53929. device.queue.writeBuffer(
  53930. buffer,
  53931. bufferOffset,
  53932. array,
  53933. dataOffset,
  53934. size
  53935. );
  53936. }
  53937. bufferAttribute.clearUpdateRanges();
  53938. }
  53939. }
  53940. /**
  53941. * This method creates the vertex buffer layout data which are
  53942. * require when creating a render pipeline for the given render object.
  53943. *
  53944. * @param {RenderObject} renderObject - The render object.
  53945. * @return {Array<Object>} An array holding objects which describe the vertex buffer layout.
  53946. */
  53947. createShaderVertexBuffers( renderObject ) {
  53948. const attributes = renderObject.getAttributes();
  53949. const vertexBuffers = new Map();
  53950. for ( let slot = 0; slot < attributes.length; slot ++ ) {
  53951. const geometryAttribute = attributes[ slot ];
  53952. const bytesPerElement = geometryAttribute.array.BYTES_PER_ELEMENT;
  53953. const bufferAttribute = this._getBufferAttribute( geometryAttribute );
  53954. let vertexBufferLayout = vertexBuffers.get( bufferAttribute );
  53955. if ( vertexBufferLayout === undefined ) {
  53956. let arrayStride, stepMode;
  53957. if ( geometryAttribute.isInterleavedBufferAttribute === true ) {
  53958. arrayStride = geometryAttribute.data.stride * bytesPerElement;
  53959. stepMode = geometryAttribute.data.isInstancedInterleavedBuffer ? GPUInputStepMode.Instance : GPUInputStepMode.Vertex;
  53960. } else {
  53961. arrayStride = geometryAttribute.itemSize * bytesPerElement;
  53962. stepMode = geometryAttribute.isInstancedBufferAttribute ? GPUInputStepMode.Instance : GPUInputStepMode.Vertex;
  53963. }
  53964. // patch for INT16 and UINT16
  53965. if ( geometryAttribute.normalized === false && ( geometryAttribute.array.constructor === Int16Array || geometryAttribute.array.constructor === Uint16Array ) ) {
  53966. arrayStride = 4;
  53967. }
  53968. vertexBufferLayout = {
  53969. arrayStride,
  53970. attributes: [],
  53971. stepMode
  53972. };
  53973. vertexBuffers.set( bufferAttribute, vertexBufferLayout );
  53974. }
  53975. const format = this._getVertexFormat( geometryAttribute );
  53976. const offset = ( geometryAttribute.isInterleavedBufferAttribute === true ) ? geometryAttribute.offset * bytesPerElement : 0;
  53977. vertexBufferLayout.attributes.push( {
  53978. shaderLocation: slot,
  53979. offset,
  53980. format
  53981. } );
  53982. }
  53983. return Array.from( vertexBuffers.values() );
  53984. }
  53985. /**
  53986. * Destroys the GPU buffer of the given buffer attribute.
  53987. *
  53988. * @param {BufferAttribute} attribute - The buffer attribute.
  53989. */
  53990. destroyAttribute( attribute ) {
  53991. const backend = this.backend;
  53992. const data = backend.get( this._getBufferAttribute( attribute ) );
  53993. data.buffer.destroy();
  53994. backend.delete( attribute );
  53995. }
  53996. /**
  53997. * This method performs a readback operation by moving buffer data from
  53998. * a storage buffer attribute from the GPU to the CPU.
  53999. *
  54000. * @async
  54001. * @param {StorageBufferAttribute} attribute - The storage buffer attribute.
  54002. * @return {Promise<ArrayBuffer>} A promise that resolves with the buffer data when the data are ready.
  54003. */
  54004. async getArrayBufferAsync( attribute ) {
  54005. const backend = this.backend;
  54006. const device = backend.device;
  54007. const data = backend.get( this._getBufferAttribute( attribute ) );
  54008. const bufferGPU = data.buffer;
  54009. const size = bufferGPU.size;
  54010. const readBufferGPU = device.createBuffer( {
  54011. label: `${ attribute.name }_readback`,
  54012. size,
  54013. usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ
  54014. } );
  54015. const cmdEncoder = device.createCommandEncoder( {
  54016. label: `readback_encoder_${ attribute.name }`
  54017. } );
  54018. cmdEncoder.copyBufferToBuffer(
  54019. bufferGPU,
  54020. 0,
  54021. readBufferGPU,
  54022. 0,
  54023. size
  54024. );
  54025. const gpuCommands = cmdEncoder.finish();
  54026. device.queue.submit( [ gpuCommands ] );
  54027. await readBufferGPU.mapAsync( GPUMapMode.READ );
  54028. const arrayBuffer = readBufferGPU.getMappedRange();
  54029. const dstBuffer = new attribute.array.constructor( arrayBuffer.slice( 0 ) );
  54030. readBufferGPU.unmap();
  54031. return dstBuffer.buffer;
  54032. }
  54033. /**
  54034. * Returns the vertex format of the given buffer attribute.
  54035. *
  54036. * @private
  54037. * @param {BufferAttribute} geometryAttribute - The buffer attribute.
  54038. * @return {string|undefined} The vertex format (e.g. 'float32x3').
  54039. */
  54040. _getVertexFormat( geometryAttribute ) {
  54041. const { itemSize, normalized } = geometryAttribute;
  54042. const ArrayType = geometryAttribute.array.constructor;
  54043. const AttributeType = geometryAttribute.constructor;
  54044. let format;
  54045. if ( itemSize === 1 ) {
  54046. format = typeArraysToVertexFormatPrefixForItemSize1.get( ArrayType );
  54047. } else {
  54048. const prefixOptions = typedAttributeToVertexFormatPrefix.get( AttributeType ) || typedArraysToVertexFormatPrefix.get( ArrayType );
  54049. const prefix = prefixOptions[ normalized ? 1 : 0 ];
  54050. if ( prefix ) {
  54051. const bytesPerUnit = ArrayType.BYTES_PER_ELEMENT * itemSize;
  54052. const paddedBytesPerUnit = Math.floor( ( bytesPerUnit + 3 ) / 4 ) * 4;
  54053. const paddedItemSize = paddedBytesPerUnit / ArrayType.BYTES_PER_ELEMENT;
  54054. if ( paddedItemSize % 1 ) {
  54055. throw new Error( 'THREE.WebGPUAttributeUtils: Bad vertex format item size.' );
  54056. }
  54057. format = `${prefix}x${paddedItemSize}`;
  54058. }
  54059. }
  54060. if ( ! format ) {
  54061. error( 'WebGPUAttributeUtils: Vertex format not supported yet.' );
  54062. }
  54063. return format;
  54064. }
  54065. /**
  54066. * Utility method for handling interleaved buffer attributes correctly.
  54067. * To process them, their `InterleavedBuffer` is returned.
  54068. *
  54069. * @private
  54070. * @param {BufferAttribute} attribute - The attribute.
  54071. * @return {BufferAttribute|InterleavedBuffer}
  54072. */
  54073. _getBufferAttribute( attribute ) {
  54074. if ( attribute.isInterleavedBufferAttribute ) attribute = attribute.data;
  54075. return attribute;
  54076. }
  54077. }
  54078. /**
  54079. * Class representing a WebGPU bind group layout.
  54080. *
  54081. * @private
  54082. */
  54083. class BindGroupLayout {
  54084. /**
  54085. * Constructs a new layout.
  54086. *
  54087. * @param {GPUBindGroupLayout} layoutGPU - A GPU Bind Group Layout.
  54088. */
  54089. constructor( layoutGPU ) {
  54090. /**
  54091. * The current GPUBindGroupLayout.
  54092. *
  54093. * @type {GPUBindGroupLayout}
  54094. */
  54095. this.layoutGPU = layoutGPU;
  54096. /**
  54097. * The number of bind groups that use this layout.
  54098. *
  54099. * @type {number}
  54100. */
  54101. this.usedTimes = 0;
  54102. }
  54103. }
  54104. /**
  54105. * A WebGPU backend utility module for managing bindings.
  54106. *
  54107. * When reading the documentation it's helpful to keep in mind that
  54108. * all class definitions starting with 'GPU*' are modules from the
  54109. * WebGPU API. So for example `BindGroup` is a class from the engine
  54110. * whereas `GPUBindGroup` is a class from WebGPU.
  54111. *
  54112. * @private
  54113. */
  54114. class WebGPUBindingUtils {
  54115. /**
  54116. * Constructs a new utility object.
  54117. *
  54118. * @param {WebGPUBackend} backend - The WebGPU backend.
  54119. */
  54120. constructor( backend ) {
  54121. /**
  54122. * A reference to the WebGPU backend.
  54123. *
  54124. * @type {WebGPUBackend}
  54125. */
  54126. this.backend = backend;
  54127. /**
  54128. * A cache that maps combinations of layout entries to existing bind group layouts.
  54129. *
  54130. * @private
  54131. * @type {Map<string, BindGroupLayout>}
  54132. */
  54133. this._bindGroupLayoutCache = new Map();
  54134. }
  54135. /**
  54136. * Creates a GPU bind group layout for the given bind group.
  54137. *
  54138. * @param {BindGroup} bindGroup - The bind group.
  54139. * @return {GPUBindGroupLayout} The GPU bind group layout.
  54140. */
  54141. createBindingsLayout( bindGroup ) {
  54142. const backend = this.backend;
  54143. const device = backend.device;
  54144. const bindingsData = backend.get( bindGroup );
  54145. // check if the the bind group already has a layout
  54146. if ( bindingsData.layout ) {
  54147. return bindingsData.layout.layoutGPU;
  54148. }
  54149. // if not, assing one
  54150. const entries = this._createLayoutEntries( bindGroup );
  54151. const bindGroupLayoutKey = JSON.stringify( entries );
  54152. // try to find an existing layout in the cache
  54153. let bindGroupLayout = this._bindGroupLayoutCache.get( bindGroupLayoutKey );
  54154. // if not create a new one
  54155. if ( bindGroupLayout === undefined ) {
  54156. bindGroupLayout = new BindGroupLayout( device.createBindGroupLayout( { entries } ) );
  54157. this._bindGroupLayoutCache.set( bindGroupLayoutKey, bindGroupLayout );
  54158. }
  54159. bindGroupLayout.usedTimes ++;
  54160. bindingsData.layout = bindGroupLayout;
  54161. bindingsData.layoutKey = bindGroupLayoutKey;
  54162. return bindGroupLayout.layoutGPU;
  54163. }
  54164. /**
  54165. * Creates bindings from the given bind group definition.
  54166. *
  54167. * @param {BindGroup} bindGroup - The bind group.
  54168. * @param {Array<BindGroup>} bindings - Array of bind groups.
  54169. * @param {number} cacheIndex - The cache index.
  54170. * @param {number} version - The version.
  54171. */
  54172. createBindings( bindGroup, bindings, cacheIndex, version = 0 ) {
  54173. const { backend } = this;
  54174. const bindingsData = backend.get( bindGroup );
  54175. // setup (static) binding layout and (dynamic) binding group
  54176. const bindLayoutGPU = this.createBindingsLayout( bindGroup );
  54177. let bindGroupGPU;
  54178. if ( cacheIndex > 0 ) {
  54179. if ( bindingsData.groups === undefined ) {
  54180. bindingsData.groups = [];
  54181. bindingsData.versions = [];
  54182. }
  54183. if ( bindingsData.versions[ cacheIndex ] === version ) {
  54184. bindGroupGPU = bindingsData.groups[ cacheIndex ];
  54185. }
  54186. }
  54187. if ( bindGroupGPU === undefined ) {
  54188. bindGroupGPU = this.createBindGroup( bindGroup, bindLayoutGPU );
  54189. if ( cacheIndex > 0 ) {
  54190. bindingsData.groups[ cacheIndex ] = bindGroupGPU;
  54191. bindingsData.versions[ cacheIndex ] = version;
  54192. }
  54193. }
  54194. bindingsData.group = bindGroupGPU;
  54195. }
  54196. /**
  54197. * Updates a buffer binding.
  54198. *
  54199. * @param {Buffer} binding - The buffer binding to update.
  54200. */
  54201. updateBinding( binding ) {
  54202. const backend = this.backend;
  54203. const device = backend.device;
  54204. const array = binding.buffer; // cpu
  54205. const buffer = backend.get( binding ).buffer; // gpu
  54206. const updateRanges = binding.updateRanges;
  54207. if ( updateRanges.length === 0 ) {
  54208. device.queue.writeBuffer(
  54209. buffer,
  54210. 0,
  54211. array,
  54212. 0
  54213. );
  54214. } else {
  54215. const isTyped = isTypedArray( array );
  54216. const byteOffsetFactor = isTyped ? 1 : array.BYTES_PER_ELEMENT;
  54217. for ( let i = 0, l = updateRanges.length; i < l; i ++ ) {
  54218. const range = updateRanges[ i ];
  54219. const dataOffset = range.start * byteOffsetFactor;
  54220. const size = range.count * byteOffsetFactor;
  54221. const bufferOffset = dataOffset * ( isTyped ? array.BYTES_PER_ELEMENT : 1 ); // bufferOffset is always in bytes
  54222. device.queue.writeBuffer(
  54223. buffer,
  54224. bufferOffset,
  54225. array,
  54226. dataOffset,
  54227. size
  54228. );
  54229. }
  54230. binding.clearUpdateRanges();
  54231. }
  54232. }
  54233. /**
  54234. * Creates a GPU bind group for the camera index.
  54235. *
  54236. * @param {Uint32Array} data - The index data.
  54237. * @param {GPUBindGroupLayout} layoutGPU - The GPU bind group layout.
  54238. * @return {GPUBindGroup} The GPU bind group.
  54239. */
  54240. createBindGroupIndex( data, layoutGPU ) {
  54241. const backend = this.backend;
  54242. const device = backend.device;
  54243. const usage = GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST;
  54244. const index = data[ 0 ];
  54245. const buffer = device.createBuffer( {
  54246. label: 'bindingCameraIndex_' + index,
  54247. size: 16, // uint(4) * 4
  54248. usage: usage
  54249. } );
  54250. device.queue.writeBuffer( buffer, 0, data, 0 );
  54251. const entries = [ { binding: 0, resource: { buffer } } ];
  54252. return device.createBindGroup( {
  54253. label: 'bindGroupCameraIndex_' + index,
  54254. layout: layoutGPU,
  54255. entries
  54256. } );
  54257. }
  54258. /**
  54259. * Creates a GPU bind group for the given bind group and GPU layout.
  54260. *
  54261. * @param {BindGroup} bindGroup - The bind group.
  54262. * @param {GPUBindGroupLayout} layoutGPU - The GPU bind group layout.
  54263. * @return {GPUBindGroup} The GPU bind group.
  54264. */
  54265. createBindGroup( bindGroup, layoutGPU ) {
  54266. const backend = this.backend;
  54267. const device = backend.device;
  54268. let bindingPoint = 0;
  54269. const entriesGPU = [];
  54270. for ( const binding of bindGroup.bindings ) {
  54271. if ( binding.isUniformBuffer ) {
  54272. const bindingData = backend.get( binding );
  54273. if ( bindingData.buffer === undefined ) {
  54274. const byteLength = binding.byteLength;
  54275. const usage = GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST;
  54276. const visibilities = [];
  54277. if ( binding.visibility & GPUShaderStage.VERTEX ) {
  54278. visibilities.push( 'vertex' );
  54279. }
  54280. if ( binding.visibility & GPUShaderStage.FRAGMENT ) {
  54281. visibilities.push( 'fragment' );
  54282. }
  54283. if ( binding.visibility & GPUShaderStage.COMPUTE ) {
  54284. visibilities.push( 'compute' );
  54285. }
  54286. const bufferVisibility = `(${visibilities.join( ',' )})`;
  54287. const bufferGPU = device.createBuffer( {
  54288. label: `bindingBuffer${binding.id}_${binding.name}_${bufferVisibility}`,
  54289. size: byteLength,
  54290. usage: usage
  54291. } );
  54292. bindingData.buffer = bufferGPU;
  54293. }
  54294. entriesGPU.push( { binding: bindingPoint, resource: { buffer: bindingData.buffer } } );
  54295. } else if ( binding.isStorageBuffer ) {
  54296. const bindingData = backend.get( binding );
  54297. if ( bindingData.buffer === undefined ) {
  54298. const attribute = binding.attribute;
  54299. //const usage = GPUBufferUsage.STORAGE | GPUBufferUsage.VERTEX | /*GPUBufferUsage.COPY_SRC |*/ GPUBufferUsage.COPY_DST;
  54300. //backend.attributeUtils.createAttribute( attribute, usage ); // @TODO: Move it to universal renderer
  54301. bindingData.buffer = backend.get( attribute ).buffer;
  54302. }
  54303. entriesGPU.push( { binding: bindingPoint, resource: { buffer: bindingData.buffer } } );
  54304. } else if ( binding.isSampledTexture ) {
  54305. const textureData = backend.get( binding.texture );
  54306. let resourceGPU;
  54307. if ( textureData.externalTexture !== undefined ) {
  54308. resourceGPU = device.importExternalTexture( { source: textureData.externalTexture } );
  54309. } else {
  54310. const mipLevelCount = binding.store ? 1 : textureData.texture.mipLevelCount;
  54311. const baseMipLevel = binding.store ? binding.mipLevel : 0;
  54312. let propertyName = `view-${ textureData.texture.width }-${ textureData.texture.height }`;
  54313. if ( textureData.texture.depthOrArrayLayers > 1 ) {
  54314. propertyName += `-${ textureData.texture.depthOrArrayLayers }`;
  54315. }
  54316. propertyName += `-${ mipLevelCount }-${ baseMipLevel }`;
  54317. resourceGPU = textureData[ propertyName ];
  54318. if ( resourceGPU === undefined ) {
  54319. const aspectGPU = GPUTextureAspect.All;
  54320. let dimensionViewGPU;
  54321. if ( binding.isSampledCubeTexture ) {
  54322. dimensionViewGPU = GPUTextureViewDimension.Cube;
  54323. } else if ( binding.isSampledTexture3D ) {
  54324. dimensionViewGPU = GPUTextureViewDimension.ThreeD;
  54325. } else if ( binding.texture.isArrayTexture || binding.texture.isDataArrayTexture || binding.texture.isCompressedArrayTexture ) {
  54326. dimensionViewGPU = GPUTextureViewDimension.TwoDArray;
  54327. } else {
  54328. dimensionViewGPU = GPUTextureViewDimension.TwoD;
  54329. }
  54330. resourceGPU = textureData[ propertyName ] = textureData.texture.createView( { aspect: aspectGPU, dimension: dimensionViewGPU, mipLevelCount, baseMipLevel } );
  54331. }
  54332. }
  54333. entriesGPU.push( { binding: bindingPoint, resource: resourceGPU } );
  54334. } else if ( binding.isSampler ) {
  54335. const textureGPU = backend.get( binding.texture );
  54336. entriesGPU.push( { binding: bindingPoint, resource: textureGPU.sampler } );
  54337. }
  54338. bindingPoint ++;
  54339. }
  54340. return device.createBindGroup( {
  54341. label: 'bindGroup_' + bindGroup.name,
  54342. layout: layoutGPU,
  54343. entries: entriesGPU
  54344. } );
  54345. }
  54346. /**
  54347. * Creates a GPU bind group layout entries for the given bind group.
  54348. *
  54349. * @private
  54350. * @param {BindGroup} bindGroup - The bind group.
  54351. * @return {Array<GPUBindGroupLayoutEntry>} The GPU bind group layout entries.
  54352. */
  54353. _createLayoutEntries( bindGroup ) {
  54354. const entries = [];
  54355. let index = 0;
  54356. for ( const binding of bindGroup.bindings ) {
  54357. const backend = this.backend;
  54358. const bindingGPU = {
  54359. binding: index,
  54360. visibility: binding.visibility
  54361. };
  54362. if ( binding.isUniformBuffer || binding.isStorageBuffer ) {
  54363. const buffer = {}; // GPUBufferBindingLayout
  54364. if ( binding.isStorageBuffer ) {
  54365. if ( binding.visibility & GPUShaderStage.COMPUTE ) {
  54366. // compute
  54367. if ( binding.access === NodeAccess.READ_WRITE || binding.access === NodeAccess.WRITE_ONLY ) {
  54368. buffer.type = GPUBufferBindingType.Storage;
  54369. } else {
  54370. buffer.type = GPUBufferBindingType.ReadOnlyStorage;
  54371. }
  54372. } else {
  54373. buffer.type = GPUBufferBindingType.ReadOnlyStorage;
  54374. }
  54375. }
  54376. bindingGPU.buffer = buffer;
  54377. } else if ( binding.isSampledTexture && binding.store ) {
  54378. const storageTexture = {}; // GPUStorageTextureBindingLayout
  54379. storageTexture.format = this.backend.get( binding.texture ).texture.format;
  54380. const access = binding.access;
  54381. if ( access === NodeAccess.READ_WRITE ) {
  54382. storageTexture.access = GPUStorageTextureAccess.ReadWrite;
  54383. } else if ( access === NodeAccess.WRITE_ONLY ) {
  54384. storageTexture.access = GPUStorageTextureAccess.WriteOnly;
  54385. } else {
  54386. storageTexture.access = GPUStorageTextureAccess.ReadOnly;
  54387. }
  54388. if ( binding.texture.isArrayTexture ) {
  54389. storageTexture.viewDimension = GPUTextureViewDimension.TwoDArray;
  54390. } else if ( binding.texture.is3DTexture ) {
  54391. storageTexture.viewDimension = GPUTextureViewDimension.ThreeD;
  54392. }
  54393. bindingGPU.storageTexture = storageTexture;
  54394. } else if ( binding.isSampledTexture ) {
  54395. const texture = {}; // GPUTextureBindingLayout
  54396. const { primarySamples } = backend.utils.getTextureSampleData( binding.texture );
  54397. if ( primarySamples > 1 ) {
  54398. texture.multisampled = true;
  54399. if ( ! binding.texture.isDepthTexture ) {
  54400. texture.sampleType = GPUTextureSampleType.UnfilterableFloat;
  54401. }
  54402. }
  54403. if ( binding.texture.isDepthTexture ) {
  54404. if ( backend.compatibilityMode && binding.texture.compareFunction === null ) {
  54405. texture.sampleType = GPUTextureSampleType.UnfilterableFloat;
  54406. } else {
  54407. texture.sampleType = GPUTextureSampleType.Depth;
  54408. }
  54409. } else if ( binding.texture.isDataTexture || binding.texture.isDataArrayTexture || binding.texture.isData3DTexture ) {
  54410. const type = binding.texture.type;
  54411. if ( type === IntType ) {
  54412. texture.sampleType = GPUTextureSampleType.SInt;
  54413. } else if ( type === UnsignedIntType ) {
  54414. texture.sampleType = GPUTextureSampleType.UInt;
  54415. } else if ( type === FloatType ) {
  54416. if ( this.backend.hasFeature( 'float32-filterable' ) ) {
  54417. texture.sampleType = GPUTextureSampleType.Float;
  54418. } else {
  54419. texture.sampleType = GPUTextureSampleType.UnfilterableFloat;
  54420. }
  54421. }
  54422. }
  54423. if ( binding.isSampledCubeTexture ) {
  54424. texture.viewDimension = GPUTextureViewDimension.Cube;
  54425. } else if ( binding.texture.isArrayTexture || binding.texture.isDataArrayTexture || binding.texture.isCompressedArrayTexture ) {
  54426. texture.viewDimension = GPUTextureViewDimension.TwoDArray;
  54427. } else if ( binding.isSampledTexture3D ) {
  54428. texture.viewDimension = GPUTextureViewDimension.ThreeD;
  54429. }
  54430. bindingGPU.texture = texture;
  54431. } else if ( binding.isSampler ) {
  54432. const sampler = {}; // GPUSamplerBindingLayout
  54433. if ( binding.texture.isDepthTexture ) {
  54434. if ( binding.texture.compareFunction !== null ) {
  54435. sampler.type = GPUSamplerBindingType.Comparison;
  54436. } else if ( backend.compatibilityMode ) {
  54437. sampler.type = GPUSamplerBindingType.NonFiltering;
  54438. }
  54439. }
  54440. bindingGPU.sampler = sampler;
  54441. } else {
  54442. error( `WebGPUBindingUtils: Unsupported binding "${ binding }".` );
  54443. }
  54444. entries.push( bindingGPU );
  54445. index ++;
  54446. }
  54447. return entries;
  54448. }
  54449. /**
  54450. * Delete the data associated with a bind group.
  54451. *
  54452. * @param {BindGroup} bindGroup - The bind group.
  54453. */
  54454. deleteBindGroupData( bindGroup ) {
  54455. const { backend } = this;
  54456. const bindingsData = backend.get( bindGroup );
  54457. if ( bindingsData.layout ) {
  54458. bindingsData.layout.usedTimes --;
  54459. if ( bindingsData.layout.usedTimes === 0 ) {
  54460. this._bindGroupLayoutCache.delete( bindingsData.layoutKey );
  54461. }
  54462. bindingsData.layout = undefined;
  54463. bindingsData.layoutKey = undefined;
  54464. }
  54465. }
  54466. /**
  54467. * Frees internal resources.
  54468. */
  54469. dispose() {
  54470. this._bindGroupLayoutCache.clear();
  54471. }
  54472. }
  54473. /**
  54474. * A WebGPU backend utility module for managing pipelines.
  54475. *
  54476. * @private
  54477. */
  54478. class WebGPUPipelineUtils {
  54479. /**
  54480. * Constructs a new utility object.
  54481. *
  54482. * @param {WebGPUBackend} backend - The WebGPU backend.
  54483. */
  54484. constructor( backend ) {
  54485. /**
  54486. * A reference to the WebGPU backend.
  54487. *
  54488. * @type {WebGPUBackend}
  54489. */
  54490. this.backend = backend;
  54491. /**
  54492. * A Weak Map that tracks the active pipeline for render or compute passes.
  54493. *
  54494. * @private
  54495. * @type {WeakMap<(GPURenderPassEncoder|GPUComputePassEncoder),(GPURenderPipeline|GPUComputePipeline)>}
  54496. */
  54497. this._activePipelines = new WeakMap();
  54498. }
  54499. /**
  54500. * Sets the given pipeline for the given pass. The method makes sure to only set the
  54501. * pipeline when necessary.
  54502. *
  54503. * @param {(GPURenderPassEncoder|GPUComputePassEncoder)} pass - The pass encoder.
  54504. * @param {(GPURenderPipeline|GPUComputePipeline)} pipeline - The pipeline.
  54505. */
  54506. setPipeline( pass, pipeline ) {
  54507. const currentPipeline = this._activePipelines.get( pass );
  54508. if ( currentPipeline !== pipeline ) {
  54509. pass.setPipeline( pipeline );
  54510. this._activePipelines.set( pass, pipeline );
  54511. }
  54512. }
  54513. /**
  54514. * Returns the sample count derived from the given render context.
  54515. *
  54516. * @private
  54517. * @param {RenderContext} renderContext - The render context.
  54518. * @return {number} The sample count.
  54519. */
  54520. _getSampleCount( renderContext ) {
  54521. return this.backend.utils.getSampleCountRenderContext( renderContext );
  54522. }
  54523. /**
  54524. * Creates a render pipeline for the given render object.
  54525. *
  54526. * @param {RenderObject} renderObject - The render object.
  54527. * @param {Array<Promise>} promises - An array of compilation promises which are used in `compileAsync()`.
  54528. */
  54529. createRenderPipeline( renderObject, promises ) {
  54530. const { object, material, geometry, pipeline } = renderObject;
  54531. const { vertexProgram, fragmentProgram } = pipeline;
  54532. const backend = this.backend;
  54533. const device = backend.device;
  54534. const utils = backend.utils;
  54535. const pipelineData = backend.get( pipeline );
  54536. // bind group layouts
  54537. const bindGroupLayouts = [];
  54538. for ( const bindGroup of renderObject.getBindings() ) {
  54539. const bindingsData = backend.get( bindGroup );
  54540. const { layoutGPU } = bindingsData.layout;
  54541. bindGroupLayouts.push( layoutGPU );
  54542. }
  54543. // vertex buffers
  54544. const vertexBuffers = backend.attributeUtils.createShaderVertexBuffers( renderObject );
  54545. // blending
  54546. let blending;
  54547. if ( material.blending !== NoBlending && ( material.blending !== NormalBlending || material.transparent !== false ) ) {
  54548. blending = this._getBlending( material );
  54549. }
  54550. // stencil
  54551. let stencilFront = {};
  54552. if ( material.stencilWrite === true ) {
  54553. stencilFront = {
  54554. compare: this._getStencilCompare( material ),
  54555. failOp: this._getStencilOperation( material.stencilFail ),
  54556. depthFailOp: this._getStencilOperation( material.stencilZFail ),
  54557. passOp: this._getStencilOperation( material.stencilZPass )
  54558. };
  54559. }
  54560. const colorWriteMask = this._getColorWriteMask( material );
  54561. const targets = [];
  54562. if ( renderObject.context.textures !== null ) {
  54563. const textures = renderObject.context.textures;
  54564. for ( let i = 0; i < textures.length; i ++ ) {
  54565. const colorFormat = utils.getTextureFormatGPU( textures[ i ] );
  54566. if ( i === 0 ) {
  54567. targets.push( {
  54568. format: colorFormat,
  54569. blend: blending,
  54570. writeMask: colorWriteMask
  54571. } );
  54572. } else {
  54573. targets.push( {
  54574. format: colorFormat,
  54575. writeMask: colorWriteMask
  54576. } );
  54577. }
  54578. }
  54579. } else {
  54580. const colorFormat = utils.getCurrentColorFormat( renderObject.context );
  54581. targets.push( {
  54582. format: colorFormat,
  54583. blend: blending,
  54584. writeMask: colorWriteMask
  54585. } );
  54586. }
  54587. const vertexModule = backend.get( vertexProgram ).module;
  54588. const fragmentModule = backend.get( fragmentProgram ).module;
  54589. const primitiveState = this._getPrimitiveState( object, geometry, material );
  54590. const depthCompare = this._getDepthCompare( material );
  54591. const depthStencilFormat = utils.getCurrentDepthStencilFormat( renderObject.context );
  54592. const sampleCount = this._getSampleCount( renderObject.context );
  54593. const pipelineDescriptor = {
  54594. label: `renderPipeline_${ material.name || material.type }_${ material.id }`,
  54595. vertex: Object.assign( {}, vertexModule, { buffers: vertexBuffers } ),
  54596. fragment: Object.assign( {}, fragmentModule, { targets } ),
  54597. primitive: primitiveState,
  54598. multisample: {
  54599. count: sampleCount,
  54600. alphaToCoverageEnabled: material.alphaToCoverage && sampleCount > 1
  54601. },
  54602. layout: device.createPipelineLayout( {
  54603. bindGroupLayouts
  54604. } )
  54605. };
  54606. const depthStencil = {};
  54607. const renderDepth = renderObject.context.depth;
  54608. const renderStencil = renderObject.context.stencil;
  54609. if ( renderDepth === true || renderStencil === true ) {
  54610. if ( renderDepth === true ) {
  54611. depthStencil.format = depthStencilFormat;
  54612. depthStencil.depthWriteEnabled = material.depthWrite;
  54613. depthStencil.depthCompare = depthCompare;
  54614. }
  54615. if ( renderStencil === true ) {
  54616. depthStencil.stencilFront = stencilFront;
  54617. depthStencil.stencilBack = {}; // three.js does not provide an API to configure the back function (gl.stencilFuncSeparate() was never used)
  54618. depthStencil.stencilReadMask = material.stencilFuncMask;
  54619. depthStencil.stencilWriteMask = material.stencilWriteMask;
  54620. }
  54621. if ( material.polygonOffset === true ) {
  54622. depthStencil.depthBias = material.polygonOffsetUnits;
  54623. depthStencil.depthBiasSlopeScale = material.polygonOffsetFactor;
  54624. depthStencil.depthBiasClamp = 0; // three.js does not provide an API to configure this value
  54625. }
  54626. pipelineDescriptor.depthStencil = depthStencil;
  54627. }
  54628. // create pipeline
  54629. device.pushErrorScope( 'validation' );
  54630. if ( promises === null ) {
  54631. pipelineData.pipeline = device.createRenderPipeline( pipelineDescriptor );
  54632. device.popErrorScope().then( ( err ) => {
  54633. if ( err !== null ) {
  54634. pipelineData.error = true;
  54635. error( err.message );
  54636. }
  54637. } );
  54638. } else {
  54639. const p = new Promise( async ( resolve /*, reject*/ ) => {
  54640. try {
  54641. pipelineData.pipeline = await device.createRenderPipelineAsync( pipelineDescriptor );
  54642. } catch ( err ) { }
  54643. const errorScope = await device.popErrorScope();
  54644. if ( errorScope !== null ) {
  54645. pipelineData.error = true;
  54646. error( errorScope.message );
  54647. }
  54648. resolve();
  54649. } );
  54650. promises.push( p );
  54651. }
  54652. }
  54653. /**
  54654. * Creates GPU render bundle encoder for the given render context.
  54655. *
  54656. * @param {RenderContext} renderContext - The render context.
  54657. * @param {?string} [label='renderBundleEncoder'] - The label.
  54658. * @return {GPURenderBundleEncoder} The GPU render bundle encoder.
  54659. */
  54660. createBundleEncoder( renderContext, label = 'renderBundleEncoder' ) {
  54661. const backend = this.backend;
  54662. const { utils, device } = backend;
  54663. const depthStencilFormat = utils.getCurrentDepthStencilFormat( renderContext );
  54664. const colorFormats = utils.getCurrentColorFormats( renderContext );
  54665. const sampleCount = this._getSampleCount( renderContext );
  54666. const descriptor = {
  54667. label,
  54668. colorFormats,
  54669. depthStencilFormat,
  54670. sampleCount
  54671. };
  54672. return device.createRenderBundleEncoder( descriptor );
  54673. }
  54674. /**
  54675. * Creates a compute pipeline for the given compute node.
  54676. *
  54677. * @param {ComputePipeline} pipeline - The compute pipeline.
  54678. * @param {Array<BindGroup>} bindings - The bindings.
  54679. */
  54680. createComputePipeline( pipeline, bindings ) {
  54681. const backend = this.backend;
  54682. const device = backend.device;
  54683. const computeProgram = backend.get( pipeline.computeProgram ).module;
  54684. const pipelineGPU = backend.get( pipeline );
  54685. // bind group layouts
  54686. const bindGroupLayouts = [];
  54687. for ( const bindingsGroup of bindings ) {
  54688. const bindingsData = backend.get( bindingsGroup );
  54689. const { layoutGPU } = bindingsData.layout;
  54690. bindGroupLayouts.push( layoutGPU );
  54691. }
  54692. pipelineGPU.pipeline = device.createComputePipeline( {
  54693. compute: computeProgram,
  54694. layout: device.createPipelineLayout( {
  54695. bindGroupLayouts
  54696. } )
  54697. } );
  54698. }
  54699. /**
  54700. * Returns the blending state as a descriptor object required
  54701. * for the pipeline creation.
  54702. *
  54703. * @private
  54704. * @param {Material} material - The material.
  54705. * @return {Object} The blending state.
  54706. */
  54707. _getBlending( material ) {
  54708. let color, alpha;
  54709. const blending = material.blending;
  54710. const blendSrc = material.blendSrc;
  54711. const blendDst = material.blendDst;
  54712. const blendEquation = material.blendEquation;
  54713. if ( blending === CustomBlending ) {
  54714. const blendSrcAlpha = material.blendSrcAlpha !== null ? material.blendSrcAlpha : blendSrc;
  54715. const blendDstAlpha = material.blendDstAlpha !== null ? material.blendDstAlpha : blendDst;
  54716. const blendEquationAlpha = material.blendEquationAlpha !== null ? material.blendEquationAlpha : blendEquation;
  54717. color = {
  54718. srcFactor: this._getBlendFactor( blendSrc ),
  54719. dstFactor: this._getBlendFactor( blendDst ),
  54720. operation: this._getBlendOperation( blendEquation )
  54721. };
  54722. alpha = {
  54723. srcFactor: this._getBlendFactor( blendSrcAlpha ),
  54724. dstFactor: this._getBlendFactor( blendDstAlpha ),
  54725. operation: this._getBlendOperation( blendEquationAlpha )
  54726. };
  54727. } else {
  54728. const premultipliedAlpha = material.premultipliedAlpha;
  54729. const setBlend = ( srcRGB, dstRGB, srcAlpha, dstAlpha ) => {
  54730. color = {
  54731. srcFactor: srcRGB,
  54732. dstFactor: dstRGB,
  54733. operation: GPUBlendOperation.Add
  54734. };
  54735. alpha = {
  54736. srcFactor: srcAlpha,
  54737. dstFactor: dstAlpha,
  54738. operation: GPUBlendOperation.Add
  54739. };
  54740. };
  54741. if ( premultipliedAlpha ) {
  54742. switch ( blending ) {
  54743. case NormalBlending:
  54744. setBlend( GPUBlendFactor.One, GPUBlendFactor.OneMinusSrcAlpha, GPUBlendFactor.One, GPUBlendFactor.OneMinusSrcAlpha );
  54745. break;
  54746. case AdditiveBlending:
  54747. setBlend( GPUBlendFactor.One, GPUBlendFactor.One, GPUBlendFactor.One, GPUBlendFactor.One );
  54748. break;
  54749. case SubtractiveBlending:
  54750. setBlend( GPUBlendFactor.Zero, GPUBlendFactor.OneMinusSrc, GPUBlendFactor.Zero, GPUBlendFactor.One );
  54751. break;
  54752. case MultiplyBlending:
  54753. setBlend( GPUBlendFactor.Dst, GPUBlendFactor.OneMinusSrcAlpha, GPUBlendFactor.Zero, GPUBlendFactor.One );
  54754. break;
  54755. }
  54756. } else {
  54757. switch ( blending ) {
  54758. case NormalBlending:
  54759. setBlend( GPUBlendFactor.SrcAlpha, GPUBlendFactor.OneMinusSrcAlpha, GPUBlendFactor.One, GPUBlendFactor.OneMinusSrcAlpha );
  54760. break;
  54761. case AdditiveBlending:
  54762. setBlend( GPUBlendFactor.SrcAlpha, GPUBlendFactor.One, GPUBlendFactor.One, GPUBlendFactor.One );
  54763. break;
  54764. case SubtractiveBlending:
  54765. error( 'WebGPURenderer: SubtractiveBlending requires material.premultipliedAlpha = true' );
  54766. break;
  54767. case MultiplyBlending:
  54768. error( 'WebGPURenderer: MultiplyBlending requires material.premultipliedAlpha = true' );
  54769. break;
  54770. }
  54771. }
  54772. }
  54773. if ( color !== undefined && alpha !== undefined ) {
  54774. return { color, alpha };
  54775. } else {
  54776. error( 'WebGPURenderer: Invalid blending: ', blending );
  54777. }
  54778. }
  54779. /**
  54780. * Returns the GPU blend factor which is required for the pipeline creation.
  54781. *
  54782. * @private
  54783. * @param {number} blend - The blend factor as a three.js constant.
  54784. * @return {string} The GPU blend factor.
  54785. */
  54786. _getBlendFactor( blend ) {
  54787. let blendFactor;
  54788. switch ( blend ) {
  54789. case ZeroFactor:
  54790. blendFactor = GPUBlendFactor.Zero;
  54791. break;
  54792. case OneFactor:
  54793. blendFactor = GPUBlendFactor.One;
  54794. break;
  54795. case SrcColorFactor:
  54796. blendFactor = GPUBlendFactor.Src;
  54797. break;
  54798. case OneMinusSrcColorFactor:
  54799. blendFactor = GPUBlendFactor.OneMinusSrc;
  54800. break;
  54801. case SrcAlphaFactor:
  54802. blendFactor = GPUBlendFactor.SrcAlpha;
  54803. break;
  54804. case OneMinusSrcAlphaFactor:
  54805. blendFactor = GPUBlendFactor.OneMinusSrcAlpha;
  54806. break;
  54807. case DstColorFactor:
  54808. blendFactor = GPUBlendFactor.Dst;
  54809. break;
  54810. case OneMinusDstColorFactor:
  54811. blendFactor = GPUBlendFactor.OneMinusDst;
  54812. break;
  54813. case DstAlphaFactor:
  54814. blendFactor = GPUBlendFactor.DstAlpha;
  54815. break;
  54816. case OneMinusDstAlphaFactor:
  54817. blendFactor = GPUBlendFactor.OneMinusDstAlpha;
  54818. break;
  54819. case SrcAlphaSaturateFactor:
  54820. blendFactor = GPUBlendFactor.SrcAlphaSaturated;
  54821. break;
  54822. case BlendColorFactor:
  54823. blendFactor = GPUBlendFactor.Constant;
  54824. break;
  54825. case OneMinusBlendColorFactor:
  54826. blendFactor = GPUBlendFactor.OneMinusConstant;
  54827. break;
  54828. default:
  54829. error( 'WebGPURenderer: Blend factor not supported.', blend );
  54830. }
  54831. return blendFactor;
  54832. }
  54833. /**
  54834. * Returns the GPU stencil compare function which is required for the pipeline creation.
  54835. *
  54836. * @private
  54837. * @param {Material} material - The material.
  54838. * @return {string} The GPU stencil compare function.
  54839. */
  54840. _getStencilCompare( material ) {
  54841. let stencilCompare;
  54842. const stencilFunc = material.stencilFunc;
  54843. switch ( stencilFunc ) {
  54844. case NeverStencilFunc:
  54845. stencilCompare = GPUCompareFunction.Never;
  54846. break;
  54847. case AlwaysStencilFunc:
  54848. stencilCompare = GPUCompareFunction.Always;
  54849. break;
  54850. case LessStencilFunc:
  54851. stencilCompare = GPUCompareFunction.Less;
  54852. break;
  54853. case LessEqualStencilFunc:
  54854. stencilCompare = GPUCompareFunction.LessEqual;
  54855. break;
  54856. case EqualStencilFunc:
  54857. stencilCompare = GPUCompareFunction.Equal;
  54858. break;
  54859. case GreaterEqualStencilFunc:
  54860. stencilCompare = GPUCompareFunction.GreaterEqual;
  54861. break;
  54862. case GreaterStencilFunc:
  54863. stencilCompare = GPUCompareFunction.Greater;
  54864. break;
  54865. case NotEqualStencilFunc:
  54866. stencilCompare = GPUCompareFunction.NotEqual;
  54867. break;
  54868. default:
  54869. error( 'WebGPURenderer: Invalid stencil function.', stencilFunc );
  54870. }
  54871. return stencilCompare;
  54872. }
  54873. /**
  54874. * Returns the GPU stencil operation which is required for the pipeline creation.
  54875. *
  54876. * @private
  54877. * @param {number} op - A three.js constant defining the stencil operation.
  54878. * @return {string} The GPU stencil operation.
  54879. */
  54880. _getStencilOperation( op ) {
  54881. let stencilOperation;
  54882. switch ( op ) {
  54883. case KeepStencilOp:
  54884. stencilOperation = GPUStencilOperation.Keep;
  54885. break;
  54886. case ZeroStencilOp:
  54887. stencilOperation = GPUStencilOperation.Zero;
  54888. break;
  54889. case ReplaceStencilOp:
  54890. stencilOperation = GPUStencilOperation.Replace;
  54891. break;
  54892. case InvertStencilOp:
  54893. stencilOperation = GPUStencilOperation.Invert;
  54894. break;
  54895. case IncrementStencilOp:
  54896. stencilOperation = GPUStencilOperation.IncrementClamp;
  54897. break;
  54898. case DecrementStencilOp:
  54899. stencilOperation = GPUStencilOperation.DecrementClamp;
  54900. break;
  54901. case IncrementWrapStencilOp:
  54902. stencilOperation = GPUStencilOperation.IncrementWrap;
  54903. break;
  54904. case DecrementWrapStencilOp:
  54905. stencilOperation = GPUStencilOperation.DecrementWrap;
  54906. break;
  54907. default:
  54908. error( 'WebGPURenderer: Invalid stencil operation.', stencilOperation );
  54909. }
  54910. return stencilOperation;
  54911. }
  54912. /**
  54913. * Returns the GPU blend operation which is required for the pipeline creation.
  54914. *
  54915. * @private
  54916. * @param {number} blendEquation - A three.js constant defining the blend equation.
  54917. * @return {string} The GPU blend operation.
  54918. */
  54919. _getBlendOperation( blendEquation ) {
  54920. let blendOperation;
  54921. switch ( blendEquation ) {
  54922. case AddEquation:
  54923. blendOperation = GPUBlendOperation.Add;
  54924. break;
  54925. case SubtractEquation:
  54926. blendOperation = GPUBlendOperation.Subtract;
  54927. break;
  54928. case ReverseSubtractEquation:
  54929. blendOperation = GPUBlendOperation.ReverseSubtract;
  54930. break;
  54931. case MinEquation:
  54932. blendOperation = GPUBlendOperation.Min;
  54933. break;
  54934. case MaxEquation:
  54935. blendOperation = GPUBlendOperation.Max;
  54936. break;
  54937. default:
  54938. error( 'WebGPUPipelineUtils: Blend equation not supported.', blendEquation );
  54939. }
  54940. return blendOperation;
  54941. }
  54942. /**
  54943. * Returns the primitive state as a descriptor object required
  54944. * for the pipeline creation.
  54945. *
  54946. * @private
  54947. * @param {Object3D} object - The 3D object.
  54948. * @param {BufferGeometry} geometry - The geometry.
  54949. * @param {Material} material - The material.
  54950. * @return {Object} The primitive state.
  54951. */
  54952. _getPrimitiveState( object, geometry, material ) {
  54953. const descriptor = {};
  54954. const utils = this.backend.utils;
  54955. //
  54956. descriptor.topology = utils.getPrimitiveTopology( object, material );
  54957. if ( geometry.index !== null && object.isLine === true && object.isLineSegments !== true ) {
  54958. descriptor.stripIndexFormat = ( geometry.index.array instanceof Uint16Array ) ? GPUIndexFormat.Uint16 : GPUIndexFormat.Uint32;
  54959. }
  54960. //
  54961. let flipSided = ( material.side === BackSide );
  54962. if ( object.isMesh && object.matrixWorld.determinant() < 0 ) flipSided = ! flipSided;
  54963. descriptor.frontFace = ( flipSided === true ) ? GPUFrontFace.CW : GPUFrontFace.CCW;
  54964. //
  54965. descriptor.cullMode = ( material.side === DoubleSide ) ? GPUCullMode.None : GPUCullMode.Back;
  54966. return descriptor;
  54967. }
  54968. /**
  54969. * Returns the GPU color write mask which is required for the pipeline creation.
  54970. *
  54971. * @private
  54972. * @param {Material} material - The material.
  54973. * @return {number} The GPU color write mask.
  54974. */
  54975. _getColorWriteMask( material ) {
  54976. return ( material.colorWrite === true ) ? GPUColorWriteFlags.All : GPUColorWriteFlags.None;
  54977. }
  54978. /**
  54979. * Returns the GPU depth compare function which is required for the pipeline creation.
  54980. *
  54981. * @private
  54982. * @param {Material} material - The material.
  54983. * @return {string} The GPU depth compare function.
  54984. */
  54985. _getDepthCompare( material ) {
  54986. let depthCompare;
  54987. if ( material.depthTest === false ) {
  54988. depthCompare = GPUCompareFunction.Always;
  54989. } else {
  54990. const depthFunc = material.depthFunc;
  54991. switch ( depthFunc ) {
  54992. case NeverDepth:
  54993. depthCompare = GPUCompareFunction.Never;
  54994. break;
  54995. case AlwaysDepth:
  54996. depthCompare = GPUCompareFunction.Always;
  54997. break;
  54998. case LessDepth:
  54999. depthCompare = GPUCompareFunction.Less;
  55000. break;
  55001. case LessEqualDepth:
  55002. depthCompare = GPUCompareFunction.LessEqual;
  55003. break;
  55004. case EqualDepth:
  55005. depthCompare = GPUCompareFunction.Equal;
  55006. break;
  55007. case GreaterEqualDepth:
  55008. depthCompare = GPUCompareFunction.GreaterEqual;
  55009. break;
  55010. case GreaterDepth:
  55011. depthCompare = GPUCompareFunction.Greater;
  55012. break;
  55013. case NotEqualDepth:
  55014. depthCompare = GPUCompareFunction.NotEqual;
  55015. break;
  55016. default:
  55017. error( 'WebGPUPipelineUtils: Invalid depth function.', depthFunc );
  55018. }
  55019. }
  55020. return depthCompare;
  55021. }
  55022. }
  55023. /**
  55024. * Manages a pool of WebGPU timestamp queries for performance measurement.
  55025. * Extends the base TimestampQueryPool to provide WebGPU-specific implementation.
  55026. *
  55027. * @augments TimestampQueryPool
  55028. */
  55029. class WebGPUTimestampQueryPool extends TimestampQueryPool {
  55030. /**
  55031. * Creates a new WebGPU timestamp query pool.
  55032. *
  55033. * @param {GPUDevice} device - The WebGPU device to create queries on.
  55034. * @param {string} type - The type identifier for this query pool.
  55035. * @param {number} [maxQueries=2048] - Maximum number of queries this pool can hold.
  55036. */
  55037. constructor( device, type, maxQueries = 2048 ) {
  55038. super( maxQueries );
  55039. this.device = device;
  55040. this.type = type;
  55041. this.querySet = this.device.createQuerySet( {
  55042. type: 'timestamp',
  55043. count: this.maxQueries,
  55044. label: `queryset_global_timestamp_${type}`
  55045. } );
  55046. const bufferSize = this.maxQueries * 8;
  55047. this.resolveBuffer = this.device.createBuffer( {
  55048. label: `buffer_timestamp_resolve_${type}`,
  55049. size: bufferSize,
  55050. usage: GPUBufferUsage.QUERY_RESOLVE | GPUBufferUsage.COPY_SRC
  55051. } );
  55052. this.resultBuffer = this.device.createBuffer( {
  55053. label: `buffer_timestamp_result_${type}`,
  55054. size: bufferSize,
  55055. usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ
  55056. } );
  55057. }
  55058. /**
  55059. * Allocates a pair of queries for a given render context.
  55060. *
  55061. * @param {string} uid - A unique identifier for the render context.
  55062. * @returns {?number} The base offset for the allocated queries, or null if allocation failed.
  55063. */
  55064. allocateQueriesForContext( uid ) {
  55065. if ( ! this.trackTimestamp || this.isDisposed ) return null;
  55066. if ( this.currentQueryIndex + 2 > this.maxQueries ) {
  55067. 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() } ).` );
  55068. return null;
  55069. }
  55070. const baseOffset = this.currentQueryIndex;
  55071. this.currentQueryIndex += 2;
  55072. this.queryOffsets.set( uid, baseOffset );
  55073. return baseOffset;
  55074. }
  55075. /**
  55076. * Asynchronously resolves all pending queries and returns the total duration.
  55077. * If there's already a pending resolve operation, returns that promise instead.
  55078. *
  55079. * @async
  55080. * @returns {Promise<number>} The total duration in milliseconds, or the last valid value if resolution fails.
  55081. */
  55082. async resolveQueriesAsync() {
  55083. if ( ! this.trackTimestamp || this.currentQueryIndex === 0 || this.isDisposed ) {
  55084. return this.lastValue;
  55085. }
  55086. if ( this.pendingResolve ) {
  55087. return this.pendingResolve;
  55088. }
  55089. this.pendingResolve = this._resolveQueries();
  55090. try {
  55091. const result = await this.pendingResolve;
  55092. return result;
  55093. } finally {
  55094. this.pendingResolve = null;
  55095. }
  55096. }
  55097. /**
  55098. * Internal method to resolve queries and calculate total duration.
  55099. *
  55100. * @async
  55101. * @private
  55102. * @returns {Promise<number>} The total duration in milliseconds.
  55103. */
  55104. async _resolveQueries() {
  55105. if ( this.isDisposed ) {
  55106. return this.lastValue;
  55107. }
  55108. try {
  55109. if ( this.resultBuffer.mapState !== 'unmapped' ) {
  55110. return this.lastValue;
  55111. }
  55112. const currentOffsets = new Map( this.queryOffsets );
  55113. const queryCount = this.currentQueryIndex;
  55114. const bytesUsed = queryCount * 8;
  55115. // Reset state before GPU work
  55116. this.currentQueryIndex = 0;
  55117. this.queryOffsets.clear();
  55118. const commandEncoder = this.device.createCommandEncoder();
  55119. commandEncoder.resolveQuerySet(
  55120. this.querySet,
  55121. 0,
  55122. queryCount,
  55123. this.resolveBuffer,
  55124. 0
  55125. );
  55126. commandEncoder.copyBufferToBuffer(
  55127. this.resolveBuffer,
  55128. 0,
  55129. this.resultBuffer,
  55130. 0,
  55131. bytesUsed
  55132. );
  55133. const commandBuffer = commandEncoder.finish();
  55134. this.device.queue.submit( [ commandBuffer ] );
  55135. if ( this.resultBuffer.mapState !== 'unmapped' ) {
  55136. return this.lastValue;
  55137. }
  55138. // Create and track the mapping operation
  55139. await this.resultBuffer.mapAsync( GPUMapMode.READ, 0, bytesUsed );
  55140. if ( this.isDisposed ) {
  55141. if ( this.resultBuffer.mapState === 'mapped' ) {
  55142. this.resultBuffer.unmap();
  55143. }
  55144. return this.lastValue;
  55145. }
  55146. //
  55147. const times = new BigUint64Array( this.resultBuffer.getMappedRange( 0, bytesUsed ) );
  55148. const framesDuration = {};
  55149. const frames = [];
  55150. for ( const [ uid, baseOffset ] of currentOffsets ) {
  55151. const match = uid.match( /^(.*):f(\d+)$/ );
  55152. const frame = parseInt( match[ 2 ] );
  55153. if ( frames.includes( frame ) === false ) {
  55154. frames.push( frame );
  55155. }
  55156. if ( framesDuration[ frame ] === undefined ) framesDuration[ frame ] = 0;
  55157. const startTime = times[ baseOffset ];
  55158. const endTime = times[ baseOffset + 1 ];
  55159. const duration = Number( endTime - startTime ) / 1e6;
  55160. this.timestamps.set( uid, duration );
  55161. framesDuration[ frame ] += duration;
  55162. }
  55163. // Return the total duration of the last frame
  55164. const totalDuration = framesDuration[ frames[ frames.length - 1 ] ];
  55165. this.resultBuffer.unmap();
  55166. this.lastValue = totalDuration;
  55167. this.frames = frames;
  55168. return totalDuration;
  55169. } catch ( e ) {
  55170. error( 'Error resolving queries:', e );
  55171. if ( this.resultBuffer.mapState === 'mapped' ) {
  55172. this.resultBuffer.unmap();
  55173. }
  55174. return this.lastValue;
  55175. }
  55176. }
  55177. /**
  55178. * Dispose of the query pool.
  55179. *
  55180. * @async
  55181. * @returns {Promise} A Promise that resolves when the dispose has been executed.
  55182. */
  55183. async dispose() {
  55184. if ( this.isDisposed ) {
  55185. return;
  55186. }
  55187. this.isDisposed = true;
  55188. // Wait for pending resolve operation
  55189. if ( this.pendingResolve ) {
  55190. try {
  55191. await this.pendingResolve;
  55192. } catch ( e ) {
  55193. error( 'Error waiting for pending resolve:', e );
  55194. }
  55195. }
  55196. // Ensure buffer is unmapped before destroying
  55197. if ( this.resultBuffer && this.resultBuffer.mapState === 'mapped' ) {
  55198. try {
  55199. this.resultBuffer.unmap();
  55200. } catch ( e ) {
  55201. error( 'Error unmapping buffer:', e );
  55202. }
  55203. }
  55204. // Destroy resources
  55205. if ( this.querySet ) {
  55206. this.querySet.destroy();
  55207. this.querySet = null;
  55208. }
  55209. if ( this.resolveBuffer ) {
  55210. this.resolveBuffer.destroy();
  55211. this.resolveBuffer = null;
  55212. }
  55213. if ( this.resultBuffer ) {
  55214. this.resultBuffer.destroy();
  55215. this.resultBuffer = null;
  55216. }
  55217. this.queryOffsets.clear();
  55218. this.pendingResolve = null;
  55219. }
  55220. }
  55221. /*// debugger tools
  55222. import 'https://greggman.github.io/webgpu-avoid-redundant-state-setting/webgpu-check-redundant-state-setting.js';
  55223. //*/
  55224. /**
  55225. * A backend implementation targeting WebGPU.
  55226. *
  55227. * @private
  55228. * @augments Backend
  55229. */
  55230. class WebGPUBackend extends Backend {
  55231. /**
  55232. * WebGPUBackend options.
  55233. *
  55234. * @typedef {Object} WebGPUBackend~Options
  55235. * @property {boolean} [logarithmicDepthBuffer=false] - Whether logarithmic depth buffer is enabled or not.
  55236. * @property {boolean} [alpha=true] - Whether the default framebuffer (which represents the final contents of the canvas) should be transparent or opaque.
  55237. * @property {boolean} [compatibilityMode=false] - Whether the backend should be in compatibility mode or not.
  55238. * @property {boolean} [depth=true] - Whether the default framebuffer should have a depth buffer or not.
  55239. * @property {boolean} [stencil=false] - Whether the default framebuffer should have a stencil buffer or not.
  55240. * @property {boolean} [antialias=false] - Whether MSAA as the default anti-aliasing should be enabled or not.
  55241. * @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.
  55242. * @property {boolean} [forceWebGL=false] - If set to `true`, the renderer uses a WebGL 2 backend no matter if WebGPU is supported or not.
  55243. * @property {boolean} [trackTimestamp=false] - Whether to track timestamps with a Timestamp Query API or not.
  55244. * @property {string} [powerPreference=undefined] - The power preference.
  55245. * @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.
  55246. * @property {GPUDevice} [device=undefined] - If there is an existing GPU device on app level, it can be passed to the renderer as a parameter.
  55247. * @property {number} [outputType=undefined] - Texture type for output to canvas. By default, device's preferred format is used; other formats may incur overhead.
  55248. */
  55249. /**
  55250. * Constructs a new WebGPU backend.
  55251. *
  55252. * @param {WebGPUBackend~Options} [parameters] - The configuration parameter.
  55253. */
  55254. constructor( parameters = {} ) {
  55255. super( parameters );
  55256. /**
  55257. * This flag can be used for type testing.
  55258. *
  55259. * @type {boolean}
  55260. * @readonly
  55261. * @default true
  55262. */
  55263. this.isWebGPUBackend = true;
  55264. // some parameters require default values other than "undefined"
  55265. this.parameters.alpha = ( parameters.alpha === undefined ) ? true : parameters.alpha;
  55266. this.parameters.compatibilityMode = ( parameters.compatibilityMode === undefined ) ? false : parameters.compatibilityMode;
  55267. this.parameters.requiredLimits = ( parameters.requiredLimits === undefined ) ? {} : parameters.requiredLimits;
  55268. /**
  55269. * Indicates whether the backend is in compatibility mode or not.
  55270. * @type {boolean}
  55271. * @default false
  55272. */
  55273. this.compatibilityMode = this.parameters.compatibilityMode;
  55274. /**
  55275. * A reference to the device.
  55276. *
  55277. * @type {?GPUDevice}
  55278. * @default null
  55279. */
  55280. this.device = null;
  55281. /**
  55282. * A reference to the default render pass descriptor.
  55283. *
  55284. * @type {?Object}
  55285. * @default null
  55286. */
  55287. this.defaultRenderPassdescriptor = null;
  55288. /**
  55289. * A reference to a backend module holding common utility functions.
  55290. *
  55291. * @type {WebGPUUtils}
  55292. */
  55293. this.utils = new WebGPUUtils( this );
  55294. /**
  55295. * A reference to a backend module holding shader attribute-related
  55296. * utility functions.
  55297. *
  55298. * @type {WebGPUAttributeUtils}
  55299. */
  55300. this.attributeUtils = new WebGPUAttributeUtils( this );
  55301. /**
  55302. * A reference to a backend module holding shader binding-related
  55303. * utility functions.
  55304. *
  55305. * @type {WebGPUBindingUtils}
  55306. */
  55307. this.bindingUtils = new WebGPUBindingUtils( this );
  55308. /**
  55309. * A reference to a backend module holding shader pipeline-related
  55310. * utility functions.
  55311. *
  55312. * @type {WebGPUPipelineUtils}
  55313. */
  55314. this.pipelineUtils = new WebGPUPipelineUtils( this );
  55315. /**
  55316. * A reference to a backend module holding shader texture-related
  55317. * utility functions.
  55318. *
  55319. * @type {WebGPUTextureUtils}
  55320. */
  55321. this.textureUtils = new WebGPUTextureUtils( this );
  55322. /**
  55323. * A map that manages the resolve buffers for occlusion queries.
  55324. *
  55325. * @type {Map<number,GPUBuffer>}
  55326. */
  55327. this.occludedResolveCache = new Map();
  55328. }
  55329. /**
  55330. * Initializes the backend so it is ready for usage.
  55331. *
  55332. * @async
  55333. * @param {Renderer} renderer - The renderer.
  55334. * @return {Promise} A Promise that resolves when the backend has been initialized.
  55335. */
  55336. async init( renderer ) {
  55337. await super.init( renderer );
  55338. //
  55339. const parameters = this.parameters;
  55340. // create the device if it is not passed with parameters
  55341. let device;
  55342. if ( parameters.device === undefined ) {
  55343. const adapterOptions = {
  55344. powerPreference: parameters.powerPreference,
  55345. featureLevel: parameters.compatibilityMode ? 'compatibility' : undefined
  55346. };
  55347. const adapter = ( typeof navigator !== 'undefined' ) ? await navigator.gpu.requestAdapter( adapterOptions ) : null;
  55348. if ( adapter === null ) {
  55349. throw new Error( 'WebGPUBackend: Unable to create WebGPU adapter.' );
  55350. }
  55351. // feature support
  55352. const features = Object.values( GPUFeatureName );
  55353. const supportedFeatures = [];
  55354. for ( const name of features ) {
  55355. if ( adapter.features.has( name ) ) {
  55356. supportedFeatures.push( name );
  55357. }
  55358. }
  55359. const deviceDescriptor = {
  55360. requiredFeatures: supportedFeatures,
  55361. requiredLimits: parameters.requiredLimits
  55362. };
  55363. device = await adapter.requestDevice( deviceDescriptor );
  55364. } else {
  55365. device = parameters.device;
  55366. }
  55367. device.lost.then( ( info ) => {
  55368. if ( info.reason === 'destroyed' ) return;
  55369. const deviceLossInfo = {
  55370. api: 'WebGPU',
  55371. message: info.message || 'Unknown reason',
  55372. reason: info.reason || null,
  55373. originalEvent: info
  55374. };
  55375. renderer.onDeviceLost( deviceLossInfo );
  55376. } );
  55377. this.device = device;
  55378. this.trackTimestamp = this.trackTimestamp && this.hasFeature( GPUFeatureName.TimestampQuery );
  55379. this.updateSize();
  55380. }
  55381. /**
  55382. * A reference to the context.
  55383. *
  55384. * @type {?GPUCanvasContext}
  55385. * @default null
  55386. */
  55387. get context() {
  55388. const canvasTarget = this.renderer.getCanvasTarget();
  55389. const canvasData = this.get( canvasTarget );
  55390. let context = canvasData.context;
  55391. if ( context === undefined ) {
  55392. const parameters = this.parameters;
  55393. if ( canvasTarget.isDefaultCanvasTarget === true && parameters.context !== undefined ) {
  55394. context = parameters.context;
  55395. } else {
  55396. context = canvasTarget.domElement.getContext( 'webgpu' );
  55397. }
  55398. // OffscreenCanvas does not have setAttribute, see #22811
  55399. if ( 'setAttribute' in canvasTarget.domElement ) canvasTarget.domElement.setAttribute( 'data-engine', `three.js r${ REVISION } webgpu` );
  55400. const alphaMode = parameters.alpha ? 'premultiplied' : 'opaque';
  55401. const toneMappingMode = parameters.outputType === HalfFloatType ? 'extended' : 'standard';
  55402. context.configure( {
  55403. device: this.device,
  55404. format: this.utils.getPreferredCanvasFormat(),
  55405. usage: GPUTextureUsage.RENDER_ATTACHMENT | GPUTextureUsage.COPY_SRC,
  55406. alphaMode: alphaMode,
  55407. toneMapping: {
  55408. mode: toneMappingMode
  55409. }
  55410. } );
  55411. canvasData.context = context;
  55412. }
  55413. return context;
  55414. }
  55415. /**
  55416. * The coordinate system of the backend.
  55417. *
  55418. * @type {number}
  55419. * @readonly
  55420. */
  55421. get coordinateSystem() {
  55422. return WebGPUCoordinateSystem;
  55423. }
  55424. /**
  55425. * This method performs a readback operation by moving buffer data from
  55426. * a storage buffer attribute from the GPU to the CPU.
  55427. *
  55428. * @async
  55429. * @param {StorageBufferAttribute} attribute - The storage buffer attribute.
  55430. * @return {Promise<ArrayBuffer>} A promise that resolves with the buffer data when the data are ready.
  55431. */
  55432. async getArrayBufferAsync( attribute ) {
  55433. return await this.attributeUtils.getArrayBufferAsync( attribute );
  55434. }
  55435. /**
  55436. * Returns the backend's rendering context.
  55437. *
  55438. * @return {GPUCanvasContext} The rendering context.
  55439. */
  55440. getContext() {
  55441. return this.context;
  55442. }
  55443. /**
  55444. * Returns the default render pass descriptor.
  55445. *
  55446. * In WebGPU, the default framebuffer must be configured
  55447. * like custom framebuffers so the backend needs a render
  55448. * pass descriptor even when rendering directly to screen.
  55449. *
  55450. * @private
  55451. * @return {Object} The render pass descriptor.
  55452. */
  55453. _getDefaultRenderPassDescriptor() {
  55454. const renderer = this.renderer;
  55455. const canvasTarget = renderer.getCanvasTarget();
  55456. const canvasData = this.get( canvasTarget );
  55457. const samples = renderer.currentSamples;
  55458. let descriptor = canvasData.descriptor;
  55459. if ( descriptor === undefined || canvasData.samples !== samples ) {
  55460. descriptor = {
  55461. colorAttachments: [ {
  55462. view: null
  55463. } ]
  55464. };
  55465. if ( renderer.depth === true || renderer.stencil === true ) {
  55466. descriptor.depthStencilAttachment = {
  55467. view: this.textureUtils.getDepthBuffer( renderer.depth, renderer.stencil ).createView()
  55468. };
  55469. }
  55470. const colorAttachment = descriptor.colorAttachments[ 0 ];
  55471. if ( samples > 0 ) {
  55472. colorAttachment.view = this.textureUtils.getColorBuffer().createView();
  55473. } else {
  55474. colorAttachment.resolveTarget = undefined;
  55475. }
  55476. canvasData.descriptor = descriptor;
  55477. canvasData.samples = samples;
  55478. }
  55479. const colorAttachment = descriptor.colorAttachments[ 0 ];
  55480. if ( samples > 0 ) {
  55481. colorAttachment.resolveTarget = this.context.getCurrentTexture().createView();
  55482. } else {
  55483. colorAttachment.view = this.context.getCurrentTexture().createView();
  55484. }
  55485. return descriptor;
  55486. }
  55487. /**
  55488. * Internal to determine if the current render target is a render target array with depth 2D array texture.
  55489. *
  55490. * @param {RenderContext} renderContext - The render context.
  55491. * @return {boolean} Whether the render target is a render target array with depth 2D array texture.
  55492. *
  55493. * @private
  55494. */
  55495. _isRenderCameraDepthArray( renderContext ) {
  55496. return renderContext.depthTexture && renderContext.depthTexture.image.depth > 1 && renderContext.camera.isArrayCamera;
  55497. }
  55498. /**
  55499. * Returns the render pass descriptor for the given render context.
  55500. *
  55501. * @private
  55502. * @param {RenderContext} renderContext - The render context.
  55503. * @param {Object} colorAttachmentsConfig - Configuration object for the color attachments.
  55504. * @return {Object} The render pass descriptor.
  55505. */
  55506. _getRenderPassDescriptor( renderContext, colorAttachmentsConfig = {} ) {
  55507. const renderTarget = renderContext.renderTarget;
  55508. const renderTargetData = this.get( renderTarget );
  55509. let descriptors = renderTargetData.descriptors;
  55510. if ( descriptors === undefined ||
  55511. renderTargetData.width !== renderTarget.width ||
  55512. renderTargetData.height !== renderTarget.height ||
  55513. renderTargetData.samples !== renderTarget.samples
  55514. ) {
  55515. descriptors = {};
  55516. renderTargetData.descriptors = descriptors;
  55517. }
  55518. const cacheKey = renderContext.getCacheKey();
  55519. let descriptorBase = descriptors[ cacheKey ];
  55520. if ( descriptorBase === undefined ) {
  55521. const textures = renderContext.textures;
  55522. const textureViews = [];
  55523. let sliceIndex;
  55524. const isRenderCameraDepthArray = this._isRenderCameraDepthArray( renderContext );
  55525. for ( let i = 0; i < textures.length; i ++ ) {
  55526. const textureData = this.get( textures[ i ] );
  55527. const viewDescriptor = {
  55528. label: `colorAttachment_${ i }`,
  55529. baseMipLevel: renderContext.activeMipmapLevel,
  55530. mipLevelCount: 1,
  55531. baseArrayLayer: renderContext.activeCubeFace,
  55532. arrayLayerCount: 1,
  55533. dimension: GPUTextureViewDimension.TwoD
  55534. };
  55535. if ( renderTarget.isRenderTarget3D ) {
  55536. sliceIndex = renderContext.activeCubeFace;
  55537. viewDescriptor.baseArrayLayer = 0;
  55538. viewDescriptor.dimension = GPUTextureViewDimension.ThreeD;
  55539. viewDescriptor.depthOrArrayLayers = textures[ i ].image.depth;
  55540. } else if ( renderTarget.isRenderTarget && textures[ i ].image.depth > 1 ) {
  55541. if ( isRenderCameraDepthArray === true ) {
  55542. const cameras = renderContext.camera.cameras;
  55543. for ( let layer = 0; layer < cameras.length; layer ++ ) {
  55544. const layerViewDescriptor = {
  55545. ...viewDescriptor,
  55546. baseArrayLayer: layer,
  55547. arrayLayerCount: 1,
  55548. dimension: GPUTextureViewDimension.TwoD
  55549. };
  55550. const textureView = textureData.texture.createView( layerViewDescriptor );
  55551. textureViews.push( {
  55552. view: textureView,
  55553. resolveTarget: undefined,
  55554. depthSlice: undefined
  55555. } );
  55556. }
  55557. } else {
  55558. viewDescriptor.dimension = GPUTextureViewDimension.TwoDArray;
  55559. viewDescriptor.depthOrArrayLayers = textures[ i ].image.depth;
  55560. }
  55561. }
  55562. if ( isRenderCameraDepthArray !== true ) {
  55563. const textureView = textureData.texture.createView( viewDescriptor );
  55564. let view, resolveTarget;
  55565. if ( textureData.msaaTexture !== undefined ) {
  55566. view = textureData.msaaTexture.createView();
  55567. resolveTarget = textureView;
  55568. } else {
  55569. view = textureView;
  55570. resolveTarget = undefined;
  55571. }
  55572. textureViews.push( {
  55573. view,
  55574. resolveTarget,
  55575. depthSlice: sliceIndex
  55576. } );
  55577. }
  55578. }
  55579. descriptorBase = { textureViews };
  55580. if ( renderContext.depth ) {
  55581. const depthTextureData = this.get( renderContext.depthTexture );
  55582. const options = {};
  55583. if ( renderContext.depthTexture.isArrayTexture || renderContext.depthTexture.isCubeTexture ) {
  55584. options.dimension = GPUTextureViewDimension.TwoD;
  55585. options.arrayLayerCount = 1;
  55586. options.baseArrayLayer = renderContext.activeCubeFace;
  55587. }
  55588. descriptorBase.depthStencilView = depthTextureData.texture.createView( options );
  55589. }
  55590. descriptors[ cacheKey ] = descriptorBase;
  55591. renderTargetData.width = renderTarget.width;
  55592. renderTargetData.height = renderTarget.height;
  55593. renderTargetData.samples = renderTarget.samples;
  55594. renderTargetData.activeMipmapLevel = renderContext.activeMipmapLevel;
  55595. renderTargetData.activeCubeFace = renderContext.activeCubeFace;
  55596. }
  55597. const descriptor = {
  55598. colorAttachments: []
  55599. };
  55600. // Apply dynamic properties to cached views
  55601. for ( let i = 0; i < descriptorBase.textureViews.length; i ++ ) {
  55602. const viewInfo = descriptorBase.textureViews[ i ];
  55603. let clearValue = { r: 0, g: 0, b: 0, a: 1 };
  55604. if ( i === 0 && colorAttachmentsConfig.clearValue ) {
  55605. clearValue = colorAttachmentsConfig.clearValue;
  55606. }
  55607. descriptor.colorAttachments.push( {
  55608. view: viewInfo.view,
  55609. depthSlice: viewInfo.depthSlice,
  55610. resolveTarget: viewInfo.resolveTarget,
  55611. loadOp: colorAttachmentsConfig.loadOp || GPULoadOp.Load,
  55612. storeOp: colorAttachmentsConfig.storeOp || GPUStoreOp.Store,
  55613. clearValue: clearValue
  55614. } );
  55615. }
  55616. if ( descriptorBase.depthStencilView ) {
  55617. descriptor.depthStencilAttachment = {
  55618. view: descriptorBase.depthStencilView
  55619. };
  55620. }
  55621. return descriptor;
  55622. }
  55623. /**
  55624. * This method is executed at the beginning of a render call and prepares
  55625. * the WebGPU state for upcoming render calls
  55626. *
  55627. * @param {RenderContext} renderContext - The render context.
  55628. */
  55629. beginRender( renderContext ) {
  55630. const renderContextData = this.get( renderContext );
  55631. //
  55632. const device = this.device;
  55633. const occlusionQueryCount = renderContext.occlusionQueryCount;
  55634. let occlusionQuerySet;
  55635. if ( occlusionQueryCount > 0 ) {
  55636. if ( renderContextData.currentOcclusionQuerySet ) renderContextData.currentOcclusionQuerySet.destroy();
  55637. if ( renderContextData.currentOcclusionQueryBuffer ) renderContextData.currentOcclusionQueryBuffer.destroy();
  55638. // Get a reference to the array of objects with queries. The renderContextData property
  55639. // can be changed by another render pass before the buffer.mapAsyc() completes.
  55640. renderContextData.currentOcclusionQuerySet = renderContextData.occlusionQuerySet;
  55641. renderContextData.currentOcclusionQueryBuffer = renderContextData.occlusionQueryBuffer;
  55642. renderContextData.currentOcclusionQueryObjects = renderContextData.occlusionQueryObjects;
  55643. //
  55644. occlusionQuerySet = device.createQuerySet( { type: 'occlusion', count: occlusionQueryCount, label: `occlusionQuerySet_${ renderContext.id }` } );
  55645. renderContextData.occlusionQuerySet = occlusionQuerySet;
  55646. renderContextData.occlusionQueryIndex = 0;
  55647. renderContextData.occlusionQueryObjects = new Array( occlusionQueryCount );
  55648. renderContextData.lastOcclusionObject = null;
  55649. }
  55650. let descriptor;
  55651. if ( renderContext.textures === null ) {
  55652. descriptor = this._getDefaultRenderPassDescriptor();
  55653. } else {
  55654. descriptor = this._getRenderPassDescriptor( renderContext, { loadOp: GPULoadOp.Load } );
  55655. }
  55656. this.initTimestampQuery( TimestampQuery.RENDER, this.getTimestampUID( renderContext ), descriptor );
  55657. descriptor.occlusionQuerySet = occlusionQuerySet;
  55658. const depthStencilAttachment = descriptor.depthStencilAttachment;
  55659. if ( renderContext.textures !== null ) {
  55660. const colorAttachments = descriptor.colorAttachments;
  55661. for ( let i = 0; i < colorAttachments.length; i ++ ) {
  55662. const colorAttachment = colorAttachments[ i ];
  55663. if ( renderContext.clearColor ) {
  55664. colorAttachment.clearValue = i === 0 ? renderContext.clearColorValue : { r: 0, g: 0, b: 0, a: 1 };
  55665. colorAttachment.loadOp = GPULoadOp.Clear;
  55666. } else {
  55667. colorAttachment.loadOp = GPULoadOp.Load;
  55668. }
  55669. colorAttachment.storeOp = GPUStoreOp.Store;
  55670. }
  55671. } else {
  55672. const colorAttachment = descriptor.colorAttachments[ 0 ];
  55673. if ( renderContext.clearColor ) {
  55674. colorAttachment.clearValue = renderContext.clearColorValue;
  55675. colorAttachment.loadOp = GPULoadOp.Clear;
  55676. } else {
  55677. colorAttachment.loadOp = GPULoadOp.Load;
  55678. }
  55679. colorAttachment.storeOp = GPUStoreOp.Store;
  55680. }
  55681. //
  55682. if ( renderContext.depth ) {
  55683. if ( renderContext.clearDepth ) {
  55684. depthStencilAttachment.depthClearValue = renderContext.clearDepthValue;
  55685. depthStencilAttachment.depthLoadOp = GPULoadOp.Clear;
  55686. } else {
  55687. depthStencilAttachment.depthLoadOp = GPULoadOp.Load;
  55688. }
  55689. depthStencilAttachment.depthStoreOp = GPUStoreOp.Store;
  55690. }
  55691. if ( renderContext.stencil ) {
  55692. if ( renderContext.clearStencil ) {
  55693. depthStencilAttachment.stencilClearValue = renderContext.clearStencilValue;
  55694. depthStencilAttachment.stencilLoadOp = GPULoadOp.Clear;
  55695. } else {
  55696. depthStencilAttachment.stencilLoadOp = GPULoadOp.Load;
  55697. }
  55698. depthStencilAttachment.stencilStoreOp = GPUStoreOp.Store;
  55699. }
  55700. //
  55701. const encoder = device.createCommandEncoder( { label: 'renderContext_' + renderContext.id } );
  55702. // shadow arrays - prepare bundle encoders for each camera in an array camera
  55703. if ( this._isRenderCameraDepthArray( renderContext ) === true ) {
  55704. const cameras = renderContext.camera.cameras;
  55705. if ( ! renderContextData.layerDescriptors || renderContextData.layerDescriptors.length !== cameras.length ) {
  55706. this._createDepthLayerDescriptors( renderContext, renderContextData, descriptor, cameras );
  55707. } else {
  55708. this._updateDepthLayerDescriptors( renderContext, renderContextData, cameras );
  55709. }
  55710. // Create bundle encoders for each layer
  55711. renderContextData.bundleEncoders = [];
  55712. renderContextData.bundleSets = [];
  55713. // Create separate bundle encoders for each camera in the array
  55714. for ( let i = 0; i < cameras.length; i ++ ) {
  55715. const bundleEncoder = this.pipelineUtils.createBundleEncoder(
  55716. renderContext,
  55717. 'renderBundleArrayCamera_' + i
  55718. );
  55719. // Initialize state tracking for this bundle
  55720. const bundleSets = {
  55721. attributes: {},
  55722. bindingGroups: [],
  55723. pipeline: null,
  55724. index: null
  55725. };
  55726. renderContextData.bundleEncoders.push( bundleEncoder );
  55727. renderContextData.bundleSets.push( bundleSets );
  55728. }
  55729. // We'll complete the bundles in finishRender
  55730. renderContextData.currentPass = null;
  55731. } else {
  55732. const currentPass = encoder.beginRenderPass( descriptor );
  55733. renderContextData.currentPass = currentPass;
  55734. if ( renderContext.viewport ) {
  55735. this.updateViewport( renderContext );
  55736. }
  55737. if ( renderContext.scissor ) {
  55738. this.updateScissor( renderContext );
  55739. }
  55740. }
  55741. //
  55742. renderContextData.descriptor = descriptor;
  55743. renderContextData.encoder = encoder;
  55744. renderContextData.currentSets = { attributes: {}, bindingGroups: [], pipeline: null, index: null };
  55745. renderContextData.renderBundles = [];
  55746. }
  55747. /**
  55748. * This method creates layer descriptors for each camera in an array camera
  55749. * to prepare for rendering to a depth array texture.
  55750. *
  55751. * @param {RenderContext} renderContext - The render context.
  55752. * @param {Object} renderContextData - The render context data.
  55753. * @param {Object} descriptor - The render pass descriptor.
  55754. * @param {ArrayCamera} cameras - The array camera.
  55755. *
  55756. * @private
  55757. */
  55758. _createDepthLayerDescriptors( renderContext, renderContextData, descriptor, cameras ) {
  55759. const depthStencilAttachment = descriptor.depthStencilAttachment;
  55760. renderContextData.layerDescriptors = [];
  55761. const depthTextureData = this.get( renderContext.depthTexture );
  55762. if ( ! depthTextureData.viewCache ) {
  55763. depthTextureData.viewCache = [];
  55764. }
  55765. for ( let i = 0; i < cameras.length; i ++ ) {
  55766. const layerDescriptor = {
  55767. ...descriptor,
  55768. colorAttachments: [ {
  55769. ...descriptor.colorAttachments[ 0 ],
  55770. view: descriptor.colorAttachments[ i ].view
  55771. } ]
  55772. };
  55773. if ( descriptor.depthStencilAttachment ) {
  55774. const layerIndex = i;
  55775. if ( ! depthTextureData.viewCache[ layerIndex ] ) {
  55776. depthTextureData.viewCache[ layerIndex ] = depthTextureData.texture.createView( {
  55777. dimension: GPUTextureViewDimension.TwoD,
  55778. baseArrayLayer: i,
  55779. arrayLayerCount: 1
  55780. } );
  55781. }
  55782. layerDescriptor.depthStencilAttachment = {
  55783. view: depthTextureData.viewCache[ layerIndex ],
  55784. depthLoadOp: depthStencilAttachment.depthLoadOp || GPULoadOp.Clear,
  55785. depthStoreOp: depthStencilAttachment.depthStoreOp || GPUStoreOp.Store,
  55786. depthClearValue: depthStencilAttachment.depthClearValue || 1.0
  55787. };
  55788. if ( renderContext.stencil ) {
  55789. layerDescriptor.depthStencilAttachment.stencilLoadOp = depthStencilAttachment.stencilLoadOp;
  55790. layerDescriptor.depthStencilAttachment.stencilStoreOp = depthStencilAttachment.stencilStoreOp;
  55791. layerDescriptor.depthStencilAttachment.stencilClearValue = depthStencilAttachment.stencilClearValue;
  55792. }
  55793. } else {
  55794. layerDescriptor.depthStencilAttachment = { ...depthStencilAttachment };
  55795. }
  55796. renderContextData.layerDescriptors.push( layerDescriptor );
  55797. }
  55798. }
  55799. /**
  55800. * This method updates the layer descriptors for each camera in an array camera
  55801. * to prepare for rendering to a depth array texture.
  55802. *
  55803. * @param {RenderContext} renderContext - The render context.
  55804. * @param {Object} renderContextData - The render context data.
  55805. * @param {ArrayCamera} cameras - The array camera.
  55806. *
  55807. */
  55808. _updateDepthLayerDescriptors( renderContext, renderContextData, cameras ) {
  55809. for ( let i = 0; i < cameras.length; i ++ ) {
  55810. const layerDescriptor = renderContextData.layerDescriptors[ i ];
  55811. if ( layerDescriptor.depthStencilAttachment ) {
  55812. const depthAttachment = layerDescriptor.depthStencilAttachment;
  55813. if ( renderContext.depth ) {
  55814. if ( renderContext.clearDepth ) {
  55815. depthAttachment.depthClearValue = renderContext.clearDepthValue;
  55816. depthAttachment.depthLoadOp = GPULoadOp.Clear;
  55817. } else {
  55818. depthAttachment.depthLoadOp = GPULoadOp.Load;
  55819. }
  55820. }
  55821. if ( renderContext.stencil ) {
  55822. if ( renderContext.clearStencil ) {
  55823. depthAttachment.stencilClearValue = renderContext.clearStencilValue;
  55824. depthAttachment.stencilLoadOp = GPULoadOp.Clear;
  55825. } else {
  55826. depthAttachment.stencilLoadOp = GPULoadOp.Load;
  55827. }
  55828. }
  55829. }
  55830. }
  55831. }
  55832. /**
  55833. * This method is executed at the end of a render call and finalizes work
  55834. * after draw calls.
  55835. *
  55836. * @param {RenderContext} renderContext - The render context.
  55837. */
  55838. finishRender( renderContext ) {
  55839. const renderContextData = this.get( renderContext );
  55840. const occlusionQueryCount = renderContext.occlusionQueryCount;
  55841. if ( renderContextData.renderBundles.length > 0 ) {
  55842. renderContextData.currentPass.executeBundles( renderContextData.renderBundles );
  55843. }
  55844. if ( occlusionQueryCount > renderContextData.occlusionQueryIndex ) {
  55845. renderContextData.currentPass.endOcclusionQuery();
  55846. }
  55847. // shadow arrays - Execute bundles for each layer
  55848. const encoder = renderContextData.encoder;
  55849. if ( this._isRenderCameraDepthArray( renderContext ) === true ) {
  55850. const bundles = [];
  55851. for ( let i = 0; i < renderContextData.bundleEncoders.length; i ++ ) {
  55852. const bundleEncoder = renderContextData.bundleEncoders[ i ];
  55853. bundles.push( bundleEncoder.finish() );
  55854. }
  55855. for ( let i = 0; i < renderContextData.layerDescriptors.length; i ++ ) {
  55856. if ( i < bundles.length ) {
  55857. const layerDescriptor = renderContextData.layerDescriptors[ i ];
  55858. const renderPass = encoder.beginRenderPass( layerDescriptor );
  55859. if ( renderContext.viewport ) {
  55860. const { x, y, width, height, minDepth, maxDepth } = renderContext.viewportValue;
  55861. renderPass.setViewport( x, y, width, height, minDepth, maxDepth );
  55862. }
  55863. if ( renderContext.scissor ) {
  55864. const { x, y, width, height } = renderContext.scissorValue;
  55865. renderPass.setScissorRect( x, y, width, height );
  55866. }
  55867. renderPass.executeBundles( [ bundles[ i ] ] );
  55868. renderPass.end();
  55869. }
  55870. }
  55871. } else if ( renderContextData.currentPass ) {
  55872. renderContextData.currentPass.end();
  55873. }
  55874. if ( occlusionQueryCount > 0 ) {
  55875. const bufferSize = occlusionQueryCount * 8; // 8 byte entries for query results
  55876. //
  55877. let queryResolveBuffer = this.occludedResolveCache.get( bufferSize );
  55878. if ( queryResolveBuffer === undefined ) {
  55879. queryResolveBuffer = this.device.createBuffer(
  55880. {
  55881. size: bufferSize,
  55882. usage: GPUBufferUsage.QUERY_RESOLVE | GPUBufferUsage.COPY_SRC
  55883. }
  55884. );
  55885. this.occludedResolveCache.set( bufferSize, queryResolveBuffer );
  55886. }
  55887. //
  55888. const readBuffer = this.device.createBuffer(
  55889. {
  55890. size: bufferSize,
  55891. usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ
  55892. }
  55893. );
  55894. // two buffers required here - WebGPU doesn't allow usage of QUERY_RESOLVE & MAP_READ to be combined
  55895. renderContextData.encoder.resolveQuerySet( renderContextData.occlusionQuerySet, 0, occlusionQueryCount, queryResolveBuffer, 0 );
  55896. renderContextData.encoder.copyBufferToBuffer( queryResolveBuffer, 0, readBuffer, 0, bufferSize );
  55897. renderContextData.occlusionQueryBuffer = readBuffer;
  55898. //
  55899. this.resolveOccludedAsync( renderContext );
  55900. }
  55901. this.device.queue.submit( [ renderContextData.encoder.finish() ] );
  55902. //
  55903. if ( renderContext.textures !== null ) {
  55904. const textures = renderContext.textures;
  55905. for ( let i = 0; i < textures.length; i ++ ) {
  55906. const texture = textures[ i ];
  55907. if ( texture.generateMipmaps === true ) {
  55908. this.textureUtils.generateMipmaps( texture );
  55909. }
  55910. }
  55911. }
  55912. }
  55913. /**
  55914. * Returns `true` if the given 3D object is fully occluded by other
  55915. * 3D objects in the scene.
  55916. *
  55917. * @param {RenderContext} renderContext - The render context.
  55918. * @param {Object3D} object - The 3D object to test.
  55919. * @return {boolean} Whether the 3D object is fully occluded or not.
  55920. */
  55921. isOccluded( renderContext, object ) {
  55922. const renderContextData = this.get( renderContext );
  55923. return renderContextData.occluded && renderContextData.occluded.has( object );
  55924. }
  55925. /**
  55926. * This method processes the result of occlusion queries and writes it
  55927. * into render context data.
  55928. *
  55929. * @async
  55930. * @param {RenderContext} renderContext - The render context.
  55931. * @return {Promise} A Promise that resolves when the occlusion query results have been processed.
  55932. */
  55933. async resolveOccludedAsync( renderContext ) {
  55934. const renderContextData = this.get( renderContext );
  55935. // handle occlusion query results
  55936. const { currentOcclusionQueryBuffer, currentOcclusionQueryObjects } = renderContextData;
  55937. if ( currentOcclusionQueryBuffer && currentOcclusionQueryObjects ) {
  55938. const occluded = new WeakSet();
  55939. renderContextData.currentOcclusionQueryObjects = null;
  55940. renderContextData.currentOcclusionQueryBuffer = null;
  55941. await currentOcclusionQueryBuffer.mapAsync( GPUMapMode.READ );
  55942. const buffer = currentOcclusionQueryBuffer.getMappedRange();
  55943. const results = new BigUint64Array( buffer );
  55944. for ( let i = 0; i < currentOcclusionQueryObjects.length; i ++ ) {
  55945. if ( results[ i ] === BigInt( 0 ) ) {
  55946. occluded.add( currentOcclusionQueryObjects[ i ] );
  55947. }
  55948. }
  55949. currentOcclusionQueryBuffer.destroy();
  55950. renderContextData.occluded = occluded;
  55951. }
  55952. }
  55953. /**
  55954. * Updates the viewport with the values from the given render context.
  55955. *
  55956. * @param {RenderContext} renderContext - The render context.
  55957. */
  55958. updateViewport( renderContext ) {
  55959. const { currentPass } = this.get( renderContext );
  55960. const { x, y, width, height, minDepth, maxDepth } = renderContext.viewportValue;
  55961. currentPass.setViewport( x, y, width, height, minDepth, maxDepth );
  55962. }
  55963. /**
  55964. * Updates the scissor with the values from the given render context.
  55965. *
  55966. * @param {RenderContext} renderContext - The render context.
  55967. */
  55968. updateScissor( renderContext ) {
  55969. const { currentPass } = this.get( renderContext );
  55970. const { x, y, width, height } = renderContext.scissorValue;
  55971. currentPass.setScissorRect( x, y, width, height );
  55972. }
  55973. /**
  55974. * Returns the clear color and alpha into a single
  55975. * color object.
  55976. *
  55977. * @return {Color4} The clear color.
  55978. */
  55979. getClearColor() {
  55980. const clearColor = super.getClearColor();
  55981. // only premultiply alpha when alphaMode is "premultiplied"
  55982. if ( this.renderer.alpha === true ) {
  55983. clearColor.r *= clearColor.a;
  55984. clearColor.g *= clearColor.a;
  55985. clearColor.b *= clearColor.a;
  55986. }
  55987. return clearColor;
  55988. }
  55989. /**
  55990. * Performs a clear operation.
  55991. *
  55992. * @param {boolean} color - Whether the color buffer should be cleared or not.
  55993. * @param {boolean} depth - Whether the depth buffer should be cleared or not.
  55994. * @param {boolean} stencil - Whether the stencil buffer should be cleared or not.
  55995. * @param {?RenderContext} [renderTargetContext=null] - The render context of the current set render target.
  55996. */
  55997. clear( color, depth, stencil, renderTargetContext = null ) {
  55998. const device = this.device;
  55999. const renderer = this.renderer;
  56000. let colorAttachments = [];
  56001. let depthStencilAttachment;
  56002. let clearValue;
  56003. let supportsDepth;
  56004. let supportsStencil;
  56005. if ( color ) {
  56006. const clearColor = this.getClearColor();
  56007. clearValue = { r: clearColor.r, g: clearColor.g, b: clearColor.b, a: clearColor.a };
  56008. }
  56009. if ( renderTargetContext === null ) {
  56010. supportsDepth = renderer.depth;
  56011. supportsStencil = renderer.stencil;
  56012. const descriptor = this._getDefaultRenderPassDescriptor();
  56013. if ( color ) {
  56014. colorAttachments = descriptor.colorAttachments;
  56015. const colorAttachment = colorAttachments[ 0 ];
  56016. colorAttachment.clearValue = clearValue;
  56017. colorAttachment.loadOp = GPULoadOp.Clear;
  56018. colorAttachment.storeOp = GPUStoreOp.Store;
  56019. }
  56020. if ( supportsDepth || supportsStencil ) {
  56021. depthStencilAttachment = descriptor.depthStencilAttachment;
  56022. }
  56023. } else {
  56024. supportsDepth = renderTargetContext.depth;
  56025. supportsStencil = renderTargetContext.stencil;
  56026. const clearConfig = {
  56027. loadOp: color ? GPULoadOp.Clear : GPULoadOp.Load,
  56028. clearValue: color ? clearValue : undefined
  56029. };
  56030. if ( supportsDepth ) {
  56031. clearConfig.depthLoadOp = depth ? GPULoadOp.Clear : GPULoadOp.Load;
  56032. clearConfig.depthClearValue = depth ? renderer.getClearDepth() : undefined;
  56033. clearConfig.depthStoreOp = GPUStoreOp.Store;
  56034. }
  56035. if ( supportsStencil ) {
  56036. clearConfig.stencilLoadOp = stencil ? GPULoadOp.Clear : GPULoadOp.Load;
  56037. clearConfig.stencilClearValue = stencil ? renderer.getClearStencil() : undefined;
  56038. clearConfig.stencilStoreOp = GPUStoreOp.Store;
  56039. }
  56040. const descriptor = this._getRenderPassDescriptor( renderTargetContext, clearConfig );
  56041. colorAttachments = descriptor.colorAttachments;
  56042. depthStencilAttachment = descriptor.depthStencilAttachment;
  56043. }
  56044. if ( supportsDepth && depthStencilAttachment ) {
  56045. if ( depth ) {
  56046. depthStencilAttachment.depthLoadOp = GPULoadOp.Clear;
  56047. depthStencilAttachment.depthClearValue = renderer.getClearDepth();
  56048. depthStencilAttachment.depthStoreOp = GPUStoreOp.Store;
  56049. } else {
  56050. depthStencilAttachment.depthLoadOp = GPULoadOp.Load;
  56051. depthStencilAttachment.depthStoreOp = GPUStoreOp.Store;
  56052. }
  56053. }
  56054. //
  56055. if ( supportsStencil && depthStencilAttachment ) {
  56056. if ( stencil ) {
  56057. depthStencilAttachment.stencilLoadOp = GPULoadOp.Clear;
  56058. depthStencilAttachment.stencilClearValue = renderer.getClearStencil();
  56059. depthStencilAttachment.stencilStoreOp = GPUStoreOp.Store;
  56060. } else {
  56061. depthStencilAttachment.stencilLoadOp = GPULoadOp.Load;
  56062. depthStencilAttachment.stencilStoreOp = GPUStoreOp.Store;
  56063. }
  56064. }
  56065. //
  56066. const encoder = device.createCommandEncoder( { label: 'clear' } );
  56067. const currentPass = encoder.beginRenderPass( {
  56068. colorAttachments,
  56069. depthStencilAttachment
  56070. } );
  56071. currentPass.end();
  56072. device.queue.submit( [ encoder.finish() ] );
  56073. }
  56074. // compute
  56075. /**
  56076. * This method is executed at the beginning of a compute call and
  56077. * prepares the state for upcoming compute tasks.
  56078. *
  56079. * @param {Node|Array<Node>} computeGroup - The compute node(s).
  56080. */
  56081. beginCompute( computeGroup ) {
  56082. const groupGPU = this.get( computeGroup );
  56083. //
  56084. const descriptor = {
  56085. label: 'computeGroup_' + computeGroup.id
  56086. };
  56087. this.initTimestampQuery( TimestampQuery.COMPUTE, this.getTimestampUID( computeGroup ), descriptor );
  56088. groupGPU.cmdEncoderGPU = this.device.createCommandEncoder( { label: 'computeGroup_' + computeGroup.id } );
  56089. groupGPU.passEncoderGPU = groupGPU.cmdEncoderGPU.beginComputePass( descriptor );
  56090. }
  56091. /**
  56092. * Executes a compute command for the given compute node.
  56093. *
  56094. * @param {Node|Array<Node>} computeGroup - The group of compute nodes of a compute call. Can be a single compute node.
  56095. * @param {Node} computeNode - The compute node.
  56096. * @param {Array<BindGroup>} bindings - The bindings.
  56097. * @param {ComputePipeline} pipeline - The compute pipeline.
  56098. * @param {number|Array<number>|IndirectStorageBufferAttribute} [dispatchSize=null]
  56099. * - A single number representing count, or
  56100. * - An array [x, y, z] representing dispatch size, or
  56101. * - A IndirectStorageBufferAttribute for indirect dispatch size.
  56102. */
  56103. compute( computeGroup, computeNode, bindings, pipeline, dispatchSize = null ) {
  56104. const computeNodeData = this.get( computeNode );
  56105. const { passEncoderGPU } = this.get( computeGroup );
  56106. // pipeline
  56107. const pipelineGPU = this.get( pipeline ).pipeline;
  56108. this.pipelineUtils.setPipeline( passEncoderGPU, pipelineGPU );
  56109. // bind groups
  56110. for ( let i = 0, l = bindings.length; i < l; i ++ ) {
  56111. const bindGroup = bindings[ i ];
  56112. const bindingsData = this.get( bindGroup );
  56113. passEncoderGPU.setBindGroup( i, bindingsData.group );
  56114. }
  56115. if ( dispatchSize === null ) {
  56116. dispatchSize = computeNode.count;
  56117. }
  56118. // When the dispatchSize is set with a StorageBuffer from the GPU.
  56119. if ( dispatchSize && typeof dispatchSize === 'object' && dispatchSize.isIndirectStorageBufferAttribute ) {
  56120. const dispatchBuffer = this.get( dispatchSize ).buffer;
  56121. passEncoderGPU.dispatchWorkgroupsIndirect( dispatchBuffer, 0 );
  56122. return;
  56123. }
  56124. if ( typeof dispatchSize === 'number' ) {
  56125. // If a single number is given, we calculate the dispatch size based on the workgroup size
  56126. const count = dispatchSize;
  56127. if ( computeNodeData.dispatchSize === undefined || computeNodeData.count !== count ) {
  56128. // cache dispatch size to avoid recalculating it every time
  56129. computeNodeData.dispatchSize = [ 0, 1, 1 ];
  56130. computeNodeData.count = count;
  56131. const workgroupSize = computeNode.workgroupSize;
  56132. let size = workgroupSize[ 0 ];
  56133. for ( let i = 1; i < workgroupSize.length; i ++ )
  56134. size *= workgroupSize[ i ];
  56135. const dispatchCount = Math.ceil( count / size );
  56136. //
  56137. const maxComputeWorkgroupsPerDimension = this.device.limits.maxComputeWorkgroupsPerDimension;
  56138. dispatchSize = [ dispatchCount, 1, 1 ];
  56139. if ( dispatchCount > maxComputeWorkgroupsPerDimension ) {
  56140. dispatchSize[ 0 ] = Math.min( dispatchCount, maxComputeWorkgroupsPerDimension );
  56141. dispatchSize[ 1 ] = Math.ceil( dispatchCount / maxComputeWorkgroupsPerDimension );
  56142. }
  56143. computeNodeData.dispatchSize = dispatchSize;
  56144. }
  56145. dispatchSize = computeNodeData.dispatchSize;
  56146. }
  56147. //
  56148. passEncoderGPU.dispatchWorkgroups(
  56149. dispatchSize[ 0 ],
  56150. dispatchSize[ 1 ] || 1,
  56151. dispatchSize[ 2 ] || 1
  56152. );
  56153. }
  56154. /**
  56155. * This method is executed at the end of a compute call and
  56156. * finalizes work after compute tasks.
  56157. *
  56158. * @param {Node|Array<Node>} computeGroup - The compute node(s).
  56159. */
  56160. finishCompute( computeGroup ) {
  56161. const groupData = this.get( computeGroup );
  56162. groupData.passEncoderGPU.end();
  56163. this.device.queue.submit( [ groupData.cmdEncoderGPU.finish() ] );
  56164. }
  56165. // render object
  56166. /**
  56167. * Executes a draw command for the given render object.
  56168. *
  56169. * @param {RenderObject} renderObject - The render object to draw.
  56170. * @param {Info} info - Holds a series of statistical information about the GPU memory and the rendering process.
  56171. */
  56172. draw( renderObject, info ) {
  56173. const { object, material, context, pipeline } = renderObject;
  56174. const bindings = renderObject.getBindings();
  56175. const renderContextData = this.get( context );
  56176. const pipelineData = this.get( pipeline );
  56177. const pipelineGPU = pipelineData.pipeline;
  56178. if ( pipelineData.error === true ) return;
  56179. const index = renderObject.getIndex();
  56180. const hasIndex = ( index !== null );
  56181. const drawParams = renderObject.getDrawParameters();
  56182. if ( drawParams === null ) return;
  56183. // pipeline
  56184. const setPipelineAndBindings = ( passEncoderGPU, currentSets ) => {
  56185. // pipeline
  56186. this.pipelineUtils.setPipeline( passEncoderGPU, pipelineGPU );
  56187. currentSets.pipeline = pipelineGPU;
  56188. // bind groups
  56189. const currentBindingGroups = currentSets.bindingGroups;
  56190. for ( let i = 0, l = bindings.length; i < l; i ++ ) {
  56191. const bindGroup = bindings[ i ];
  56192. const bindingsData = this.get( bindGroup );
  56193. if ( currentBindingGroups[ bindGroup.index ] !== bindGroup.id ) {
  56194. passEncoderGPU.setBindGroup( bindGroup.index, bindingsData.group );
  56195. currentBindingGroups[ bindGroup.index ] = bindGroup.id;
  56196. }
  56197. }
  56198. // attributes
  56199. // index
  56200. if ( hasIndex === true ) {
  56201. if ( currentSets.index !== index ) {
  56202. const buffer = this.get( index ).buffer;
  56203. const indexFormat = ( index.array instanceof Uint16Array ) ? GPUIndexFormat.Uint16 : GPUIndexFormat.Uint32;
  56204. passEncoderGPU.setIndexBuffer( buffer, indexFormat );
  56205. currentSets.index = index;
  56206. }
  56207. }
  56208. // vertex buffers
  56209. const vertexBuffers = renderObject.getVertexBuffers();
  56210. for ( let i = 0, l = vertexBuffers.length; i < l; i ++ ) {
  56211. const vertexBuffer = vertexBuffers[ i ];
  56212. if ( currentSets.attributes[ i ] !== vertexBuffer ) {
  56213. const buffer = this.get( vertexBuffer ).buffer;
  56214. passEncoderGPU.setVertexBuffer( i, buffer );
  56215. currentSets.attributes[ i ] = vertexBuffer;
  56216. }
  56217. }
  56218. // stencil
  56219. if ( context.stencil === true && material.stencilWrite === true && renderContextData.currentStencilRef !== material.stencilRef ) {
  56220. passEncoderGPU.setStencilReference( material.stencilRef );
  56221. renderContextData.currentStencilRef = material.stencilRef;
  56222. }
  56223. };
  56224. // Define draw function
  56225. const draw = ( passEncoderGPU, currentSets ) => {
  56226. setPipelineAndBindings( passEncoderGPU, currentSets );
  56227. if ( object.isBatchedMesh === true ) {
  56228. const starts = object._multiDrawStarts;
  56229. const counts = object._multiDrawCounts;
  56230. const drawCount = object._multiDrawCount;
  56231. const drawInstances = object._multiDrawInstances;
  56232. if ( drawInstances !== null ) {
  56233. // @deprecated, r174
  56234. warnOnce( 'WebGPUBackend: renderMultiDrawInstances has been deprecated and will be removed in r184. Append to renderMultiDraw arguments and use indirection.' );
  56235. }
  56236. for ( let i = 0; i < drawCount; i ++ ) {
  56237. const count = drawInstances ? drawInstances[ i ] : 1;
  56238. const firstInstance = count > 1 ? 0 : i;
  56239. if ( hasIndex === true ) {
  56240. passEncoderGPU.drawIndexed( counts[ i ], count, starts[ i ] / index.array.BYTES_PER_ELEMENT, 0, firstInstance );
  56241. } else {
  56242. passEncoderGPU.draw( counts[ i ], count, starts[ i ], firstInstance );
  56243. }
  56244. info.update( object, counts[ i ], count );
  56245. }
  56246. } else if ( hasIndex === true ) {
  56247. const { vertexCount: indexCount, instanceCount, firstVertex: firstIndex } = drawParams;
  56248. const indirect = renderObject.getIndirect();
  56249. if ( indirect !== null ) {
  56250. const buffer = this.get( indirect ).buffer;
  56251. const indirectOffset = renderObject.getIndirectOffset();
  56252. const indirectOffsets = Array.isArray( indirectOffset ) ? indirectOffset : [ indirectOffset ];
  56253. for ( let i = 0; i < indirectOffsets.length; i ++ ) {
  56254. passEncoderGPU.drawIndexedIndirect( buffer, indirectOffsets[ i ] );
  56255. }
  56256. } else {
  56257. passEncoderGPU.drawIndexed( indexCount, instanceCount, firstIndex, 0, 0 );
  56258. }
  56259. info.update( object, indexCount, instanceCount );
  56260. } else {
  56261. const { vertexCount, instanceCount, firstVertex } = drawParams;
  56262. const indirect = renderObject.getIndirect();
  56263. if ( indirect !== null ) {
  56264. const buffer = this.get( indirect ).buffer;
  56265. const indirectOffset = renderObject.getIndirectOffset();
  56266. const indirectOffsets = Array.isArray( indirectOffset ) ? indirectOffset : [ indirectOffset ];
  56267. for ( let i = 0; i < indirectOffsets.length; i ++ ) {
  56268. passEncoderGPU.drawIndirect( buffer, indirectOffsets[ i ] );
  56269. }
  56270. } else {
  56271. passEncoderGPU.draw( vertexCount, instanceCount, firstVertex, 0 );
  56272. }
  56273. info.update( object, vertexCount, instanceCount );
  56274. }
  56275. };
  56276. if ( renderObject.camera.isArrayCamera && renderObject.camera.cameras.length > 0 ) {
  56277. const cameraData = this.get( renderObject.camera );
  56278. const cameras = renderObject.camera.cameras;
  56279. const cameraIndex = renderObject.getBindingGroup( 'cameraIndex' );
  56280. if ( cameraData.indexesGPU === undefined || cameraData.indexesGPU.length !== cameras.length ) {
  56281. const bindingsData = this.get( cameraIndex );
  56282. const indexesGPU = [];
  56283. const data = new Uint32Array( [ 0, 0, 0, 0 ] );
  56284. for ( let i = 0, len = cameras.length; i < len; i ++ ) {
  56285. data[ 0 ] = i;
  56286. const { layoutGPU } = bindingsData.layout;
  56287. const bindGroupIndex = this.bindingUtils.createBindGroupIndex( data, layoutGPU );
  56288. indexesGPU.push( bindGroupIndex );
  56289. }
  56290. cameraData.indexesGPU = indexesGPU; // TODO: Create a global library for this
  56291. }
  56292. const pixelRatio = this.renderer.getPixelRatio();
  56293. for ( let i = 0, len = cameras.length; i < len; i ++ ) {
  56294. const subCamera = cameras[ i ];
  56295. if ( object.layers.test( subCamera.layers ) ) {
  56296. const vp = subCamera.viewport;
  56297. let pass = renderContextData.currentPass;
  56298. let sets = renderContextData.currentSets;
  56299. if ( renderContextData.bundleEncoders ) {
  56300. const bundleEncoder = renderContextData.bundleEncoders[ i ];
  56301. const bundleSets = renderContextData.bundleSets[ i ];
  56302. pass = bundleEncoder;
  56303. sets = bundleSets;
  56304. }
  56305. if ( vp ) {
  56306. pass.setViewport(
  56307. Math.floor( vp.x * pixelRatio ),
  56308. Math.floor( vp.y * pixelRatio ),
  56309. Math.floor( vp.width * pixelRatio ),
  56310. Math.floor( vp.height * pixelRatio ),
  56311. context.viewportValue.minDepth,
  56312. context.viewportValue.maxDepth
  56313. );
  56314. }
  56315. // Set camera index binding for this layer
  56316. if ( cameraIndex && cameraData.indexesGPU ) {
  56317. pass.setBindGroup( cameraIndex.index, cameraData.indexesGPU[ i ] );
  56318. sets.bindingGroups[ cameraIndex.index ] = cameraIndex.id;
  56319. }
  56320. draw( pass, sets );
  56321. }
  56322. }
  56323. } else {
  56324. // Regular single camera rendering
  56325. if ( renderContextData.currentPass ) {
  56326. // Handle occlusion queries
  56327. if ( renderContextData.occlusionQuerySet !== undefined ) {
  56328. const lastObject = renderContextData.lastOcclusionObject;
  56329. if ( lastObject !== object ) {
  56330. if ( lastObject !== null && lastObject.occlusionTest === true ) {
  56331. renderContextData.currentPass.endOcclusionQuery();
  56332. renderContextData.occlusionQueryIndex ++;
  56333. }
  56334. if ( object.occlusionTest === true ) {
  56335. renderContextData.currentPass.beginOcclusionQuery( renderContextData.occlusionQueryIndex );
  56336. renderContextData.occlusionQueryObjects[ renderContextData.occlusionQueryIndex ] = object;
  56337. }
  56338. renderContextData.lastOcclusionObject = object;
  56339. }
  56340. }
  56341. draw( renderContextData.currentPass, renderContextData.currentSets );
  56342. }
  56343. }
  56344. }
  56345. // cache key
  56346. /**
  56347. * Returns `true` if the render pipeline requires an update.
  56348. *
  56349. * @param {RenderObject} renderObject - The render object.
  56350. * @return {boolean} Whether the render pipeline requires an update or not.
  56351. */
  56352. needsRenderUpdate( renderObject ) {
  56353. const data = this.get( renderObject );
  56354. const { object, material } = renderObject;
  56355. const utils = this.utils;
  56356. const sampleCount = utils.getSampleCountRenderContext( renderObject.context );
  56357. const colorSpace = utils.getCurrentColorSpace( renderObject.context );
  56358. const colorFormat = utils.getCurrentColorFormat( renderObject.context );
  56359. const depthStencilFormat = utils.getCurrentDepthStencilFormat( renderObject.context );
  56360. const primitiveTopology = utils.getPrimitiveTopology( object, material );
  56361. let needsUpdate = false;
  56362. if ( data.material !== material || data.materialVersion !== material.version ||
  56363. data.transparent !== material.transparent || data.blending !== material.blending || data.premultipliedAlpha !== material.premultipliedAlpha ||
  56364. data.blendSrc !== material.blendSrc || data.blendDst !== material.blendDst || data.blendEquation !== material.blendEquation ||
  56365. data.blendSrcAlpha !== material.blendSrcAlpha || data.blendDstAlpha !== material.blendDstAlpha || data.blendEquationAlpha !== material.blendEquationAlpha ||
  56366. data.colorWrite !== material.colorWrite || data.depthWrite !== material.depthWrite || data.depthTest !== material.depthTest || data.depthFunc !== material.depthFunc ||
  56367. data.stencilWrite !== material.stencilWrite || data.stencilFunc !== material.stencilFunc ||
  56368. data.stencilFail !== material.stencilFail || data.stencilZFail !== material.stencilZFail || data.stencilZPass !== material.stencilZPass ||
  56369. data.stencilFuncMask !== material.stencilFuncMask || data.stencilWriteMask !== material.stencilWriteMask ||
  56370. data.side !== material.side || data.alphaToCoverage !== material.alphaToCoverage ||
  56371. data.sampleCount !== sampleCount || data.colorSpace !== colorSpace ||
  56372. data.colorFormat !== colorFormat || data.depthStencilFormat !== depthStencilFormat ||
  56373. data.primitiveTopology !== primitiveTopology ||
  56374. data.clippingContextCacheKey !== renderObject.clippingContextCacheKey
  56375. ) {
  56376. data.material = material; data.materialVersion = material.version;
  56377. data.transparent = material.transparent; data.blending = material.blending; data.premultipliedAlpha = material.premultipliedAlpha;
  56378. data.blendSrc = material.blendSrc; data.blendDst = material.blendDst; data.blendEquation = material.blendEquation;
  56379. data.blendSrcAlpha = material.blendSrcAlpha; data.blendDstAlpha = material.blendDstAlpha; data.blendEquationAlpha = material.blendEquationAlpha;
  56380. data.colorWrite = material.colorWrite;
  56381. data.depthWrite = material.depthWrite; data.depthTest = material.depthTest; data.depthFunc = material.depthFunc;
  56382. data.stencilWrite = material.stencilWrite; data.stencilFunc = material.stencilFunc;
  56383. data.stencilFail = material.stencilFail; data.stencilZFail = material.stencilZFail; data.stencilZPass = material.stencilZPass;
  56384. data.stencilFuncMask = material.stencilFuncMask; data.stencilWriteMask = material.stencilWriteMask;
  56385. data.side = material.side; data.alphaToCoverage = material.alphaToCoverage;
  56386. data.sampleCount = sampleCount;
  56387. data.colorSpace = colorSpace;
  56388. data.colorFormat = colorFormat;
  56389. data.depthStencilFormat = depthStencilFormat;
  56390. data.primitiveTopology = primitiveTopology;
  56391. data.clippingContextCacheKey = renderObject.clippingContextCacheKey;
  56392. needsUpdate = true;
  56393. }
  56394. return needsUpdate;
  56395. }
  56396. /**
  56397. * Returns a cache key that is used to identify render pipelines.
  56398. *
  56399. * @param {RenderObject} renderObject - The render object.
  56400. * @return {string} The cache key.
  56401. */
  56402. getRenderCacheKey( renderObject ) {
  56403. const { object, material } = renderObject;
  56404. const utils = this.utils;
  56405. const renderContext = renderObject.context;
  56406. // meshes with negative scale have a different frontFace render pipeline
  56407. // descriptor value so the following must be honored in the cache key
  56408. const frontFaceCW = ( object.isMesh && object.matrixWorld.determinant() < 0 );
  56409. return [
  56410. material.transparent, material.blending, material.premultipliedAlpha,
  56411. material.blendSrc, material.blendDst, material.blendEquation,
  56412. material.blendSrcAlpha, material.blendDstAlpha, material.blendEquationAlpha,
  56413. material.colorWrite,
  56414. material.depthWrite, material.depthTest, material.depthFunc,
  56415. material.stencilWrite, material.stencilFunc,
  56416. material.stencilFail, material.stencilZFail, material.stencilZPass,
  56417. material.stencilFuncMask, material.stencilWriteMask,
  56418. material.side,
  56419. frontFaceCW,
  56420. utils.getSampleCountRenderContext( renderContext ),
  56421. utils.getCurrentColorSpace( renderContext ), utils.getCurrentColorFormat( renderContext ), utils.getCurrentDepthStencilFormat( renderContext ),
  56422. utils.getPrimitiveTopology( object, material ),
  56423. renderObject.getGeometryCacheKey(),
  56424. renderObject.clippingContextCacheKey
  56425. ].join();
  56426. }
  56427. // textures
  56428. /**
  56429. * Updates a GPU sampler for the given texture.
  56430. *
  56431. * @param {Texture} texture - The texture to update the sampler for.
  56432. * @return {string} The current sampler key.
  56433. */
  56434. updateSampler( texture ) {
  56435. return this.textureUtils.updateSampler( texture );
  56436. }
  56437. /**
  56438. * Creates a default texture for the given texture that can be used
  56439. * as a placeholder until the actual texture is ready for usage.
  56440. *
  56441. * @param {Texture} texture - The texture to create a default texture for.
  56442. * @return {boolean} Whether the sampler has been updated or not.
  56443. */
  56444. createDefaultTexture( texture ) {
  56445. return this.textureUtils.createDefaultTexture( texture );
  56446. }
  56447. /**
  56448. * Defines a texture on the GPU for the given texture object.
  56449. *
  56450. * @param {Texture} texture - The texture.
  56451. * @param {Object} [options={}] - Optional configuration parameter.
  56452. */
  56453. createTexture( texture, options ) {
  56454. this.textureUtils.createTexture( texture, options );
  56455. }
  56456. /**
  56457. * Uploads the updated texture data to the GPU.
  56458. *
  56459. * @param {Texture} texture - The texture.
  56460. * @param {Object} [options={}] - Optional configuration parameter.
  56461. */
  56462. updateTexture( texture, options ) {
  56463. this.textureUtils.updateTexture( texture, options );
  56464. }
  56465. /**
  56466. * Generates mipmaps for the given texture.
  56467. *
  56468. * @param {Texture} texture - The texture.
  56469. */
  56470. generateMipmaps( texture ) {
  56471. this.textureUtils.generateMipmaps( texture );
  56472. }
  56473. /**
  56474. * Destroys the GPU data for the given texture object.
  56475. *
  56476. * @param {Texture} texture - The texture.
  56477. * @param {boolean} [isDefaultTexture=false] - Whether the texture uses a default GPU texture or not.
  56478. */
  56479. destroyTexture( texture, isDefaultTexture = false ) {
  56480. this.textureUtils.destroyTexture( texture, isDefaultTexture );
  56481. }
  56482. /**
  56483. * Returns texture data as a typed array.
  56484. *
  56485. * @async
  56486. * @param {Texture} texture - The texture to copy.
  56487. * @param {number} x - The x coordinate of the copy origin.
  56488. * @param {number} y - The y coordinate of the copy origin.
  56489. * @param {number} width - The width of the copy.
  56490. * @param {number} height - The height of the copy.
  56491. * @param {number} faceIndex - The face index.
  56492. * @return {Promise<TypedArray>} A Promise that resolves with a typed array when the copy operation has finished.
  56493. */
  56494. async copyTextureToBuffer( texture, x, y, width, height, faceIndex ) {
  56495. return this.textureUtils.copyTextureToBuffer( texture, x, y, width, height, faceIndex );
  56496. }
  56497. /**
  56498. * Inits a time stamp query for the given render context.
  56499. *
  56500. * @param {string} type - The type of the timestamp query (e.g. 'render', 'compute').
  56501. * @param {number} uid - Unique id for the context (e.g. render context id).
  56502. * @param {Object} descriptor - The query descriptor.
  56503. */
  56504. initTimestampQuery( type, uid, descriptor ) {
  56505. if ( ! this.trackTimestamp ) return;
  56506. if ( ! this.timestampQueryPool[ type ] ) {
  56507. // TODO: Variable maxQueries?
  56508. this.timestampQueryPool[ type ] = new WebGPUTimestampQueryPool( this.device, type, 2048 );
  56509. }
  56510. const timestampQueryPool = this.timestampQueryPool[ type ];
  56511. const baseOffset = timestampQueryPool.allocateQueriesForContext( uid );
  56512. descriptor.timestampWrites = {
  56513. querySet: timestampQueryPool.querySet,
  56514. beginningOfPassWriteIndex: baseOffset,
  56515. endOfPassWriteIndex: baseOffset + 1,
  56516. };
  56517. }
  56518. // node builder
  56519. /**
  56520. * Returns a node builder for the given render object.
  56521. *
  56522. * @param {RenderObject} object - The render object.
  56523. * @param {Renderer} renderer - The renderer.
  56524. * @return {WGSLNodeBuilder} The node builder.
  56525. */
  56526. createNodeBuilder( object, renderer ) {
  56527. return new WGSLNodeBuilder( object, renderer );
  56528. }
  56529. // program
  56530. /**
  56531. * Creates a shader program from the given programmable stage.
  56532. *
  56533. * @param {ProgrammableStage} program - The programmable stage.
  56534. */
  56535. createProgram( program ) {
  56536. const programGPU = this.get( program );
  56537. programGPU.module = {
  56538. module: this.device.createShaderModule( { code: program.code, label: program.stage + ( program.name !== '' ? `_${ program.name }` : '' ) } ),
  56539. entryPoint: 'main'
  56540. };
  56541. }
  56542. /**
  56543. * Destroys the shader program of the given programmable stage.
  56544. *
  56545. * @param {ProgrammableStage} program - The programmable stage.
  56546. */
  56547. destroyProgram( program ) {
  56548. this.delete( program );
  56549. }
  56550. // pipelines
  56551. /**
  56552. * Creates a render pipeline for the given render object.
  56553. *
  56554. * @param {RenderObject} renderObject - The render object.
  56555. * @param {Array<Promise>} promises - An array of compilation promises which are used in `compileAsync()`.
  56556. */
  56557. createRenderPipeline( renderObject, promises ) {
  56558. this.pipelineUtils.createRenderPipeline( renderObject, promises );
  56559. }
  56560. /**
  56561. * Creates a compute pipeline for the given compute node.
  56562. *
  56563. * @param {ComputePipeline} computePipeline - The compute pipeline.
  56564. * @param {Array<BindGroup>} bindings - The bindings.
  56565. */
  56566. createComputePipeline( computePipeline, bindings ) {
  56567. this.pipelineUtils.createComputePipeline( computePipeline, bindings );
  56568. }
  56569. /**
  56570. * Prepares the state for encoding render bundles.
  56571. *
  56572. * @param {RenderContext} renderContext - The render context.
  56573. */
  56574. beginBundle( renderContext ) {
  56575. const renderContextData = this.get( renderContext );
  56576. renderContextData._currentPass = renderContextData.currentPass;
  56577. renderContextData._currentSets = renderContextData.currentSets;
  56578. renderContextData.currentSets = { attributes: {}, bindingGroups: [], pipeline: null, index: null };
  56579. renderContextData.currentPass = this.pipelineUtils.createBundleEncoder( renderContext );
  56580. }
  56581. /**
  56582. * After processing render bundles this method finalizes related work.
  56583. *
  56584. * @param {RenderContext} renderContext - The render context.
  56585. * @param {RenderBundle} bundle - The render bundle.
  56586. */
  56587. finishBundle( renderContext, bundle ) {
  56588. const renderContextData = this.get( renderContext );
  56589. const bundleEncoder = renderContextData.currentPass;
  56590. const bundleGPU = bundleEncoder.finish();
  56591. this.get( bundle ).bundleGPU = bundleGPU;
  56592. // restore render pass state
  56593. renderContextData.currentSets = renderContextData._currentSets;
  56594. renderContextData.currentPass = renderContextData._currentPass;
  56595. }
  56596. /**
  56597. * Adds a render bundle to the render context data.
  56598. *
  56599. * @param {RenderContext} renderContext - The render context.
  56600. * @param {RenderBundle} bundle - The render bundle to add.
  56601. */
  56602. addBundle( renderContext, bundle ) {
  56603. const renderContextData = this.get( renderContext );
  56604. renderContextData.renderBundles.push( this.get( bundle ).bundleGPU );
  56605. }
  56606. // bindings
  56607. /**
  56608. * Creates bindings from the given bind group definition.
  56609. *
  56610. * @param {BindGroup} bindGroup - The bind group.
  56611. * @param {Array<BindGroup>} bindings - Array of bind groups.
  56612. * @param {number} cacheIndex - The cache index.
  56613. * @param {number} version - The version.
  56614. */
  56615. createBindings( bindGroup, bindings, cacheIndex, version ) {
  56616. this.bindingUtils.createBindings( bindGroup, bindings, cacheIndex, version );
  56617. }
  56618. /**
  56619. * Updates the given bind group definition.
  56620. *
  56621. * @param {BindGroup} bindGroup - The bind group.
  56622. * @param {Array<BindGroup>} bindings - Array of bind groups.
  56623. * @param {number} cacheIndex - The cache index.
  56624. * @param {number} version - The version.
  56625. */
  56626. updateBindings( bindGroup, bindings, cacheIndex, version ) {
  56627. this.bindingUtils.createBindings( bindGroup, bindings, cacheIndex, version );
  56628. }
  56629. /**
  56630. * Updates a buffer binding.
  56631. *
  56632. * @param {Buffer} binding - The buffer binding to update.
  56633. */
  56634. updateBinding( binding ) {
  56635. this.bindingUtils.updateBinding( binding );
  56636. }
  56637. /**
  56638. * Delete data associated with the current bind group.
  56639. *
  56640. * @param {BindGroup} bindGroup - The bind group.
  56641. */
  56642. deleteBindGroupData( bindGroup ) {
  56643. this.bindingUtils.deleteBindGroupData( bindGroup );
  56644. }
  56645. // attributes
  56646. /**
  56647. * Creates the buffer of an indexed shader attribute.
  56648. *
  56649. * @param {BufferAttribute} attribute - The indexed buffer attribute.
  56650. */
  56651. createIndexAttribute( attribute ) {
  56652. let usage = GPUBufferUsage.INDEX | GPUBufferUsage.COPY_SRC | GPUBufferUsage.COPY_DST;
  56653. if ( attribute.isStorageBufferAttribute || attribute.isStorageInstancedBufferAttribute ) {
  56654. usage |= GPUBufferUsage.STORAGE;
  56655. }
  56656. this.attributeUtils.createAttribute( attribute, usage );
  56657. }
  56658. /**
  56659. * Creates the GPU buffer of a shader attribute.
  56660. *
  56661. * @param {BufferAttribute} attribute - The buffer attribute.
  56662. */
  56663. createAttribute( attribute ) {
  56664. this.attributeUtils.createAttribute( attribute, GPUBufferUsage.VERTEX | GPUBufferUsage.COPY_SRC | GPUBufferUsage.COPY_DST );
  56665. }
  56666. /**
  56667. * Creates the GPU buffer of a storage attribute.
  56668. *
  56669. * @param {BufferAttribute} attribute - The buffer attribute.
  56670. */
  56671. createStorageAttribute( attribute ) {
  56672. this.attributeUtils.createAttribute( attribute, GPUBufferUsage.STORAGE | GPUBufferUsage.VERTEX | GPUBufferUsage.COPY_SRC | GPUBufferUsage.COPY_DST );
  56673. }
  56674. /**
  56675. * Creates the GPU buffer of an indirect storage attribute.
  56676. *
  56677. * @param {BufferAttribute} attribute - The buffer attribute.
  56678. */
  56679. createIndirectStorageAttribute( attribute ) {
  56680. this.attributeUtils.createAttribute( attribute, GPUBufferUsage.STORAGE | GPUBufferUsage.INDIRECT | GPUBufferUsage.COPY_SRC | GPUBufferUsage.COPY_DST );
  56681. }
  56682. /**
  56683. * Updates the GPU buffer of a shader attribute.
  56684. *
  56685. * @param {BufferAttribute} attribute - The buffer attribute to update.
  56686. */
  56687. updateAttribute( attribute ) {
  56688. this.attributeUtils.updateAttribute( attribute );
  56689. }
  56690. /**
  56691. * Destroys the GPU buffer of a shader attribute.
  56692. *
  56693. * @param {BufferAttribute} attribute - The buffer attribute to destroy.
  56694. */
  56695. destroyAttribute( attribute ) {
  56696. this.attributeUtils.destroyAttribute( attribute );
  56697. }
  56698. // canvas
  56699. /**
  56700. * Triggers an update of the default render pass descriptor.
  56701. */
  56702. updateSize() {
  56703. this.delete( this.renderer.getCanvasTarget() );
  56704. }
  56705. // utils public
  56706. /**
  56707. * Returns the maximum anisotropy texture filtering value.
  56708. *
  56709. * @return {number} The maximum anisotropy texture filtering value.
  56710. */
  56711. getMaxAnisotropy() {
  56712. return 16;
  56713. }
  56714. /**
  56715. * Checks if the given feature is supported by the backend.
  56716. *
  56717. * @param {string} name - The feature's name.
  56718. * @return {boolean} Whether the feature is supported or not.
  56719. */
  56720. hasFeature( name ) {
  56721. if ( GPUFeatureMap[ name ] !== undefined ) name = GPUFeatureMap[ name ];
  56722. return this.device.features.has( name );
  56723. }
  56724. /**
  56725. * Copies data of the given source texture to the given destination texture.
  56726. *
  56727. * @param {Texture} srcTexture - The source texture.
  56728. * @param {Texture} dstTexture - The destination texture.
  56729. * @param {?(Box3|Box2)} [srcRegion=null] - The region of the source texture to copy.
  56730. * @param {?(Vector2|Vector3)} [dstPosition=null] - The destination position of the copy.
  56731. * @param {number} [srcLevel=0] - The mipmap level to copy.
  56732. * @param {number} [dstLevel=0] - The destination mip level to copy to.
  56733. */
  56734. copyTextureToTexture( srcTexture, dstTexture, srcRegion = null, dstPosition = null, srcLevel = 0, dstLevel = 0 ) {
  56735. let dstX = 0;
  56736. let dstY = 0;
  56737. let dstZ = 0;
  56738. let srcX = 0;
  56739. let srcY = 0;
  56740. let srcZ = 0;
  56741. let srcWidth = srcTexture.image.width;
  56742. let srcHeight = srcTexture.image.height;
  56743. let srcDepth = 1;
  56744. if ( srcRegion !== null ) {
  56745. if ( srcRegion.isBox3 === true ) {
  56746. srcX = srcRegion.min.x;
  56747. srcY = srcRegion.min.y;
  56748. srcZ = srcRegion.min.z;
  56749. srcWidth = srcRegion.max.x - srcRegion.min.x;
  56750. srcHeight = srcRegion.max.y - srcRegion.min.y;
  56751. srcDepth = srcRegion.max.z - srcRegion.min.z;
  56752. } else {
  56753. // Assume it's a Box2
  56754. srcX = srcRegion.min.x;
  56755. srcY = srcRegion.min.y;
  56756. srcWidth = srcRegion.max.x - srcRegion.min.x;
  56757. srcHeight = srcRegion.max.y - srcRegion.min.y;
  56758. srcDepth = 1;
  56759. }
  56760. }
  56761. if ( dstPosition !== null ) {
  56762. dstX = dstPosition.x;
  56763. dstY = dstPosition.y;
  56764. dstZ = dstPosition.z || 0;
  56765. }
  56766. const encoder = this.device.createCommandEncoder( { label: 'copyTextureToTexture_' + srcTexture.id + '_' + dstTexture.id } );
  56767. const sourceGPU = this.get( srcTexture ).texture;
  56768. const destinationGPU = this.get( dstTexture ).texture;
  56769. encoder.copyTextureToTexture(
  56770. {
  56771. texture: sourceGPU,
  56772. mipLevel: srcLevel,
  56773. origin: { x: srcX, y: srcY, z: srcZ }
  56774. },
  56775. {
  56776. texture: destinationGPU,
  56777. mipLevel: dstLevel,
  56778. origin: { x: dstX, y: dstY, z: dstZ }
  56779. },
  56780. [
  56781. srcWidth,
  56782. srcHeight,
  56783. srcDepth
  56784. ]
  56785. );
  56786. this.device.queue.submit( [ encoder.finish() ] );
  56787. if ( dstLevel === 0 && dstTexture.generateMipmaps ) {
  56788. this.textureUtils.generateMipmaps( dstTexture );
  56789. }
  56790. }
  56791. /**
  56792. * Copies the current bound framebuffer to the given texture.
  56793. *
  56794. * @param {Texture} texture - The destination texture.
  56795. * @param {RenderContext} renderContext - The render context.
  56796. * @param {Vector4} rectangle - A four dimensional vector defining the origin and dimension of the copy.
  56797. */
  56798. copyFramebufferToTexture( texture, renderContext, rectangle ) {
  56799. const renderContextData = this.get( renderContext );
  56800. let sourceGPU = null;
  56801. if ( renderContext.renderTarget ) {
  56802. if ( texture.isDepthTexture ) {
  56803. sourceGPU = this.get( renderContext.depthTexture ).texture;
  56804. } else {
  56805. sourceGPU = this.get( renderContext.textures[ 0 ] ).texture;
  56806. }
  56807. } else {
  56808. if ( texture.isDepthTexture ) {
  56809. sourceGPU = this.textureUtils.getDepthBuffer( renderContext.depth, renderContext.stencil );
  56810. } else {
  56811. sourceGPU = this.context.getCurrentTexture();
  56812. }
  56813. }
  56814. const destinationGPU = this.get( texture ).texture;
  56815. if ( sourceGPU.format !== destinationGPU.format ) {
  56816. error( 'WebGPUBackend: copyFramebufferToTexture: Source and destination formats do not match.', sourceGPU.format, destinationGPU.format );
  56817. return;
  56818. }
  56819. let encoder;
  56820. if ( renderContextData.currentPass ) {
  56821. renderContextData.currentPass.end();
  56822. encoder = renderContextData.encoder;
  56823. } else {
  56824. encoder = this.device.createCommandEncoder( { label: 'copyFramebufferToTexture_' + texture.id } );
  56825. }
  56826. encoder.copyTextureToTexture(
  56827. {
  56828. texture: sourceGPU,
  56829. origin: [ rectangle.x, rectangle.y, 0 ],
  56830. },
  56831. {
  56832. texture: destinationGPU
  56833. },
  56834. [
  56835. rectangle.z,
  56836. rectangle.w
  56837. ]
  56838. );
  56839. // mipmaps must be genereated with the same encoder otherwise the copied texture data
  56840. // might be out-of-sync, see #31768
  56841. if ( texture.generateMipmaps ) {
  56842. this.textureUtils.generateMipmaps( texture, encoder );
  56843. }
  56844. if ( renderContextData.currentPass ) {
  56845. const { descriptor } = renderContextData;
  56846. for ( let i = 0; i < descriptor.colorAttachments.length; i ++ ) {
  56847. descriptor.colorAttachments[ i ].loadOp = GPULoadOp.Load;
  56848. }
  56849. if ( renderContext.depth ) descriptor.depthStencilAttachment.depthLoadOp = GPULoadOp.Load;
  56850. if ( renderContext.stencil ) descriptor.depthStencilAttachment.stencilLoadOp = GPULoadOp.Load;
  56851. renderContextData.currentPass = encoder.beginRenderPass( descriptor );
  56852. renderContextData.currentSets = { attributes: {}, bindingGroups: [], pipeline: null, index: null };
  56853. if ( renderContext.viewport ) {
  56854. this.updateViewport( renderContext );
  56855. }
  56856. if ( renderContext.scissor ) {
  56857. this.updateScissor( renderContext );
  56858. }
  56859. } else {
  56860. this.device.queue.submit( [ encoder.finish() ] );
  56861. }
  56862. }
  56863. dispose() {
  56864. this.bindingUtils.dispose();
  56865. this.textureUtils.dispose();
  56866. if ( this.occludedResolveCache ) {
  56867. for ( const buffer of this.occludedResolveCache.values() ) {
  56868. buffer.destroy();
  56869. }
  56870. this.occludedResolveCache.clear();
  56871. }
  56872. if ( this.timestampQueryPool ) {
  56873. for ( const queryPool of Object.values( this.timestampQueryPool ) ) {
  56874. if ( queryPool !== null ) queryPool.dispose();
  56875. }
  56876. }
  56877. if ( this.parameters.device === undefined && this.device !== null ) {
  56878. this.device.destroy();
  56879. }
  56880. }
  56881. }
  56882. /**
  56883. * A IES version of {@link SpotLight}. Can only be used with {@link WebGPURenderer}.
  56884. *
  56885. * @augments SpotLight
  56886. */
  56887. class IESSpotLight extends SpotLight {
  56888. /**
  56889. * Constructs a new IES spot light.
  56890. *
  56891. * @param {(number|Color|string)} [color=0xffffff] - The light's color.
  56892. * @param {number} [intensity=1] - The light's strength/intensity measured in candela (cd).
  56893. * @param {number} [distance=0] - Maximum range of the light. `0` means no limit.
  56894. * @param {number} [angle=Math.PI/3] - Maximum angle of light dispersion from its direction whose upper bound is `Math.PI/2`.
  56895. * @param {number} [penumbra=0] - Percent of the spotlight cone that is attenuated due to penumbra. Value range is `[0,1]`.
  56896. * @param {number} [decay=2] - The amount the light dims along the distance of the light.
  56897. */
  56898. constructor( color, intensity, distance, angle, penumbra, decay ) {
  56899. super( color, intensity, distance, angle, penumbra, decay );
  56900. /**
  56901. * TODO
  56902. *
  56903. * @type {?Texture}
  56904. * @default null
  56905. */
  56906. this.iesMap = null;
  56907. }
  56908. copy( source, recursive ) {
  56909. super.copy( source, recursive );
  56910. this.iesMap = source.iesMap;
  56911. return this;
  56912. }
  56913. }
  56914. /**
  56915. * A projector light version of {@link SpotLight}. Can only be used with {@link WebGPURenderer}.
  56916. *
  56917. * @augments SpotLight
  56918. */
  56919. class ProjectorLight extends SpotLight {
  56920. /**
  56921. * Constructs a new projector light.
  56922. *
  56923. * @param {(number|Color|string)} [color=0xffffff] - The light's color.
  56924. * @param {number} [intensity=1] - The light's strength/intensity measured in candela (cd).
  56925. * @param {number} [distance=0] - Maximum range of the light. `0` means no limit.
  56926. * @param {number} [angle=Math.PI/3] - Maximum angle of light dispersion from its direction whose upper bound is `Math.PI/2`.
  56927. * @param {number} [penumbra=0] - Percent of the spotlight cone that is attenuated due to penumbra. Value range is `[0,1]`.
  56928. * @param {number} [decay=2] - The amount the light dims along the distance of the light.
  56929. */
  56930. constructor( color, intensity, distance, angle, penumbra, decay ) {
  56931. super( color, intensity, distance, angle, penumbra, decay );
  56932. /**
  56933. * Aspect ratio of the light. Set to `null` to use the texture aspect ratio.
  56934. *
  56935. * @type {?number}
  56936. * @default null
  56937. */
  56938. this.aspect = null;
  56939. }
  56940. copy( source, recursive ) {
  56941. super.copy( source, recursive );
  56942. this.aspect = source.aspect;
  56943. return this;
  56944. }
  56945. }
  56946. /**
  56947. * This version of a node library represents a basic version
  56948. * just focusing on lights and tone mapping techniques.
  56949. *
  56950. * @private
  56951. * @augments NodeLibrary
  56952. */
  56953. class BasicNodeLibrary extends NodeLibrary {
  56954. /**
  56955. * Constructs a new basic node library.
  56956. */
  56957. constructor() {
  56958. super();
  56959. this.addLight( PointLightNode, PointLight );
  56960. this.addLight( DirectionalLightNode, DirectionalLight );
  56961. this.addLight( RectAreaLightNode, RectAreaLight );
  56962. this.addLight( SpotLightNode, SpotLight );
  56963. this.addLight( AmbientLightNode, AmbientLight );
  56964. this.addLight( HemisphereLightNode, HemisphereLight );
  56965. this.addLight( LightProbeNode, LightProbe );
  56966. this.addLight( IESSpotLightNode, IESSpotLight );
  56967. this.addLight( ProjectorLightNode, ProjectorLight );
  56968. this.addToneMapping( linearToneMapping, LinearToneMapping );
  56969. this.addToneMapping( reinhardToneMapping, ReinhardToneMapping );
  56970. this.addToneMapping( cineonToneMapping, CineonToneMapping );
  56971. this.addToneMapping( acesFilmicToneMapping, ACESFilmicToneMapping );
  56972. this.addToneMapping( agxToneMapping, AgXToneMapping );
  56973. this.addToneMapping( neutralToneMapping, NeutralToneMapping );
  56974. }
  56975. }
  56976. /**
  56977. * This alternative version of {@link WebGPURenderer} only supports node materials.
  56978. * So classes like `MeshBasicMaterial` are not compatible.
  56979. *
  56980. * @private
  56981. * @augments Renderer
  56982. */
  56983. class WebGPURenderer extends Renderer {
  56984. /**
  56985. * Constructs a new WebGPU renderer.
  56986. *
  56987. * @param {WebGPURenderer~Options} [parameters] - The configuration parameter.
  56988. */
  56989. constructor( parameters = {} ) {
  56990. let BackendClass;
  56991. if ( parameters.forceWebGL ) {
  56992. BackendClass = WebGLBackend;
  56993. } else {
  56994. BackendClass = WebGPUBackend;
  56995. parameters.getFallback = () => {
  56996. warn( 'WebGPURenderer: WebGPU is not available, running under WebGL2 backend.' );
  56997. return new WebGLBackend( parameters );
  56998. };
  56999. }
  57000. const backend = new BackendClass( parameters );
  57001. super( backend, parameters );
  57002. /**
  57003. * The generic default value is overwritten with the
  57004. * standard node library for type mapping. Material
  57005. * mapping is not supported with this version.
  57006. *
  57007. * @type {BasicNodeLibrary}
  57008. */
  57009. this.library = new BasicNodeLibrary();
  57010. /**
  57011. * This flag can be used for type testing.
  57012. *
  57013. * @type {boolean}
  57014. * @readonly
  57015. * @default true
  57016. */
  57017. this.isWebGPURenderer = true;
  57018. }
  57019. }
  57020. /**
  57021. * A specialized group which enables applications access to the
  57022. * Render Bundle API of WebGPU. The group with all its descendant nodes
  57023. * are considered as one render bundle and processed as such by
  57024. * the renderer.
  57025. *
  57026. * This module is only fully supported by `WebGPURenderer` with a WebGPU backend.
  57027. * With a WebGL backend, the group can technically be rendered but without
  57028. * any performance improvements.
  57029. *
  57030. * @augments Group
  57031. */
  57032. class BundleGroup extends Group {
  57033. /**
  57034. * Constructs a new bundle group.
  57035. */
  57036. constructor() {
  57037. super();
  57038. /**
  57039. * This flag can be used for type testing.
  57040. *
  57041. * @type {boolean}
  57042. * @readonly
  57043. * @default true
  57044. */
  57045. this.isBundleGroup = true;
  57046. /**
  57047. * This property is only relevant for detecting types
  57048. * during serialization/deserialization. It should always
  57049. * match the class name.
  57050. *
  57051. * @type {string}
  57052. * @readonly
  57053. * @default 'BundleGroup'
  57054. */
  57055. this.type = 'BundleGroup';
  57056. /**
  57057. * Whether the bundle is static or not. When set to `true`, the structure
  57058. * is assumed to be static and does not change. E.g. no new objects are
  57059. * added to the group
  57060. *
  57061. * If a change is required, an update can still be forced by setting the
  57062. * `needsUpdate` flag to `true`.
  57063. *
  57064. * @type {boolean}
  57065. * @default true
  57066. */
  57067. this.static = true;
  57068. /**
  57069. * The bundle group's version.
  57070. *
  57071. * @type {number}
  57072. * @readonly
  57073. * @default 0
  57074. */
  57075. this.version = 0;
  57076. }
  57077. /**
  57078. * Set this property to `true` when the bundle group has changed.
  57079. *
  57080. * @type {boolean}
  57081. * @default false
  57082. * @param {boolean} value
  57083. */
  57084. set needsUpdate( value ) {
  57085. if ( value === true ) this.version ++;
  57086. }
  57087. }
  57088. /**
  57089. * This module is responsible to manage the post processing setups in apps.
  57090. * You usually create a single instance of this class and use it to define
  57091. * the output of your post processing effect chain.
  57092. * ```js
  57093. * const postProcessing = new PostProcessing( renderer );
  57094. *
  57095. * const scenePass = pass( scene, camera );
  57096. *
  57097. * postProcessing.outputNode = scenePass;
  57098. * ```
  57099. *
  57100. * Note: This module can only be used with `WebGPURenderer`.
  57101. */
  57102. class PostProcessing {
  57103. /**
  57104. * Constructs a new post processing management module.
  57105. *
  57106. * @param {Renderer} renderer - A reference to the renderer.
  57107. * @param {Node<vec4>} outputNode - An optional output node.
  57108. */
  57109. constructor( renderer, outputNode = vec4( 0, 0, 1, 1 ) ) {
  57110. /**
  57111. * A reference to the renderer.
  57112. *
  57113. * @type {Renderer}
  57114. */
  57115. this.renderer = renderer;
  57116. /**
  57117. * A node which defines the final output of the post
  57118. * processing. This is usually the last node in a chain
  57119. * of effect nodes.
  57120. *
  57121. * @type {Node<vec4>}
  57122. */
  57123. this.outputNode = outputNode;
  57124. /**
  57125. * Whether the default output tone mapping and color
  57126. * space transformation should be enabled or not.
  57127. *
  57128. * It is enabled by default by it must be disabled when
  57129. * effects must be executed after tone mapping and color
  57130. * space conversion. A typical example is FXAA which
  57131. * requires sRGB input.
  57132. *
  57133. * When set to `false`, the app must control the output
  57134. * transformation with `RenderOutputNode`.
  57135. *
  57136. * ```js
  57137. * const outputPass = renderOutput( scenePass );
  57138. * ```
  57139. *
  57140. * @type {boolean}
  57141. */
  57142. this.outputColorTransform = true;
  57143. /**
  57144. * Must be set to `true` when the output node changes.
  57145. *
  57146. * @type {Node<vec4>}
  57147. */
  57148. this.needsUpdate = true;
  57149. const material = new NodeMaterial();
  57150. material.name = 'PostProcessing';
  57151. /**
  57152. * The full screen quad that is used to render
  57153. * the effects.
  57154. *
  57155. * @private
  57156. * @type {QuadMesh}
  57157. */
  57158. this._quadMesh = new QuadMesh( material );
  57159. this._quadMesh.name = 'Post-Processing';
  57160. /**
  57161. * The context of the post processing stack.
  57162. *
  57163. * @private
  57164. * @type {?Object}
  57165. * @default null
  57166. */
  57167. this._context = null;
  57168. }
  57169. /**
  57170. * When `PostProcessing` is used to apply post processing effects,
  57171. * the application must use this version of `render()` inside
  57172. * its animation loop (not the one from the renderer).
  57173. */
  57174. render() {
  57175. const renderer = this.renderer;
  57176. this._update();
  57177. if ( this._context.onBeforePostProcessing !== null ) this._context.onBeforePostProcessing();
  57178. const toneMapping = renderer.toneMapping;
  57179. const outputColorSpace = renderer.outputColorSpace;
  57180. renderer.toneMapping = NoToneMapping;
  57181. renderer.outputColorSpace = ColorManagement.workingColorSpace;
  57182. //
  57183. const currentXR = renderer.xr.enabled;
  57184. renderer.xr.enabled = false;
  57185. this._quadMesh.render( renderer );
  57186. renderer.xr.enabled = currentXR;
  57187. //
  57188. renderer.toneMapping = toneMapping;
  57189. renderer.outputColorSpace = outputColorSpace;
  57190. if ( this._context.onAfterPostProcessing !== null ) this._context.onAfterPostProcessing();
  57191. }
  57192. /**
  57193. * Returns the current context of the post processing stack.
  57194. *
  57195. * @readonly
  57196. * @type {?Object}
  57197. */
  57198. get context() {
  57199. return this._context;
  57200. }
  57201. /**
  57202. * Frees internal resources.
  57203. */
  57204. dispose() {
  57205. this._quadMesh.material.dispose();
  57206. }
  57207. /**
  57208. * Updates the state of the module.
  57209. *
  57210. * @private
  57211. */
  57212. _update() {
  57213. if ( this.needsUpdate === true ) {
  57214. const renderer = this.renderer;
  57215. const toneMapping = renderer.toneMapping;
  57216. const outputColorSpace = renderer.outputColorSpace;
  57217. const context = {
  57218. postProcessing: this,
  57219. onBeforePostProcessing: null,
  57220. onAfterPostProcessing: null
  57221. };
  57222. let outputNode = this.outputNode;
  57223. if ( this.outputColorTransform === true ) {
  57224. outputNode = outputNode.context( context );
  57225. outputNode = renderOutput( outputNode, toneMapping, outputColorSpace );
  57226. } else {
  57227. context.toneMapping = toneMapping;
  57228. context.outputColorSpace = outputColorSpace;
  57229. outputNode = outputNode.context( context );
  57230. }
  57231. this._context = context;
  57232. this._quadMesh.material.fragmentNode = outputNode;
  57233. this._quadMesh.material.needsUpdate = true;
  57234. this.needsUpdate = false;
  57235. }
  57236. }
  57237. /**
  57238. * When `PostProcessing` is used to apply post processing effects,
  57239. * the application must use this version of `renderAsync()` inside
  57240. * its animation loop (not the one from the renderer).
  57241. *
  57242. * @async
  57243. * @deprecated
  57244. * @return {Promise} A Promise that resolves when the render has been finished.
  57245. */
  57246. async renderAsync() {
  57247. warnOnce( 'PostProcessing: "renderAsync()" has been deprecated. Use "render()" and "await renderer.init();" when creating the renderer.' ); // @deprecated r181
  57248. await this.renderer.init();
  57249. this.render();
  57250. }
  57251. }
  57252. /**
  57253. * This special type of texture is intended for compute shaders.
  57254. * It can be used to compute the data of a texture with a compute shader.
  57255. *
  57256. * Note: This type of texture can only be used with `WebGPURenderer`
  57257. * and a WebGPU backend.
  57258. *
  57259. * @augments Texture
  57260. */
  57261. class StorageTexture extends Texture {
  57262. /**
  57263. * Constructs a new storage texture.
  57264. *
  57265. * @param {number} [width=1] - The storage texture's width.
  57266. * @param {number} [height=1] - The storage texture's height.
  57267. */
  57268. constructor( width = 1, height = 1 ) {
  57269. super();
  57270. /**
  57271. * The image object which just represents the texture's dimension.
  57272. *
  57273. * @type {{width: number, height: number}}
  57274. */
  57275. this.image = { width, height };
  57276. /**
  57277. * The default `magFilter` for storage textures is `THREE.LinearFilter`.
  57278. *
  57279. * @type {number}
  57280. */
  57281. this.magFilter = LinearFilter;
  57282. /**
  57283. * The default `minFilter` for storage textures is `THREE.LinearFilter`.
  57284. *
  57285. * @type {number}
  57286. */
  57287. this.minFilter = LinearFilter;
  57288. /**
  57289. * This flag can be used for type testing.
  57290. *
  57291. * @type {boolean}
  57292. * @readonly
  57293. * @default true
  57294. */
  57295. this.isStorageTexture = true;
  57296. /**
  57297. * When `true`, mipmaps will be auto-generated after compute writes.
  57298. * When `false`, mipmaps must be written manually via compute shaders.
  57299. *
  57300. * @type {boolean}
  57301. * @default true
  57302. */
  57303. this.mipmapsAutoUpdate = true;
  57304. }
  57305. /**
  57306. * Sets the size of the storage texture.
  57307. *
  57308. * @param {number} width - The new width of the storage texture.
  57309. * @param {number} height - The new height of the storage texture.
  57310. */
  57311. setSize( width, height ) {
  57312. if ( this.image.width !== width || this.image.height !== height ) {
  57313. this.image.width = width;
  57314. this.image.height = height;
  57315. this.dispose();
  57316. }
  57317. }
  57318. }
  57319. /**
  57320. * This special type of buffer attribute is intended for compute shaders.
  57321. * It can be used to encode draw parameters for indirect draw calls.
  57322. *
  57323. * Note: This type of buffer attribute can only be used with `WebGPURenderer`
  57324. * and a WebGPU backend.
  57325. *
  57326. * @augments StorageBufferAttribute
  57327. */
  57328. class IndirectStorageBufferAttribute extends StorageBufferAttribute {
  57329. /**
  57330. * Constructs a new storage buffer attribute.
  57331. *
  57332. * @param {number|Uint32Array} count - The item count. It is also valid to pass a `Uint32Array` as an argument.
  57333. * The subsequent parameter is then obsolete.
  57334. * @param {number} itemSize - The item size.
  57335. */
  57336. constructor( count, itemSize ) {
  57337. super( count, itemSize, Uint32Array );
  57338. /**
  57339. * This flag can be used for type testing.
  57340. *
  57341. * @type {boolean}
  57342. * @readonly
  57343. * @default true
  57344. */
  57345. this.isIndirectStorageBufferAttribute = true;
  57346. }
  57347. }
  57348. /**
  57349. * A loader for loading node objects in the three.js JSON Object/Scene format.
  57350. *
  57351. * @augments Loader
  57352. */
  57353. class NodeLoader extends Loader {
  57354. /**
  57355. * Constructs a new node loader.
  57356. *
  57357. * @param {LoadingManager} [manager] - A reference to a loading manager.
  57358. */
  57359. constructor( manager ) {
  57360. super( manager );
  57361. /**
  57362. * Represents a dictionary of textures.
  57363. *
  57364. * @type {Object<string,Texture>}
  57365. */
  57366. this.textures = {};
  57367. /**
  57368. * Represents a dictionary of node types.
  57369. *
  57370. * @type {Object<string,Node.constructor>}
  57371. */
  57372. this.nodes = {};
  57373. }
  57374. /**
  57375. * Loads the node definitions from the given URL.
  57376. *
  57377. * @param {string} url - The path/URL of the file to be loaded.
  57378. * @param {Function} onLoad - Will be called when load completes.
  57379. * @param {Function} onProgress - Will be called while load progresses.
  57380. * @param {Function} onError - Will be called when errors are thrown during the loading process.
  57381. */
  57382. load( url, onLoad, onProgress, onError ) {
  57383. const loader = new FileLoader( this.manager );
  57384. loader.setPath( this.path );
  57385. loader.setRequestHeader( this.requestHeader );
  57386. loader.setWithCredentials( this.withCredentials );
  57387. loader.load( url, ( text ) => {
  57388. try {
  57389. onLoad( this.parse( JSON.parse( text ) ) );
  57390. } catch ( e ) {
  57391. if ( onError ) {
  57392. onError( e );
  57393. } else {
  57394. error( e );
  57395. }
  57396. this.manager.itemError( url );
  57397. }
  57398. }, onProgress, onError );
  57399. }
  57400. /**
  57401. * Parse the node dependencies for the loaded node.
  57402. *
  57403. * @param {Array<Object>} [json] - The JSON definition
  57404. * @return {Object<string,Node>} A dictionary with node dependencies.
  57405. */
  57406. parseNodes( json ) {
  57407. const nodes = {};
  57408. if ( json !== undefined ) {
  57409. for ( const nodeJSON of json ) {
  57410. const { uuid, type } = nodeJSON;
  57411. nodes[ uuid ] = this.createNodeFromType( type );
  57412. nodes[ uuid ].uuid = uuid;
  57413. }
  57414. const meta = { nodes, textures: this.textures };
  57415. for ( const nodeJSON of json ) {
  57416. nodeJSON.meta = meta;
  57417. const node = nodes[ nodeJSON.uuid ];
  57418. node.deserialize( nodeJSON );
  57419. delete nodeJSON.meta;
  57420. }
  57421. }
  57422. return nodes;
  57423. }
  57424. /**
  57425. * Parses the node from the given JSON.
  57426. *
  57427. * @param {Object} json - The JSON definition
  57428. * @param {string} json.type - The node type.
  57429. * @param {string} json.uuid - The node UUID.
  57430. * @param {Array<Object>} [json.nodes] - The node dependencies.
  57431. * @param {Object} [json.meta] - The meta data.
  57432. * @return {Node} The parsed node.
  57433. */
  57434. parse( json ) {
  57435. const node = this.createNodeFromType( json.type );
  57436. node.uuid = json.uuid;
  57437. const nodes = this.parseNodes( json.nodes );
  57438. const meta = { nodes, textures: this.textures };
  57439. json.meta = meta;
  57440. node.deserialize( json );
  57441. delete json.meta;
  57442. return node;
  57443. }
  57444. /**
  57445. * Defines the dictionary of textures.
  57446. *
  57447. * @param {Object<string,Texture>} value - The texture library defines as `<uuid,texture>`.
  57448. * @return {NodeLoader} A reference to this loader.
  57449. */
  57450. setTextures( value ) {
  57451. this.textures = value;
  57452. return this;
  57453. }
  57454. /**
  57455. * Defines the dictionary of node types.
  57456. *
  57457. * @param {Object<string,Node.constructor>} value - The node library defined as `<classname,class>`.
  57458. * @return {NodeLoader} A reference to this loader.
  57459. */
  57460. setNodes( value ) {
  57461. this.nodes = value;
  57462. return this;
  57463. }
  57464. /**
  57465. * Creates a node object from the given type.
  57466. *
  57467. * @param {string} type - The node type.
  57468. * @return {Node} The created node instance.
  57469. */
  57470. createNodeFromType( type ) {
  57471. if ( this.nodes[ type ] === undefined ) {
  57472. error( 'NodeLoader: Node type not found:', type );
  57473. return float();
  57474. }
  57475. return nodeObject( new this.nodes[ type ]() );
  57476. }
  57477. }
  57478. /**
  57479. * A special type of material loader for loading node materials.
  57480. *
  57481. * @augments MaterialLoader
  57482. */
  57483. class NodeMaterialLoader extends MaterialLoader {
  57484. /**
  57485. * Constructs a new node material loader.
  57486. *
  57487. * @param {LoadingManager} [manager] - A reference to a loading manager.
  57488. */
  57489. constructor( manager ) {
  57490. super( manager );
  57491. /**
  57492. * Represents a dictionary of node types.
  57493. *
  57494. * @type {Object<string,Node.constructor>}
  57495. */
  57496. this.nodes = {};
  57497. /**
  57498. * Represents a dictionary of node material types.
  57499. *
  57500. * @type {Object<string,NodeMaterial.constructor>}
  57501. */
  57502. this.nodeMaterials = {};
  57503. }
  57504. /**
  57505. * Parses the node material from the given JSON.
  57506. *
  57507. * @param {Object} json - The JSON definition
  57508. * @return {NodeMaterial}. The parsed material.
  57509. */
  57510. parse( json ) {
  57511. const material = super.parse( json );
  57512. const nodes = this.nodes;
  57513. const inputNodes = json.inputNodes;
  57514. for ( const property in inputNodes ) {
  57515. const uuid = inputNodes[ property ];
  57516. material[ property ] = nodes[ uuid ];
  57517. }
  57518. return material;
  57519. }
  57520. /**
  57521. * Defines the dictionary of node types.
  57522. *
  57523. * @param {Object<string,Node.constructor>} value - The node library defined as `<classname,class>`.
  57524. * @return {NodeLoader} A reference to this loader.
  57525. */
  57526. setNodes( value ) {
  57527. this.nodes = value;
  57528. return this;
  57529. }
  57530. /**
  57531. * Defines the dictionary of node material types.
  57532. *
  57533. * @param {Object<string,NodeMaterial.constructor>} value - The node material library defined as `<classname,class>`.
  57534. * @return {NodeLoader} A reference to this loader.
  57535. */
  57536. setNodeMaterials( value ) {
  57537. this.nodeMaterials = value;
  57538. return this;
  57539. }
  57540. /**
  57541. * Creates a node material from the given type.
  57542. *
  57543. * @param {string} type - The node material type.
  57544. * @return {Node} The created node material instance.
  57545. */
  57546. createMaterialFromType( type ) {
  57547. const materialClass = this.nodeMaterials[ type ];
  57548. if ( materialClass !== undefined ) {
  57549. return new materialClass();
  57550. }
  57551. return super.createMaterialFromType( type );
  57552. }
  57553. }
  57554. /**
  57555. * A special type of object loader for loading 3D objects using
  57556. * node materials.
  57557. *
  57558. * @augments ObjectLoader
  57559. */
  57560. class NodeObjectLoader extends ObjectLoader {
  57561. /**
  57562. * Constructs a new node object loader.
  57563. *
  57564. * @param {LoadingManager} [manager] - A reference to a loading manager.
  57565. */
  57566. constructor( manager ) {
  57567. super( manager );
  57568. /**
  57569. * Represents a dictionary of node types.
  57570. *
  57571. * @type {Object<string,Node.constructor>}
  57572. */
  57573. this.nodes = {};
  57574. /**
  57575. * Represents a dictionary of node material types.
  57576. *
  57577. * @type {Object<string,NodeMaterial.constructor>}
  57578. */
  57579. this.nodeMaterials = {};
  57580. /**
  57581. * A reference to hold the `nodes` JSON property.
  57582. *
  57583. * @private
  57584. * @type {?Object[]}
  57585. */
  57586. this._nodesJSON = null;
  57587. }
  57588. /**
  57589. * Defines the dictionary of node types.
  57590. *
  57591. * @param {Object<string,Node.constructor>} value - The node library defined as `<classname,class>`.
  57592. * @return {NodeObjectLoader} A reference to this loader.
  57593. */
  57594. setNodes( value ) {
  57595. this.nodes = value;
  57596. return this;
  57597. }
  57598. /**
  57599. * Defines the dictionary of node material types.
  57600. *
  57601. * @param {Object<string,NodeMaterial.constructor>} value - The node material library defined as `<classname,class>`.
  57602. * @return {NodeObjectLoader} A reference to this loader.
  57603. */
  57604. setNodeMaterials( value ) {
  57605. this.nodeMaterials = value;
  57606. return this;
  57607. }
  57608. /**
  57609. * Parses the node objects from the given JSON.
  57610. *
  57611. * @param {Object} json - The JSON definition
  57612. * @param {Function} onLoad - The onLoad callback function.
  57613. * @return {Object3D}. The parsed 3D object.
  57614. */
  57615. parse( json, onLoad ) {
  57616. this._nodesJSON = json.nodes;
  57617. const data = super.parse( json, onLoad );
  57618. this._nodesJSON = null; // dispose
  57619. return data;
  57620. }
  57621. /**
  57622. * Parses the node objects from the given JSON and textures.
  57623. *
  57624. * @param {Object[]} json - The JSON definition
  57625. * @param {Object<string,Texture>} textures - The texture library.
  57626. * @return {Object<string,Node>}. The parsed nodes.
  57627. */
  57628. parseNodes( json, textures ) {
  57629. if ( json !== undefined ) {
  57630. const loader = new NodeLoader();
  57631. loader.setNodes( this.nodes );
  57632. loader.setTextures( textures );
  57633. return loader.parseNodes( json );
  57634. }
  57635. return {};
  57636. }
  57637. /**
  57638. * Parses the node objects from the given JSON and textures.
  57639. *
  57640. * @param {Object} json - The JSON definition
  57641. * @param {Object<string,Texture>} textures - The texture library.
  57642. * @return {Object<string,NodeMaterial>}. The parsed materials.
  57643. */
  57644. parseMaterials( json, textures ) {
  57645. const materials = {};
  57646. if ( json !== undefined ) {
  57647. const nodes = this.parseNodes( this._nodesJSON, textures );
  57648. const loader = new NodeMaterialLoader();
  57649. loader.setTextures( textures );
  57650. loader.setNodes( nodes );
  57651. loader.setNodeMaterials( this.nodeMaterials );
  57652. for ( let i = 0, l = json.length; i < l; i ++ ) {
  57653. const data = json[ i ];
  57654. materials[ data.uuid ] = loader.parse( data );
  57655. }
  57656. }
  57657. return materials;
  57658. }
  57659. }
  57660. /**
  57661. * In earlier three.js versions, clipping was defined globally
  57662. * on the renderer or on material level. This special version of
  57663. * `THREE.Group` allows to encode the clipping state into the scene
  57664. * graph. Meaning if you create an instance of this group, all
  57665. * descendant 3D objects will be affected by the respective clipping
  57666. * planes.
  57667. *
  57668. * Note: `ClippingGroup` can only be used with `WebGPURenderer`.
  57669. *
  57670. * @augments Group
  57671. */
  57672. class ClippingGroup extends Group {
  57673. /**
  57674. * Constructs a new clipping group.
  57675. */
  57676. constructor() {
  57677. super();
  57678. /**
  57679. * This flag can be used for type testing.
  57680. *
  57681. * @type {boolean}
  57682. * @readonly
  57683. * @default true
  57684. */
  57685. this.isClippingGroup = true;
  57686. /**
  57687. * An array with clipping planes.
  57688. *
  57689. * @type {Array<Plane>}
  57690. */
  57691. this.clippingPlanes = [];
  57692. /**
  57693. * Whether clipping should be enabled or not.
  57694. *
  57695. * @type {boolean}
  57696. * @default true
  57697. */
  57698. this.enabled = true;
  57699. /**
  57700. * Whether the intersection of the clipping planes is used to clip objects, rather than their union.
  57701. *
  57702. * @type {boolean}
  57703. * @default false
  57704. */
  57705. this.clipIntersection = false;
  57706. /**
  57707. * Whether shadows should be clipped or not.
  57708. *
  57709. * @type {boolean}
  57710. * @default false
  57711. */
  57712. this.clipShadows = false;
  57713. }
  57714. }
  57715. 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, CubeDepthTexture, 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, NoNormalPacking, NoToneMapping, Node, NodeAccess, NodeAttribute, NodeBuilder, NodeCache, NodeCode, NodeFrame, NodeFunctionInput, NodeLoader, NodeMaterial, NodeMaterialLoader, NodeMaterialObserver, NodeObjectLoader, NodeShaderStage, NodeType, NodeUniform, NodeUpdateType, NodeUtils, NodeVar, NodeVarying, NormalBlending, NormalGAPacking, NormalMapNode, NormalRGPacking, 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, R11_EAC_Format, RED_GREEN_RGTC2_Format, RED_RGTC1_Format, REVISION, RG11_EAC_Format, 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_R11_EAC_Format, SIGNED_RED_GREEN_RGTC2_Format, SIGNED_RED_RGTC1_Format, SIGNED_RG11_EAC_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, StorageArrayElementNode, 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号